ajax duplicando div

Question: A função $.ajax está funcionando corretamente, mas o retorno dos dados que estão sendo inseridos dentro da div <#exibeCep> está sendo duplicando quando o usuario clica varias vezes no botão. Tentei usar .remove(), e.preventDefault();, stopPropagation();, bind() e outros, mas nada evitou a duplicidade da div.
O que posso colocar para evitar a duplicação da div ?

Escolha a opção do frete

    $('#buscafrete').click(function(e) {

    e.preventDefault();
    e.stopPropagation();
    cep = $('#cep').val();
    $.ajax({
        type:'GET',
        url: "{% url 'get_frete' %}",
        dataType: "json",
        data: {
            data:cep,
            csrfmiddlewaretoken:'{{csrf_token}}',
        },
        success: function(retorno){

            if(retorno['sedex_cod_error'] == -3 || retorno['pac_cod_error'] == -3){
                $('<input type="radio" name="zipcode" id='+'sedex'+' value='+'CEP de destino invalido'+'/>'+
                    'CEP de destino invalido.'+'').appendTo('#exibeCep');
            }else
                {
                $('<input type="radio" name="zipcode" checked id='+'sedex'+' value='+retorno['Sedex']+'/>'+
                    retorno['Sedex']+' ( '+'Sedex'+' ) '+'').appendTo('#exibeCep');
                $('<input type="radio" name="zipcode" id='+'sedex'+' value='+retorno['Pac']+'/>'+retorno['Pac']+' ( '+'Pac'+' ) '+'').appendTo('#exibeCep');
            }
        },

        error: function(jqXHR, textStatus, errorThrown){
            //alert("FALHOU");
            console.log('Error');
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        },
    });

});

Answer: Crie uma div para receber a resposta Ajax:

Escolha a opção do frete

Então use-á para mostrar a resposta Ajax:
success: function(retorno){
    $('#cepAjax').empty();
    //resto do seu código aqui, usando .appendTo('#cepAjax');

Seguindo minha sugestão acima você irá esvaziar o container da resposta Ajax antes de populá-lo com os elementos gerados a partir da nova resposta.

Ou para evitar que o botão seja clicado várias vezes:
$('#buscafrete').click(function(e) {
   this.disabled = true;

Você pode reabilitá-lo dentro do success/error para permitir mais de uma busca, e combiná-lo com a primeira parte da resposta.
Por fim, fiz uma leve reescrita do seu código, utilizando as sugestões acima e adicionando alguns comentários:
$('#buscafrete').click(function(e) {
    e.preventDefault();
    this.disabled = true; //desabilita o botão após clicado

    var cep = $('#cep').val(); //use "var" para não criar globais
    $.ajax({
        type:'GET',
        url: "{% url 'get_frete' %}",
        dataType: "json",
        data: {
            data:cep,
            csrfmiddlewaretoken:'{{csrf_token}}',
        },
        context: this, //passa a referência "this" do escopo atual para o "this" dos callbacks
        success: function(retorno){
            this.disabled = false; //reabilita botão de busca
            $('#cepAjax').empty(); //esvazia a div de resposta antes de re-popular

            var invalido = retorno['sedex_cod_error'] == -3 || retorno['pac_cod_error'] == -3;

            //refatorei algumas partes comuns do seu if/else para diminuir a repetição
            var $lblSedex = $('<input type="radio" name="zipcode" id="sedex">');
            $lblSedex.find('#sedex').val(invalido ? 'CEP de destino invalido' : retorno['Sedex']);
            $lblSedex.append(invalido ? 'CEP de destino invalido.' : retorno['Sedex']+' ( Sedex )');
            $lblSedex.appendTo('#cepAjax');
            if (!invalido) {
                //Obs.: você tinha IDs duplicados aqui, o que é inválido (o radio do Pac também tinha ID "sedex") então o removi.
                //Verifique se a estilização e comportamento continuam OK
                $('<input type="radio" name="zipcode" value="'+retorno['Pac']+'">'+retorno['Pac']+' ( Pac ) ').appendTo('#cepAjax');
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            //alert("FALHOU");
            this.disabled = false; //reabilita botão de busca
            console.log('Error');
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });

});

Você não tem que seguir a risca o código acima, foi só para demonstrar algumas possíveis melhorias. Caso futuramente você deseje tratar CEPs inválidos de uma forma completamente diferente de CEPs válidos, seria interessante manter o seu if/else original.
Comment: Isso não vai impedir o ajax de ser enviado múltiplas vezes.
Comment: Pelo que entendi a duplicação é na UI, de qualquer forma vou melhorar a resposta agora que vi o HTML.
Comment: Funcionou de primeira !!! Valeu pela ajuda. Obrigado :) Vou estudar oque colocou no codigo pois preciso aprender isso ai. Valeu mesmo
Comment: @Ricardo sem problemas, pode [marcar a resposta como aceita](http://i.stack.imgur.com/uqJeW.png)? Valeu. `=]`
Answer: Ao invés de utilizar o método appendTo, tente utilizar o método .html()
Exemplo:
$("#exibeCep").html('<input type="radio" name="zipcode" id='+'sedex'+' value='+'CEP
                     + 'de destino invalido'+'/>'+'CEP de destino invalido.'+'');

ajax duplicando div


Security of website with user's pages: folders or subdomains?

Question: The client wants to make the site (webservice, as he named it), where users can create their own pages, including  with JS scripts, etc. I see two ways - using the folders:
http://service.com/user/name/ ...

and subdomains:
http://user.service.com/...

Both paths are not the problem, but the client wants to make it using folders for SEO benefits.
I think if I use folders, it will make the site less secure. For example, user can send AJAX request from its page and the server will respond him. If it was a sub-domain, in accordance with the SOP (Same Origin Policy) request would be rejected. Correct if I'm wrong.
Is it real problem with SOP for folders?
Are there any other security issues for folders?
Is it safer to use subdomains?
Comment: Letting users upload their own scripts, pages etc. will lead you to way more security issues than just knowing if they'd better use a subdomain or not..
Comment: Yes, I know that this will be an interesting experience )
Though, it is their own business what they will upload to their pages. I worried about server security with using user's pages. Is it possible to get SOP with folders? Please, tell other problems I might face with.
Answer: Continuing study this issue. As I understood, in case of using folders user also can create page with Black Hat SEO and search Engines will ban my domain. Am I right?
So I can already see 2 security issue in folders and no way to fix it. Are there solutions for it? Are subdomains really more safer or they have other issues?


run java thread continously after it ends

Question: I have a class that runs as a thread, and I would like to run in again once it finishes executing, and possibly, maintain two-three threads of the same class running at the same time (ie. if a thread finishes executing but two are running, only one is run again, and so on).
The code I tried is this:
ExecutorService pool = Executors.newFixedThreadPool( 3 );
while( true )
    pool.submit( new MyThread() );

Any feedback on how this can be achieved?
Update: the class MyThread is actually MyRunnable!
Many thanks,
Vlad
Comment: It is not recommended to start a thread more than once. You can create a new instance of the same thread and start it, but not the same one.
Comment: An `ExecutorService` runs `Runnable`s or `Callable`s, not `Thread`s.  If you can show more of your code maybe we can help.  What are you trying to run repeatedly?
Comment: @andersoj `Thread` is `Runnable`.
Comment: Yah, I got that a Thread is a Runnable but that doesn't mean it's a good idea to have a thing that might be running in its own thread and submitting it to be (confusingly) run in yet another thread by the executor.  (Or more concisely, see @Evgeniy's answer...)
Comment: @andersoj Yes, you are right :)
Answer: try
    final ExecutorService pool = Executors.newFixedThreadPool(3);
    pool.submit(new Runnable() {
        public void run() {
            System.out.println("running1");
            pool.submit(this);
        }
    });

    pool.submit(new Runnable() {
        public void run() {
            System.out.println("running2");
            pool.submit(this);
        }
    });

Comment: wait! I actually tested this throughly  and it stops after the three threads runs, this won't restart after a thread ends
Comment: I changed the test to make it clear which task is actually executed. Seems OK. All tasks run non-stop. You can add task3
Comment: It's cool idea, but this way the `Runnable` object will be the same all the time.
Answer: Use ExecutorCompletionService:
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletionService<Void> compService = new ExecutorCompletionService<Void>(executor);

for(int i = 0; i < 3; i++) compService.submit(new Task(), null);

while(true)
{
    compService.take(); // wait until one of the threads finishes its task
    compService.submit(new Task(), null);
}

Comment: This answer seems to be the exact thing I was looking for, many thanks, appreciate it!


Center Swift Pop-Over on screen

Question: I am currently working on an app that requieres the user profiles to be shown as a pop-over when the user picture is pressed. I managed to get this behaviour using UIPopoverPresentationControllerDelegate but I would like your help entering this pop-over in the middle of the screen.

My code looks like:
    func presentProfile(sender: UIButton){

            let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("profileVC") as! ProfileViewController

            vc.profilePicture =  (self.contentIdToImage[content.hostId as! String]?.image)!

            vc.modalPresentationStyle = UIModalPresentationStyle.Popover

            let height = self.view.bounds.size.height
            let width = self.view.bounds.size.width

            vc.preferredContentSize = CGSizeMake(width * 0.8, height * 0.8)

            if let presentationController = vc.popoverPresentationController {
                presentationController.delegate = self
                presentationController.permittedArrowDirections =  UIPopoverArrowDirection(rawValue: 0)
                presentationController.sourceView = sender

                self.presentViewController(vc, animated: true, completion: nil)
            }

    }

Thank you
Edit:
Based on the first answer I received I started playing around with CGRect and I think the desired behaviour can be achieved using the "sourceRect" property of the UIPopoverPresentationController but I have not figure it out.
Comment: I found the solution to my question here: http://stackoverflow.com/a/31854391/1270603
Answer: set the frame after you set the width & height
  let height = self.view.bounds.size.height
  let width = self.view.bounds.size.width
  vc.preferredContentSize = CGSizeMake(width * 0.8, height * 0.8)
  vc.frame = CGRect(x: CGRectGetMidX(width - vc.bounds.width / 2), y: CGRectGetMidY(height - vc.bounds.height/2), width: width * 0.8,  height: height * 0.8)

Comment: Sorry for the late reply, I did tried this out but it did not work. I found in this post: http://stackoverflow.com/a/31854391/1270603

Center Swift Pop-Over on screen


Tangent space groups of compact manifolds

Question: Reading a review, I have come across this sentence

...of the $SO(D)$ tangent space group of the manifold $K$

after some pages I have found

...for the case of a $D$-dimensional compact manifolds $K$, the tangent space-group is $G_T=SO(1,3+D)$

In both sentences $D$ is the dimensionality of the compact manifold.
I have two main questions:
1)What is a "tangent space-group"
2)is it $SO(D)$ or $SO(1,3+D)$? (Because there must be is a typo in one of the sentences I have cited). And in either case, why is it $SO(D)$ or $SO(1,3+D)$?
Answer: You should be more precise.
$SO(D)$  usually denotes the special orthogonal group in dimension $D$, while
$SO(1,3+D)$ means the group of (orientation preserving) transformations of $\mathbb R^{4+D}$ that preserve the standard bilinear form with signature $(1,3+D)$
the word "tangent space group" may refer to the structure group of the tangent space. This is probably the case if one study metric strucutres, when changes of coordinates are required to preserve some given bilinear form (Euclidean in the $SO(n)$ case, and Minkowsky-type in the case $SO(1,3+D)$)
Comment: the tangent space is a special case of vector bundle http://en.wikipedia.org/wiki/Vector_bundle http://en.wikipedia.org/wiki/Reduction_of_the_structure_group_of_a_bundle
Comment: what is the structure group of the tangent space?
Comment: see also http://en.wikipedia.org/wiki/Structure_group#Structure_groups_and_transition_functions
Comment: I am afraid those links exceed my level of mathematical knowledge, thanks anyway for the info


What happens to the log likelihood when the maximum likelihood estimate does not exist?

Question: What happens to the log likelihood (or indeed the likelihood) function, when the MLE does not exist?
The log likelihood is defined (for independent observations) as
$$l(\boldsymbol{\theta}) = \Sigma_{i=1}^N\text{ln}(P(y_i|\mathbf{x}_i,\boldsymbol{\theta}))$$
where the sum is over the observations, the $y_i$ are the endogenous variable values and the $\mathbf{x_i}$ are the values of the covariates in the ith observation.
The maximum likelihood estimator is
$$\boldsymbol{\theta}^* = argmax_\boldsymbol{\theta} \ l(\boldsymbol{\theta})$$
with a corresponding log likelihood
$$l(\boldsymbol{\theta}^*) = max_\boldsymbol{\theta} \ \Sigma_{i=1}^N\text{ln}(P(y_i|\mathbf{x}_i,\boldsymbol{\theta}))$$
I understand that this may depend on the model, and perhaps even on the covariate distribution. I am particularly interested in the logistic regression with i.i.d. Gaussian covariates, however more general answers or answers for other models/distributions would be most welcome.
Comment: "Does not exist" in what sense?
Comment: Have you reviewed our questions addressing perfect separation? What is it in particular that you would like to know? https://stats.stackexchange.com/search?tab=votes&q=perfect%20separation Is a sufficient answer to your question the observation that the likelihood for some parameter increases as you move towards $\pm \infty$? Why or why not?
Comment: @Tim The data is completely or quasi separated. I believe then the maximum likelihood estimator is on the boundary of the domain (i.e. somewhere at infinity) see thiis paper by Albert and Anderson ,1984 https://www.jstor.org/stable/2336390?seq=1#metadata_info_tab_contents
Comment: The asymptotics do not depend on the log likelihood or existence of MLE for any given set of data (essentially by definition): they depend on the *model.* Are you positing a *model* of complete separation?  If so, the MLE is easy to work out from first principles and from that you can readily derive its asymptotic behavior.  Obviously the log likelihood will almost surely not have a maximum for any dataset of any size in that case.
Answer: In the following linked paper you have a detailed answer: in short, MLE will try to set the estimated coefficients to +/inf, as explained at pag.340-341 of this paper that is a very good suggested reading. If you need practical remedies, and examples/solutions to be implemented in R consider also this answer in addition to the previous text.
And this completes the picture I think.
Comment: Have you read pag. 340-341? What you are asking is explained.. anyway, depending on what exact situation you assume (again see pag 340-341), you can plug the estimate into the likelihood to see what happens to the likelihood.. it is a simple optimization problem where you want to know the value of the function at the asymptotic optimum +-inf. so just plug!! In this case take the limits
Comment: So now I am back.. consider the simplest case as I anticipated: so in light of the previous comment, taking beta =+inf for positive perf sep you have a likelihood that approaches 1, ie a loglik that approaches 0. Since for negative sep you would have a lik that approaches 0 for beta=inf, then just revert the sign and take beta=-inf, and you are back to the case where the lik tends to 1 and the loglik tends to 0 (I.e the likelihood is maximized). Which is why the asymptotic optimal value for the parameter of the relevant variable for the separation would be +-inf for pos/neg perf separation  –
Comment: For more details see the edit with the new link provided
Comment: Your answer seems to concern what happens to the MLE, and not the log likelihood itself! Suppose some coefficients of the parameter vector tend to infinity, and some to minus infinity. Can anything be said about the asymptotics of the log likelihood? I am not particularly concerned with what happens to a programmatical implementation of some MLE finding algorithm. It will, of course, fail to converge to a solution in the parameter space; but what happens to the log likelihood itself?
Comment: @Fri I in fact had been reading these pages, and the only reference to the value of the log likelihood is" Thus, the likelihood function under complete
separation is monotonic, which implies that a finite maximum likelihood estimate does not exist".  From this, I would think it would increase to 0 when there are a discrete set of andogenous variables (i.e. the values y can take); but when you have a continouus distribution the probability density can become arbitraily large, even approach delta spikes, and the log likelihood
Comment: diverges to positive infinty. Either I am being really obtuse and what I have said is rubbish, or the answer really is not as obvious as it is being made out to seem.
Comment: no no you are not obtuse, you made a good point and a good question, that is why i posted a good paper as a reference. You know, the best thing you may have is a paper (possibly good), because you cannot cite as a direct reference for an official document cross validated (which is however a super site)... (to be cont)
Comment: The best thing is to use Cross validated to get 1) a good understanding 2) good references to cite in your official papers/documents/productions,.... That is why, when I can, I prefer to post papers rather than answers. that's the reason.
Comment: Ah OK. But with regards to the understanding, could you verify if you think my interpretation is correct? I cannot find anything stated explicitly regarding this.
Comment: It will depend on the kind of separation you have, if it is partial or perfect and what the variable is predicting, if 0 or 1. Now I am out for dinner (Eu time), so I cannot write too much, but if you try to simulate two samples, one where you have a single predictor that always predict y=1 and another where you have a predictor that predicts y=0, you will see very quickly what happens when you take the limit for beta going to inf, the lik function will try to reach the prob extrema to 1/0


utf8 corrigir texto como remover caracteres estranhos

Question: Boa tarde como uso o utf8 na pagina html para remover caracteres como Refeição que deveria ser Refeição? Obrigado!
Answer: Coloque o código abaixo dentro da sua tag .
<meta charset="utf-8">


Como desenhar uma Ribbon(laço de presente ou etiqueta) em uma div?

Question: Como faço para desenhar esse laço(ribbon) verde no canto superior direito da div central?

Não consegui encontrar uma maneira de faze-lo, alguém poderia me ajudar nisso? Depois da resposta eu posso editar a pergunta para que fique menos centralizada para o meu caso.

.box{
  background-color:red;
}
.box p{
  text-align:center;
  color:white;
}
.box > input{
  margin-left:50%;
}

R$ 180,00

1 mês

  <input type="radio">5

Comment: Jovem preferi remover a resposta por enquanto agora que ficou mais claro o que vc quer. Logo tento te responder com uma opção e edito a resposta que removi
Comment: tranquilo, valeu...
Comment: Ok resposta restaurada depois da uma olhada
Answer:
Só para constar, este tipo de efeito normalmente é chamado de "ribbon", pois lembra um laço de presente, de caixa ou de uso semelhante

Não bastará apenas rotacionar um DIV, teremos que "aparar ele", ou seja, teremos que criar um elemento principal, só usar ::before e ::after não vai funcionar.
Para rotacionar usaremos
transform: rotate(45deg);

Para evitar que o ribbon afete os outros elementos iremos usar quando for clicar ou selecionar algum texto ou elemento, pois o elemento principal acaba ficando maior que o ribbon, mesmo que não possa "enxerga-lo":
pointer-events: none;

Restaura os eventos no conteúdo do ribbon
pointer-events: auto;

E o "principal", para aparar o ribbon usaremos:
overflow: hidden;

O elemento vai ter que ser algo como:

Novo

Note que o seu-elemento se refere ao elemento que deseja aplicar, ele precisa receber:
position: relative;

O efeito deve ficar assim:

Nota: desta forma funciona até mesmo no Internet Explorer 9

.ribbon {
    position: absolute;
    right: 0;
    top: 0;
    width: 100px;
    height: 100px;
    overflow: hidden;
    pointer-events: none; /* impede que o ribbon atrapalhe outros elementos*/
}

.ribbon > .ribbon-content {
    position: relative;
    top: 15px;
    padding: 5px 0;
    background-color: #f00;
    width: 150%;
    transform: rotate(45deg);
    text-align: center;
    box-shadow: 1px 1px 1px rgba(0,0,0,.5);
    pointer-events: auto; /* restaura os eventos somente para o conteudo */
}

/* efeitos somente para teste*/
body {
    background: #cfcfcf;
}

.seu-elemento {
    position: relative;
    width: 200px;
    height: 400px;
    background: #fff;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
}

Novo

Novo

Novo

Answer: Vc pode usar pseudo-elementos ::before e ::after para isso.
No ::before vc usa um linear-gradiente em 45deg, e no ::after vc coloca o content:"novo"
Veja como fica no exemplo:

.container {
 width: 190px;
 height: 160px;
 position: relative;
 border: 1px solid;
 overflow: hidden;
}
.container::before {
 content: "";
 position: absolute;
 top: 0;
 right: 0;
 width: 80px;
 height: 80px;
 background-image: linear-gradient(45deg, transparent 50%, green 50%, green 75%, transparent 75%);
}
.container::after {
 content: "novo";
 position: absolute;
 top: -10px;
 right: -10px;
 width: 80px;
 height: 80px;
 display: flex;
 justify-content: center;
 align-items: center;
 color: #fff;
 transform: rotate(45deg);
}
.box{
 background-color:#999;
  float:left;
}
.box p{
 text-align:center;
 color:white;
}
.box > input{
 margin-left:50%;
}

R$ 180,00

1 mês

  <input type="radio">5

R$ 180,00

1 mês

  <input type="radio">5

R$ 180,00

1 mês

  <input type="radio">5

Answer:

body{
  background-color: #C7C7C7;
}

.wrapper{
  width: 100%;
  max-width: 600px;
  margin: auto;
  font-size: 0;
  padding: 20px;
  box-sizing: border-box;
  text-align: center;
}

.box {
  display: inline-block;
  width: 32%;
  background-color: #FFF;
  margin: 0 2px;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

.etiqueta{
  position: absolute;
  top: 10px;
  right: -30px;
  width: 100px;
  background-color: green;
  color: #FFF;
  font-size: 15px;
  transform: rotateZ(45deg);
}

.box p {
  text-align: center;
  color: #000;
  font-size: 15px;
}

R$ 310,00

1 mês

    <input type="radio">5

Novo

R$ 270,00

1 mês

    <input type="radio">5

Novo

R$ 2900,00

1 ano

    <input type="radio">5

Novo


Is it possible to attach a single field collection to multiple nodes? (And so make updating easier)

Question: Firstly is it possible to attach a single field collection to multiple nodes (so when you opened each node, you'd see the same field collection. If you altered one, they'd all change.)
And secondly, if the answer to the first question is yes, how would you go about doing this? Has anyone ever tried this before?
I've been looking through the database tables and it seems like there's no reason you couldn't just point multiple nodes to one fc, however I can't find anything on the topic.
Brief Example
A quick use case to clarify Geoff's question:
When I create node b, I have the option to populate a field collection from node a rather than a blank field collection.
Editing the field collection on node a, would then also change the value in b.
Comment: do you mean having static data within the field collection (a single field collection whose data is shared across nodes of the same content type)? or sharing a field collection across content types with differing data? the first could be done  with a custom module, the second is already built in to Drupal
Comment: @Geoff The first. I've added an example use case to question to try and add some more clarity to the question!
Comment: Have you already created this data structure? If not, then you probably shouldn't use a field collection. It sounds like the data should be a separate content type that you then connect to the parent nodes with an Entity Reference.
Answer: You have to write custom module for this and use hook_node_presave($node) to save fieldcollection value of other node into this and save node.
Then check your DB, now single fc attached to other node(s).
Answer: I would start it this way:

install Entity Reference to create a reference in B to A
create a reference field in B to let the user choose which node they want to reference, and then use some AJAX to do the initial populate of the field elements based on their selection

This will save B as normal but provide the connection between the two

create a hook_form_alter for node B, such that if a reference exists, load the referencing node and populate the fields in node B with the values from node A

This would allow any node to reference any other node (of the same content type) for value mirroring. This approach is passive, in that it requires node B to be viewed before the values are updated - this behaviour could be changed on the node A save to update the field values in all referencing nodes
If you wanted it to go the other way or be more communal, whereby any node could be manually changed and affect all the other nodes (changing node B also changes node A), it would be a little different, but this is the general idea I would use based on your question.


Solving $\sum_{n=y}^{\infty} {n\choose y}\left(\frac{(1-p)\beta}{\beta + 1}\right)^{n}\frac{\Gamma(n + \alpha)}{n!}$

Question:
Distribution of $Y$ given $Y\mid N \sim \operatorname{Binomial}(N, p)$, $N\mid \Lambda \sim \operatorname{Poisson}(\Lambda)$ and $\Lambda \sim \operatorname{Gamma}(\alpha, \beta)$.

$$f_N(n) = \int_0^{\infty} f_{N, \Lambda}(n, \lambda)\, d\lambda = \int_0^{\infty} f_{N\mid \Lambda}(n\mid  \lambda)f_{\Lambda}(\lambda) \,d\lambda\\= \dfrac{1}{\Gamma(\alpha) \beta^\alpha n!}\int_0^{\infty} \lambda^{n+\alpha - 1} \exp\left( \dfrac{-\lambda}{\beta/(\beta + 1)}\right) d\lambda$$
Using the substitution $t = \dfrac{\lambda}{\beta/(\beta + 1)}$,
$$f_N(n) = \dfrac{\Gamma(n + \alpha) \beta^n}{\Gamma(\alpha)(\beta + 1)^{n + \alpha}n!}$$ for $n = 0, 1, 2,...$
Now,
$$f_Y(y) = \sum_{n=y}^{\infty} f_{Y,N}(y, n) = \sum_{n=y}^{\infty} f(y\mid n)f_N(n) = \sum_{n=y}^{\infty} {n\choose y}p^y(1-p)^{n-y}\dfrac{\Gamma(n + \alpha) \beta^n}{\Gamma(\alpha)(\beta + 1)^{n + \alpha}n!} \\= \left(\dfrac{p}{1-p}\right)^y\dfrac1{\Gamma(\alpha)(\beta + 1)^{\alpha}}\sum_{n=y}^{\infty} {n\choose y}\left(\dfrac{(1-p)\beta}{\beta + 1}\right)^{n}\dfrac{\Gamma(n + \alpha)}{n!}$$

How should I continue from here on?
Comment: I just realized your parametrization of the gamma distribution is by shape and scale, not shape and rate, so your $\beta$ is my $1/\beta$.  Would you like me to change my answer to make it consistent with your parametrization?
Comment: I have edited my answer to use your parametrization and added a little more detail.  In case you want to know about the binomial series expansion that was used, please refer to this link:  https://en.wikipedia.org/wiki/Binomial_series#Special_cases
Comment: Do not use `\dfrac` in titles: https://math.meta.stackexchange.com/q/9687/321264.
Answer: Using the kernels is often useful when working with hierarchical models.  We have
$$f_{\Lambda}(\lambda) \propto \lambda^{\alpha-1} e^{-\lambda/\beta} \\
\Pr[N = n \mid \Lambda = \lambda] \propto e^{-\lambda} \frac{\lambda^n}{n!} \\
$$
hence the unconditional PMF of $N$ is $$\Pr[N = n] \propto \frac{1}{n!} \int_{\lambda=0}^\infty \lambda^{n+\alpha-1} e^{-(1+1/\beta)\lambda} \, d\lambda = \frac{\Gamma(n+\alpha)}{n!(1+1/\beta)^{n+\alpha}}$$
which is the kernel of a negative binomial distribution with parametrization $$\Pr[N = n] = \binom{n+\alpha-1}{\alpha-1} \left(\frac{1}{1+\beta}\right)^\alpha \left(1 - \frac{1}{1+\beta}\right)^n, \quad n \in \{0, 1, 2, \ldots\}$$ or $$N \sim \operatorname{NegativeBinomial}(r = \alpha, \pi = 1/(1+\beta)).$$  So far, this agrees with your calculation.  Then the next step of the hierarchy is
$$\Pr[Y = y \mid N = n] = \binom{n}{y} p^y (1-p)^{n-y},$$ hence
$$\begin{align*}
\Pr[Y = y] &= \left(\frac{p}{1-p}\right)^y \left(\frac{1}{1+\beta}\right)^\alpha \sum_{n=y}^\infty \binom{n}{y} (1-p)^n \binom{n+\alpha-1}{\alpha-1} (1+1/\beta)^{-n} \\
&= \left(\frac{p}{1-p}\right)^y \left(\frac{1}{1+\beta}\right)^\alpha \binom{y+\alpha-1}{\alpha-1} \sum_{n=y}^\infty \binom{n+\alpha-1}{n-y} \left(\frac{1-p}{1+1/\beta}\right)^n \\
&= \left(\frac{p}{1-p}\right)^y \left(\frac{1}{1+\beta}\right)^\alpha \binom{y+\alpha-1}{\alpha-1} \left(\frac{1-p}{1+1/\beta}\right)^y \left(\frac{1/\beta+p}{1+1/\beta}\right)^{-a-y} \\
&= \binom{y+\alpha-1}{\alpha-1} \left(\frac{1}{1+\beta p}\right)^\alpha \left(\frac{\beta p}{1+\beta p} \right)^y, \quad y \in \{0, 1, 2, \ldots\}.
\end{align*}$$
This is a negative binomial distribution with parameters $$r = \alpha, \quad \pi = 1/(1+\beta p).$$
At one point in our calculation, we used the formula for the binomial series
$$(1-z)^{-(m+1)} = \sum_{k=0}^\infty \binom{k+m}{k} z^k.$$  This occurs in the third step of the derivation of $\Pr[Y = y]$ above, with the choice $k = n-y$, $m = y+ \alpha-1$, and $z = \frac{1-p}{1+1/\beta}$, and is where you had stopped in your calculation.


Excel VBA Script to remove the most recent of duplicate records

Question: The worksheet is sorted base on Column A (account number) first and then Column C (date).
I have below script that remove duplicate records and remain the most recent one.
Sub DeleteTheOldies()
Dim RowNdx As Long
For RowNdx = Range("a1").End(xlDown).Row To 2 Step -1
Do While Cells(RowNdx, "a").Value = Cells(RowNdx - 1, "a").Value
If Cells(RowNdx, "c").Value <= Cells(RowNdx - 1, "c").Value Then
Rows(RowNdx).Delete
Else
Rows(RowNdx - 1).Delete
End If
RowNdx = RowNdx - 1
If RowNdx = 1 Then Exit Sub
Loop
Next RowNdx
End Sub

Sample data:

Column A     Column B   Column C
751063031 1605621498 03-JUL-10
751063031 5600003138 18-JUL-10
751063031 5600084443 17-AUG-10
754199715 1605621498 27-FEB-10
754199715 5600084438 17-AUG-10
757129104 5600084892 12-NOV-09
757129104 5600084438 17-AUG-10
757307416 1605621498 27-FEB-10
757307416 5600084438 17-AUG-10

Output of current script:

751063031 5600084443 17-AUG-10
754199715 5600084438 17-AUG-10
757129104 5600084438 17-AUG-10
757307416 5600084438 17-AUG-10

I need a modified version of the script to give the below output (delete the most recent and remain the rests)

751063031 1605621498 03-JUL-10
751063031 5600003138 18-JUL-10
754199715 1605621498 27-FEB-10
757129104 5600084892 12-NOV-09
757307416 1605621498 27-FEB-10
Comment: Your end result is probably easier to accomplish using a database system.
Answer: Try the following.  This will work with your example above.  If you have additional constraints/requirements, it may need to be adjusted.
Sub NewStuff()

    Dim RowNdx As Long
    Dim CurVal As String

    For RowNdx = 1 To Range("a1").End(xlDown)

        If Cells(RowNdx, "a").Value = Empty Then

            Exit For

        End If

        If Cells(RowNdx, "a").Value <> Cells(RowNdx + 1, "a").Value Then

            Rows(RowNdx).Delete
            RowNdx = RowNdx - 1

        End If

    Next RowNdx

End Sub


npm run watch - Exclude file

Question: As part of my build script using Laravel Mix, I'm needing to make a modification to one of the files inside the resources/assets/sass directory. The problem is that running npm run watch will then modify this file and the watcher re-runs the build process, causing an infinite recursive loop.
Is there any way to exclude an individual file from being watched for changes?

For example:
webpack.mix.js
// Do something with `resources/assets/sass/_modules.scss` first, then continue
mix.sass('resources/assets/sass/app.scss');

app.scss
@include "_modules.scss";

Answer: If you're ok with webpack not automatically updating your relative stylesheet URL's, try this:
In webpack.mix.js, add the following option:
processCssUrls: false

Source: https://github.com/JeffreyWay/laravel-mix/blob/master/docs/options.md

npm run watch - Exclude file


R optim() : Why I get negative value for maximum log-likelihood estimation?

Question: I generated set of random proportions using rnorm() function with mean=0.5 and standard deviation = 0.12. I get the below vector of proportions.
[0.59 0.66 0.65 0.67 0.40 0.26 0.46 0.46 0.53 0.66 0.51 0.58 0.45 0.47
0.64 0.62 0.60 0.34 0.40 0.38]
Then I re-estimated the mean and variance using R optim() function. Here, x is the above generated proportions.
foo <- function(par, x) -sum(dnorm(x, par[1], par[2], log=TRUE))

start<- c(0.1,0.1)

x <-c(0.59,0.66,0.65,0.67,0.40,0.26,0.46,0.46,0.53,0.66,0.51,0.58,0.45,0.47,0.64,0.62,0.60,0.34,0.40,0.38)

optim(start, foo, lower=c(0.01,0.01), upper=c(1,1), method="L-BFGS-B", x=x)

The output:
$par
[1] 0.5165004 0.1185091

$value
[1] -14.27772

$counts
function gradient
      55       55

$convergence
[1] 0

$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"

My question is why do  I get a negative $value (-14.27772) for as the maximum value of negative log-likelihood? because log-likelihood suppose to be a negative value so, maximum value of negative log-likelihood has to be a positive isn't it?. Appreciate your comments.
Comment: The log likelihood does not have to be negative for continuous variables.  A Normal variate with a small standard deviation, such as you have, can easily have a positive log likelihood.  Consider the value 0.59 in your example; the log of its likelihood is 0.92.  Furthermore, you want to maximize the log likelihood, not maximize the negative of the log likelihood.  Maximizing the negative of the log likelihood is equivalent to minimizing the likelihood, and why would we want to do that?  As it happens, optim minimizes as its default, so everything worked out for you.
Comment: @jbowman: do you want to post your excellent comment as an answer?
Answer: A couple of points:
The log likelihood does not have to be negative for continuous variables. A Normal variate with a small standard deviation, such as you have, can easily have a positive log likelihood. Consider the value 0.59 in your example; the log of its likelihood is 0.92.  (For discrete variables, it's a different story; unless the probability of one event equals one, all the probabilities will be less than 1, leading to negative logs.)
Furthermore, you want to maximize the log likelihood, not maximize the negative of the log likelihood. Maximizing the negative of the log likelihood is equivalent to minimizing the likelihood, and why would we want to do that? As it happens, optim minimizes as its default, so everything worked out for you - as looking at your parameter estimates and comparing them to the actual parameter values will show.


How to change how WYSIYG styles things?

Question: Instead of using HTML underline tags, I want the WYSIWYG editor (CKEditor) to wrap a span around the highlighted text. Does anyone know how I can achieve this? Thanks!
Answer: Sure see this great blog post titled WYSIWYG Module + CKEditor: Taming the Beast by Fuse Interactive. I am not affiliated with the company nor the author of it -- it's simply a great resource.
Linked in those blog comments is a link to the CKEditor Configuration Options documentation, which is what you'll end up altering to make this happen.
In the blog post they supply their own config settings for the editor in javascript. I believe you can set all these values in hook_wysiwyg_editor_settings_alter, the settings for the Styles look like:
  { name : 'Float Right', element : 'div', attributes : { 'style' : 'float:right;' } },
    { name : 'Float Left', element : 'div', attributes : { 'style' : 'float:left;' } },

Where this defines a style called Float Right that wraps the selected text in a div with some inline styling. I believe you can easily assign classes instead of inline styles as well.
This should be a huge jumping off point for you to figure it all out. Best of luck!
Answer: Go to admin/config/content/wysiwyg/profile/full_html/edit and select "Font Style" then go to the bottom of the page to the "CSS" tab and add Span=span in the "CSS classes" box.
You should now see "Span" in the styles select box on your content edit page.
If you want to give the span a style add Span name=span.name into the "CSS classes" box

How to change how WYSIYG styles things?


Correct notation for the maximum of an indexed set

Question: Which of the following is the correct notation for the maximum of the set $\{a_{i}x^i\mid i\in\{0,\ldots , n\}\}$?
$$\max\limits_{i\in\{0,\ldots , n\}}(a_{i}x^i)
\qquad\text{or}\qquad
\max\limits_{i\in\{0,\ldots , n\}}\{a_{i}x^i\}?$$
I know I could write $\max(\{a_{i}x^i\mid i\in\{0,\ldots , n\}\})$, but I would rather use the notation with the indexing set underneath the $\max$.
Comment: I'd suggest not using brackets at all.
Comment: I honestly think they are both rather clear and understandable.
Comment: There are some related questions on Math SE:  [\[1\]](https://math.stackexchange.com/questions/40861/mathematical-notation-for-the-maximum-of-a-set-of-function-values) and  [\[2\]](https://math.stackexchange.com/questions/3332276/notation-for-maximum-over-an-arbitrary-total-order).  Neither of these is quite an exact duplicate, but maybe one of them answers your question?
Answer: Short Answer:  Either of the suggested notations is "correct", in the sense that both are likely to be understood without confusion.  My preference would be to write
$$ \max_{i\in\{1,\dotsc,n\}} a_i x^i, $$
with no extra brackets or parentheses.
Discussion:  A lot of folk get really hung up on what is "correct" notation.  The reality is that there really isn't any such thing, at least not in a any universal sense.  The goal of mathematical notation is to clearly and unambiguously communicate an idea.  Any notation which does this is "correct".
In the example given above, the goal is to clearly denote the maximum element of a collection of terms of the form $a_i x^i$, where $i$ ranges over a set of integers between $1$ and $n$.  Each of the notations suggested in the question seem fine with respect to clearly conveying this idea.
Some additional thoughts:

My preference would be to write
$$ \max_{i \in \{1,\dotsc,n\}} a_i x^i. $$
That is, I think that the notation looks much better without any kind additional brackets.  The expression you are trying to maximize is short and unambiguous, so I don't think that there is any difficulty here.

You could just as easily write
$$ \max_{i\in\{1,\dotsc,n\}} \left(a_i x^i \right).$$
In this particular case, I think that the parentheses are a little redundant, but they don't get in the way.  On the other hand, if you are maximizing a more complicated expression, they may help.  For example, if I write
$$ \max_{i\in \{1,\dotsc,n\}} a_i x^i + 1,$$
do I mean "maximize the expression $(a_ix^i + 1)$", or "maximize the expression $a_i x^i$, and then add $1$"?  In this case, the notation
$$ \max_{i\in\{1,\dotsc,n\}} \left(a_i x^i + 1\right)$$
is an improvement.

Personally, I don't like the notation
$$ \max_{i\in \{1,\dotsc,n\}} \left\{ a_i x^i \right\}. $$
There is nothing really wrong with it, but I find it unaesthetic.  If I am going to write $\max A$, where $A$ is some set, I would like to completely specify the set $A$.  I don't like the specification of indices under the $\max$ operator, with the set only partially specified after.  In this case, I would rather write
$$ \max \left\{ a_ix^i : i \in \{1,\dotsc,n\} \right\}. $$
Again, let me be clear:  this is entirely a matter of taste.  If you like the notation $\max \{a_i x^i\}$, then there is absolutely nothing wrong with it.


Buscar detalhes de um livro com Google Books API em PHP

Question: Estou a usar a API do Google books para ir buscar os detalhes de um livro:
E para ir buscar os detalhes de um livro, ao pesquisar pelo nome, estou a usar o seguinte exemplo fornecido por eles, deste caso o ficheiro simple-query.php dentro da pasta examples.
O que acontece é que só consigo fazer a pesquisa por autor de livros ao chamar esta função:
$results = $service->volumes->listVolumes('Catarina Coelho', $optParams);

Como posso fazer a pesquisa pelo nome do livro? Não encontro nenhuma referência a fazer a pesquisa pelo nome do livro.
Como não consegui fazer pelo modo de cima, encontrei um exemplo na internet, mas a pesquisa é feita pelo o URL
https://www.googleapis.com/books/v1/volumes?q=Memoria+historia+da+provincia+de+Santa+Catharina

Se usar esta solução pela URL, como posso ir buscar o resultado pelo código e ficar guardado dentro de uma variável/array?
Answer: Podes ler os dados por JSON e assim manipular da forma que entenderes:
<?php
$page = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=Memoria+historia+da+provincia+de+Santa+Catharina");

$data = json_decode($page, true);

echo "Title = " . $data['items'][0]['volumeInfo']['title'];
echo "
Authors = " . @implode(",", $data['items'][0]['volumeInfo']['authors']);
?>

Aqui esta um exemplo para ires buscar o Title e Authors do livro.
Answer: Na seção Performing Search, diz-se que é possível especificar o nome do livro (ou parte dele) usando o parâmetro intitle. Por exemplo:
http https://www.googleapis.com/books/v1/volumes?q=intitle:Cem+Anos+de+Solidao

Resposta:
{
 "kind": "books#volumes",
 "totalItems": 17,
 "items": [
  {
   "kind": "books#volume",
   "id": "iPxztgAACAAJ",
   "etag": "2jx8ktgU3G8",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/iPxztgAACAAJ",
   "volumeInfo": {
    "title": "Cem anos de solidão",
    "authors": [
     "Gabriel García Márquez"
    ],
    "publishedDate": "1973",
    "industryIdentifiers": [
     {
      "type": "OTHER",
      "identifier": "OCLC:6522501"
     }
    ],
    "readingModes": {
     "text": false,
     "image": false
    },
    "pageCount": 364,
    "printType": "BOOK",
    "contentVersion": "preview-1.0.0",
    "language": "en",
    "previewLink": "http://books.google.com.br/books?id=iPxztgAACAAJ&dq=intitle:Cem+Anos+de+Solidao&hl=&cd=1&source=gbs_api",
    "infoLink": "http://books.google.com.br/books?id=iPxztgAACAAJ&dq=intitle:Cem+Anos+de+Solidao&hl=&source=gbs_api",
    "canonicalVolumeLink": "http://books.google.com.br/books/about/Cem_anos_de_solid%C3%A3o.html?hl=&id=iPxztgAACAAJ"
   },
   "saleInfo": {
    "country": "BR",
    "saleability": "NOT_FOR_SALE",
    "isEbook": false
   },
   "accessInfo": {
    "country": "BR",
    "viewability": "NO_PAGES",
    "embeddable": false,
    "publicDomain": false,
    "textToSpeechPermission": "ALLOWED",
    "epub": {
     "isAvailable": false
    },
    "pdf": {
     "isAvailable": false
    },
    "webReaderLink": "http://books.google.com.br/books/reader?id=iPxztgAACAAJ&hl=&printsec=frontcover&output=reader&source=gbs_api",
    "accessViewStatus": "NONE",
    "quoteSharingAllowed": false
   }
  }
 ]
}

Answer: Tente usar esse código:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    'Step 1:- google API url responsible for returning the book detail in JASON format
    Const GOOGLEAPIURL As String = "https://www.googleapis.com/books/v1/volumes?q=”"

    If txtISBN.Text <> String.Empty Then
        Dim requestURL As String

        'Step 2:- Reformed the URL to target particular ISBN number
        requestURL = GOOGLEAPIURL + txtISBN.Text() + "+isbn"

        'Step 3: created Http webrequest for URL
        Dim wr As HttpWebRequest = HttpWebRequest.Create(requestURL)
        'Step4 : get the response of web request in http web response object
        Dim resp As HttpWebResponse = wr.GetResponse()

        'Step 5: passes the response stream in stream reader
        Dim sreader As New StreamReader(resp.GetResponseStream())
        'Step 6: parsing the reader(which is in Jason format) using JASON.NET

        Dim rss = JObject.Parse(sreader.ReadToEnd())

        'Step 7: if object find the fetch the detail

        If rss Is Nothing = False AndAlso rss.Count > 0 Then
            lblBookName.Text = rss.Item("items")(0).Item("volumeInfo").Item("title").ToString()
            lblAuthor.Text = rss.Item("items")(0).Item("volumeInfo").Item("authors").ToString().Replace("[", "").Replace("]", "").ToString()
            lblPublisher.Text = rss.Item("items")(0).Item("volumeInfo").Item("publisher").ToString()
        Else
            lblMessage.Text = "Sorry ISBN Number not found, Please try different number."
        End If
    Else
        lblMessage.Text = "Please enter the ISBN number"
    End If
End Sub

Comment: A linguagem do OP é php, e esse código sugerio em VB.


What is the interpretation of the negative value for the Normalized Mean Absolute Error (nMAE) metric?

Question: I am using the normalized mean absolute error metric for evaluating my results. The data I use is in time-series form. Their trend may be increasing or decreasing over time. All the values are positive at first and in different scales and ranges. I standardized my data in this form: first and for all samples, subtracting each time point from its baseline value and then divided them by the std of the baseline values(of all samples). Then, using the NMAE formula for my prediction. But now, I am getting some negative values for the normalized mean absolute error metric. I don't know what does it mean?
Comment: "subtracted each time point from their baseline values and then divided them by the std. of the baseline values"  - at what point did you change these values (which will be positive and negative) to absolute values?
Comment: I have used this formula as the metric: \begin{equation}
        NMAE = \frac{\sum_{i=1}^{N} \mid Y_{pred}-Y_{real} \mid}{\sum_{i=1}^{N} Y_{real} } \end{equation}
Comment: The negative value for this metric depends on the denominator of the NMAE formula. I think after the standardization (described above), there could be appeared some negative values in the data and their summation as well. Now, I don't know the interpretation of the negative value for this metric? From the MAE we know as much as it is closer to the zero, the model performance is more acceptable. Should I consider this metric's absolute value as well and interpret it similarly?
Comment: If your Y_real values aren't all positive, this measure isn't appropriate. Use MAE, although that still gives you the problem of comparing across series.
Comment: One possible way to deal with this would be to standardize each series around a mean of 500 and a standard deviation of 100, so all the values would be positive. [picking 500 and 100 is arbitrary -- that's just the idea behind SAT college scores]
Comment: Yes, after standardization, some of the Y_real may get negative values!
Comment: What does "$Y_{real}$" refer to?  Actual data or standardized data?  If standardized, then you're going about this all wrong--your results are arbitrary and dependent on the standardization--and you should be asking a different question about how to evaluate your results appropriately.
Answer: You could use the absolute values of Yreal, since the interest here is the magnitude of MAE with respect to the magnitude of actual values (independently of the sign).
Answer: The comments give the normalized mean absolute (NMAE) error as follows.
$$
NMAE = \dfrac{
\overset{N}{\underset{i = 1}{\sum}}\left\vert
Y_{pred} - Y_{real}
\right\vert}{
\overset{N}{\underset{i = 1}{\sum}}Y_{real}
}
$$
Since the numerator is a sum of absolute values, the numerator cannot be less than zero. Consequently, if the overall $NMAE$ is less than zero, then the denominator must be less than zero, meaning that these $Y_{real}$ values must have an arithmetic mean (the usual mean) less than zero. That does not tell me much, but if you know the way you have constructed the $Y_{real}$ precludes a mean below zero, then this would be an indication of a bug in your implementation code that needs to be fixed.
Other than that, I do not see much that can be concluded, though I have my doubts that the given formula represents a useful calculation. Sure, we can write a software function to perform the calculation, stick data into the function, and get a result, but I do not see a reason to care about such a calculation. The searching I have done for normalized mean absolute error seems to put an absolute value in the denominator.
$$
NMAE = \dfrac{
\overset{N}{\underset{i = 1}{\sum}}\left\vert
Y_{pred} - Y_{real}
\right\vert}{
\overset{N}{\underset{i = 1}{\sum}}\left\vert Y_{real}\right\vert
}
$$
I am not even so sold on this being especially useful, unless you can put it in the context I discuss here where the $Y_{real}$ have a mean (maybe median for absolute errors instead of squared) of zero, but this formula definitely cannot yield values less than zero.


Storing and retrieving a complex type in UWP

Question: I have an Object which is an ObservableCollection<T>. Type T has int, string, bool, PropertyChangedEventHandler, Visibility and ObservableCollection objects.
What is the best way to store my T object as the app closes, then retrieve it when the app is opened again?
Answer: You're going to want to use DataContract and DataContractSerializer
Let's create our serializable class
    public class MySerializableObject
    {

         public int age {get; set;}

         public string name {get; set;}

         public bool isAwesome {get; set;}

    }

This class the way it is won't serialize. We need to add some attributes in to make it work.
    [DataContract]
    public class MySerializableObject
    {

          [DataMember]
          public int age {get; set;}
          [DataMember]
          public string name {get; set;}
          [DataMember]
          public bool isAwesome {get; set;}

    }

Now that we have added in DataContract above the class and DataMember above our properties, they will be serializable.
Then you can use DataContractSerializer to serialize or deserialize your data
The below code is out of my personal library. It works.
    public static void SaveObject(SerializeableObject value)
    {
        Serialize(value, new FileStream(ApplicationData.Current.RoamingFolder.Path
            + @"\" + value.objectName + ".russ", FileMode.OpenOrCreate));
    }

    public static Object GetObject(string objectName, Type targetType)
    {
        return Deserialize(new FileStream(ApplicationData.Current.RoamingFolder.Path
           + @"\" + objectName + ".russ", FileMode.OpenOrCreate), targetType);
    }

    private static void Serialize(SerializeableObject objectToSerialize, FileStream stream)
    {
        try
        {
            DataContractSerializer serializer = objectToSerialize.GetSerializer();
            serializer.WriteObject(stream, objectToSerialize);
            stream.Dispose();
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to Serialize");
            Debug.WriteLine(ex.Message);
        }
    }

    private static Object Deserialize(FileStream stream, Type targetType)
    {
        Object returnValue = null;
        try
        {
            DataContractSerializer serializer =
                  new DataContractSerializer(targetType);

            stream.Position = 0;
            returnValue = serializer.ReadObject(stream);
            stream.Dispose();
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to Deserialize");
            Debug.WriteLine(ex.Message);
        }
        return returnValue;
    }

Here are the objects I am using in the above code
    [DataContract]
    public class TestSave : SerializeableObject
    {
        [DataMember]
        public string objectName
        {
            get;
            set;
        }

        [DataMember]
        public bool SaveTestProp { get; set; }

        public DataContractSerializer GetSerializer()
        {
            return new DataContractSerializer(typeof(TestSave));
        }
    }

    public interface SerializeableObject
    {
        string objectName { get; }
        DataContractSerializer GetSerializer();
    }

Comment: I had to make some changes to the code to fit my needs, but you showed me the right direction to solving the problem. :^)
Comment: Will [DataMember] work even if it's a complex property? As I have said, there is another ObservableCollection inside type T, a Visibility and a PropertyChangedEventHandler.
Comment: Make those object's members serializable too and it will work
Comment: @WashingtonA.Ramos please look at my updated answer. It's now compiled and tested.


Weak Convergence to Exponential Random Variable

Question: Assume that $X_1$, $X_2$,... are independent random variables uniformly distributed on $[0,1]$. Let $Y^{(n)}=n\inf\{X_i,1\leq i\leq n\}$. I am asked to prove that it converges weakly to an exponential random variable, i.e. for any continuous bounded function $f:\mathbb R^{+}\rightarrow\mathbb R$,
$\displaystyle \mathbb E\left(f(Y^{(n)})\right)\xrightarrow[n\rightarrow\infty]{}\int_{\mathbb R^{+}}f(u)e^{-u}du$
Definition: A sequence of distribution functions is said to converge weakly to a limit $F$ (written $F_n\Rightarrow F)$ if $F_n(y)\rightarrow F(y)$ for all $y$ that are continuity points of $F$. A sequence of random variables $X_{n}$ is said to converge weakly or converge in distribution to a limit $X_{\infty}$ (written $X_n\Rightarrow X_{\infty}$) if their distribution functions $F_n(x)=\mathbb P(X_n\leq x)$ converge weakly.
Answer: Weak convergence is equivalent to cdf convergence at all continuity points of the limiting cdf. In this case it is easier to look at the complementary problem:
\begin{align*}
P(Y^{(n)} > y) &= P\left( \inf_{1 \leq i \leq n}{X_i} > \frac{y}{n} \right)\\
               &= P\left( \text{Every $X_i$ is greater than } \frac{y}{n} \right) \\
               &= P\left(X_1 > \frac{y}{n} \right)^n  \quad \text{by iid-ness} \\
               &= \left( 1 - y/n\right)^{n} \quad \text{for $n$ large enough}
\end{align*}
Which converges to $e^{-y}$ which is exactly what we want.
Comment: Beautiful! Thanks Bunder.
Comment: Why is $P(X_{1}>\frac{y}{n})^{n}$ equal to $(1-y/n)^{n}$ and not $1-(y/n)^{n}$? If instead it were $P(M_{1}>1-\frac{t}{n})^{n}$, would it equal $(1-1-\frac{t}{n})^{n}$?
Comment: $X_1$ is uniformly distributed in $[0,1]$. So $P(X > x) = 1 - x$ for every $0 \leq x \leq 1$. The probability $1 -(y/n)^n$ can be interpreted as $$1 - P(X_1 < y/n)^n = 1 - P(\text{All } X_i < y/n) = P(\text{At least one } X_i \geq y/n) = P(\sup X_i > y/n)$$
which is not what we look for.


Find the following one-sided limits?

Question: $$\text{a)} \ \  \lim_{x\to-2^+}(x+3)\frac{|x+2|}{x+2}$$
$$\text{b)} \ \  \lim_{x\to-2^-}(x+3)\frac{|x+2|}{x+2}$$
The answers are:
$$\text{a)} \ \  1$$
$$\text{b)} -1$$
How do you find them? It is certain that if you insert $-2$ in the first problem then you get the limit 1, but that's not true for the second one. How do I find both limits algebraically?
Answer: Hint :
$$|x+2| =
\begin{cases}
-(x+2), & \text{if } x<-2 \\
x+2, & \text{if }x \ge -2
\end{cases}$$
Answer: for a), you can replace the absolute value of the function $f(x)=x+2$ with the function itself, since approaching $-2$ from above means the function inside is positive and we know that $|f(x)|=f(x)$ whenever $f(x)\geq 0$ so
$$
\lim_{x\to-2^+}(x+3)\frac{|x+2|}{x+2}=\lim_{x\to-2^+}(x+3)\frac{x+2}{x+2}=\lim_{x\to-2^+}(x+3)=1
$$
use the same logic for part b.
Answer: So lets have a look at a). Naturally the troublesome part is $\frac{|x+2|}{x+2}$. Now since we approach -2 from the right we know that $x>-2$. Thus $\frac{|x+2|}{x+2} = \frac{x+2}{x+2} \to 1$ as $x \to -2^+$. Using that the limit of a product is the product of the limits we have that:
$$\lim_{x \to -2^+} (x+3)\frac{|x+2|}{x+2} = 1 \cdot 1 =1$$.
Now try the other using this technique.

Find the following one-sided limits?


How To Merge User Main Photo in Image?

Question: Hello facebook developers can any one help me a quick summary how can user photo merge in background image which i provided?
I already try the text and its working.
EDIT:
Hello Here Is Some Code I Got: where $name is " name of the user" i made it correct.
<code>       $canvas = imagecreatefromjpeg ("bg.jpg");
       $black = imagecolorallocate( $canvas, 61, 61, 61 );
       $font = "font.ttf";
       imagettftext( $canvas, 15, -1, 51, 60, $black, $font, $name );

       imagejpeg( $canvas, "img/".$fbid.".jpg", 50 );
       ImageDestroy( $canvas );
</code>
and now my problem is how to include the photo of the user in the background?
Comment: Your question is not really helpful. Have you tried something before? Can you post some Code?
Comment: @Stony i added some codes i got without merging picture of user... can you help me...
Answer: In order to accomplish this, you'll need to make use of ImageMagick for PHP: http://php.net/manual/en/book.imagick.php.

<code>$img1 = new Imagick( "YOUR_BACKGROUND.png" );
$img2 = new Imagick( "FB_IMAGE.png" );

$img1->compositeImage( $img2, imagick::COMPOSITE_COPYOPACITY, 0, 0 );

header('Content-type: image/png');
echo $img1;

?>
</code>
Good luck!

How To Merge User Main Photo in Image?


Shared text document where users can type in realtime Swift IOS

Question: My goal is to create a text view where two users can type at the same time in a text document (for example UITextView). I am currently using firebase as my database.
One way one could implement this is to update a document all the time from firebase with listeners attached to it that update the text. This approach isn't very practical and can cause confusion right away when one internet connection is poor.
Is it possible to create a shared text document in Swift where two users can type? And is there a more convenient approach to it than mine?
Comment: I don't think this is a good question for SO. Asking if something *is possible* is broad. Sure, it's possible but that's not really an answer. The other issue is we don't know the entire use case, for example *two users can type* - sure, that's easy. But what are the requirements? User A types Hello and user B types Goodbye - who wins? Please take a moment and review [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). In the future, post CODE related questions.
Answer: What you're describing is essentially what Firepad does on the web.
You could consider using its source code as the basis for your solution, paying special attention to the operation transform implementation in there, which is what makes its multi-user editing of a single document possible.


preg_replace not work on server as localhost?

Question: I am replacing words matching with '##' in $newstring, This replaces all words on localhost
successfully but ignores many words when I run this code on a live server.
Any suggestions what may be causing this or how I could go about fixing it?
  for($i=0;$i<count($result);$i++)
      {
       $commanword = trim(strtolower($result[$i]['Words']));
       $newstring = preg_replace("/\b".$commanword."\b/i", '##', $newstring);
      }

Comment: This calls for basic debugging first. What do `$commanword` and `$newstring` contain when you run it on the server?
Comment: $commanword have words like 'a','an','the','was'        and $newstring have string  i want remove common words from string
Comment: both variables having same values on server And local when i am tested
Answer: Try this:
for($i=0;$i<count($result);$i++)
  {
   $commanword = trim(strtolower($result[$i]['Words']));
   $pre = "/\\b" . $commanword . "\\b/i";
   $newstring = preg_replace($pre, '##', $newstring);
  }

Answer: Try this:
foreach($result as $r) {
  $commanword = trim(strtolower($r['Words']));
  $newstring = preg_replace("/\\b$commanword\\b/i", '##', $newstring);
}

There's some stylistic changes in there.  (I'd like a better name for $r, but I have no idea what it represents).  The substantive change though is that you're missing a backslash on the '\b' patterns.  The interpretation of the double-quoted string turns "\b" into "b" before it goes to the regular expression function.
Comment: $newstring = preg_replace("/\\b$commanword\\b/i", '##', $newstring); is again not work on server but work on local
Comment: it may be problem by preg_replace
Answer: hey friends i have fixed it.
 it's problem of PCRE (Perl Compatible Regular Expressions) Supportdisabled on our server now it work on server when i make it enable Thanks both of you mc0e and Joran Den Houting
Comment: Which is the configuration file to enable this?


Most powerful test for deciding probability mass function

Question: Let $X$ be an integer valued random variable supported on $\{0.1.2...,12\}$ whose pmf is either $g(x)=1/13; x=0,1,...,12$ or
$ f(x)=\dfrac x {36} 1_{\{0,1,...,6\}} + (\dfrac 13 - \dfrac x{36})1_{\{7,8,...,12\}}; x =0,1,...,12$. (where $1_A$ denotes the indicator function of a set $A$)
On the basis of one single observation $X$, how to construct the most powerful test of
$H_0: $ pmf of $X$ is $f$ vs. $H_1:$ pmf of $X$ is $g$ , at a $0.25$ level of significance ?
I don't know, have never encountered, testing  hypothesis for pmf before ... I have only known testing hypothesis for parameter.
A detailed solution of this, with some relevant reading material will be much appreciated.
Thanks in advance.
Comment: Even then, please add self-study.  Also, please tell us what you have tried so far.
Comment: The distribution is fully specified under both models, so you can directly calculate likelihood of any observation under null and alternative and so calculate the likelihood ratio as a function of $x$. Indeed since the null is uniform, one can proceed directly from inspection of the alternative. Consequently, the form of the rejection region (in terms of $x$) is obvious - the only question is where the boundary is placed, which is determined by $\alpha$ (keeping in mind that the location of the cutoff is determined under the null)
Comment: @StubbornAtom: not homework but a past exam question ...
Comment: @StatsStudent: as I said ... I only know how to use Neyman-Pearson for parameter hypothesis testing ... I don't know how to apply N-P to test pmf or pdf hypothesis ...
Answer: Recall the construction of most powerful test using the fundamental Neyman-Pearson lemma.
Consider the problem of testing a simple null against a simple alternative, namely $$H_0:X\sim f_0\quad\text{ vs }\quad H_1:X\sim f_1\,(\ne f_0)$$
, where $X$ is a random variable/vector, $f_0$ (or $f_{H_0}$) is the null distribution which is completely specified, and $f_1$ (or $f_{H_1}$) is the alternative distribution which is also completely specified.
Then any test $\varphi$ of the form
$$\varphi(x)=\begin{cases}1&,\text{ if }f_1(x)>kf_0(x)\\ \gamma&,\text{ if }f_1(x)=kf_0(x)\\0&,\text{ if }f_1(x)<kf_0(x)\end{cases}$$
where $\gamma\in(0,1)$ and $k>0$ are such that $\varphi$ is of size $\alpha$, is a most powerful size $\alpha$ test for testing $H_0$ against $H_1$.
Since you are familiar with hypothesis testing of parameters using N-P lemma, the above would not come as much of a surprise. After all, if your distribution $f$ was indexed by the parameter $\theta$ you would do the same thing for testing, say, $H_0:\theta=\theta_0$ vs $H_1:\theta=\theta_1\,(\ne\theta_0)$. In that case, $f_0$ becomes $f_{\theta_0}$ and $f_1$ becomes $f_{\theta_1}$.

To get you started, let $f$ be the pmf of $X$.
Since both the null and alternative distributions are discrete, a most powerful level $\alpha=0.25$ test for testing $H_0$ against $H_1$ is simply of the form
$$\varphi(x)=\begin{cases}1&,\text{ if }x\in E\\0&,\text{ otherwise }\end{cases}$$
, where $$E_{H_0}\varphi(X)\le 0.25$$
To choose the set of points in $E$, compute the likelihood ratio $\lambda(x)=\frac{f_{H_1}(x)}{f_{H_0}(x)}$ for each $x$, and write the different values of $\lambda(x)$ in decreasing order (because we reject $H_0$ for large values of $\lambda(x)$).
For this question, the order looks something like $$\lambda(0)=\lambda(12)>\lambda(1)=\lambda(11)>\ldots\tag{*}$$
The critical region $E$ would consist of sample points taken according to the preference rule $(*)$. So here $0,12$ would be the first values to enter into $E$, and so on until $E_{H_0}\varphi(X)$ exceeds $0.25$.
[The test $\varphi$ might not be an exact size $\alpha$ test, in which case you would have to use randomisation.]
Comment: as I said ... I only know how to use Neyman-Pearson for parameter hypothesis testing  ... could you please add some reference as to where to find application of N-P to test pmf or pdf hypothesis ?
Comment: @user521337 This is a direct application of N-P lemma and is a more general question than testing of parameters. So I would guess a standard mathematical statistics textbook would discuss these problems, worked out or as exercise.  If you are testing say, $H_0:\theta=\theta_0$ vs $H_1:\theta=\theta_1 (\ne \theta_0)$, you would use the ratio $\lambda(x)=f_{H_1}(x)/f_{H_0}(x)=f_{\theta_1}(x)/f_{\theta_0}(x)$. Does this look more familiar?
Comment: @user521337 I have updated my answer a little to focus on this particular exercise. Let me know if things are not clear.
Comment: thank you for your solution here very much ... could you also possibly take a look at these two questions https://stats.stackexchange.com/questions/386254/on-a-bayesian-hypothesis-testing   and  https://stats.stackexchange.com/questions/386815/solution-verification-for-a-hypothesis-testing-question


Block an IPv6 Address where only whitelisting is available

Question: Came across a use case where I need to block an IPv6 address from accessing a site. It is fairly simple to block an IPv4 address by skipping the specific address from the whitelist range. Does any one know how to do a similar thing with the IPv6 address or is it even possible?
PS: Whitelisting is the only option I have, no blacklisting option. I am not very good with the networking concepts of IPv6 address so please consider the question as a newbie question. I can edit the question to include more details to make the question more comprehensible. I am using Salesforce experience cloud sites to set more context to the question.
Comment: That's probably not doable.
Answer: Its probably doable, but it would probably require about 64 whitelist rules to block a certain address.
So before you are going there, I would ask myself if there is a better way to do it, for example - implement this filtering somewhere else along the way. if you have control on a proxy along the way or the service itself and add some specific logic to the service.
Assuming you have to, I would start by saying that you are probably safe by blocking the entire /64 subnet to which the blocked IP belongs, so if your blocked IPv6 address is 2001:4860:4860::8888 you can be safe with blocking 2001:4860:4860:0000/64 (normally written as 2001:4860:4860::/64)
The reason is that /64 subnets are normally the smallest subnet that is used to represent a physical site (NAT is not needed for IPv6), so anything else within this site is safe to block.
You can also reduce your problem to allow only the 2000::/3 (everything that start with hex digit 2 or 3) because these are all the Global Unicast addresses (Read here about GUA addresses)
So basically you want to allow everything in 2000::/3 apart from 2001:4860:4860::/64
The remaining problem is not related to IPv6, its more about binary arithmetics.
you need to do something like this:
for simplicity, let's say we have an 8 bit address that is 0x34 which we want to block but allow the remaining address space, 0x34 is binary 0011:0100b.
So here is a procedure to do that:
let's mark the whole 8 bit space as xxxx:xxxx we split it to two:

0xxx:xxxx
1xxx:xxxx

0011:0100 belongs to (1), so we can allow the complete 1xxx:xxxx
now we have a problem with 0xxx:xxxx, split that to get

00xx:xxxx << blocked number is here
01xx:xxxx

so we can also allow 01xx:xxxx
and again, the problem i not 00xx:xxxx, split that to get

000x:xxxx
001x:xxxx << blocked number is here

so we can allow 000x:xxxxx
and so on until you are left with exactly the blocked address.
Comment: @GalWeiss Thank you for the suggestions, I think that might work maybe for cases where we have proxy, not quite sure. Although for my specific use case in Salesforce we don't have a way to use proxy - was checking this and hence the delay for response. Also, adding so many (64 whitelist) won't be feasible. So in summary I would conclude it is not doable.
Comment: I like your idea with the binary unblocking (although it does really not scale well if you have multiple addresses to blacklist), so have an upvote. But I disagree with the notion that "/64 subnets normally represent a physical site." A /64 is the smallest "normal" subnet in IPv6, and a site _should_ be a /48, but can be smaller, like /56 or even /60 (for residential sites). Whoever gets a single /64 for their home network from their ISP should complain.
Comment: @Dubu, thanks for the clarification, that's a fair point, what I meant to say is that a single site would be represented by *at least* a /64 network, since the solution I propose becomes simpler the larger the site you are looking to block. so the solution will take at most 60-61 whitelist rules for a single site blocked.
It doesn't scale very well of course, since this is a terrible way to implement blocking. The only reason I went with suggesting a solution is because vidarlo wrote that this is probably not doable, So I thought "hmm .... challenge accepted" :)
I'll fix my answer.


python isn't accepting my variable

Question: #dating sim
energy = 10
flirtpower = 5
print ('welcome to Paragonia dating simulator!')
print ('it is a sunny day at the end of the summer. You are new to
Paragonia Highschool.')
print ('A cute blonde boy walks up to you. he says:')
name = int (input ("what's your name?"))
print ('-Nice too meet you, ' name ,'! My name is Alex, Alex Snowdon.
He smiles at you.')

python says 'invalid syntax' and highlights the variable 'name'. What am I doing wrong? I'm a complete beginner...
Comment: You forgot a comma between the string before and `name`.
Answer: You forgot a comma right before your variable name
print ('-Nice too meet you, ', name ,'! My name is Alex, Alex Snowdon. He smiles at you.')

Also, you are going to face another error because you are casting an input to an int that I think you want as an str:
Change this: name = int (input ("what's your name?"))
To:
name = input ("what's your name?")

A much easier way to write this to avoid issues like this is to use format on your string, and place {} where you want to place your variable:
print ('-Nice too meet you, {}! My name is Alex, Alex Snowdon. He smiles at you.'.format(name))

Answer: print ('-Nice too meet you, ', name ,'! My name is Alex, Alex Snowdon. He smiles at you.')
#You forgot a comma here     ^, and you cannot put a string over multiple lines,
unles you use triple-commas, like this:

"""This is a string
that goes over multiple lines."""

Comment: ahhh I forgot that! thank you:)
Answer: In this line
print ('-Nice too meet you, ' name ,'! My name is Alex, Alex Snowdon.
He smiles at you.')

You forgot to put a come after '-Nice too meet you, ' [insert coma here] name,...

python isn't accepting my variable


Proving equivalent definitions of $e$

Question: Question:
Is $$\lim_{n\to\infty}\left(\left(1+\frac{1}{n}\right)^{nx}\right)=\lim_{n\to\infty}\left(\left(1+\frac{x}{n}\right)^{n}\right)$$
Background:
I am trying to show the equivalence of definitons of $e^x$ starting with $$e=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n$$
I proceeded as follows $$e^x=\left(\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n\right)^x$$ and as the limit does not depend on $x$ then$$e^x=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^{nx}$$
Next I expanded using the binomial expansion:
$$e^x=\lim_{n\to\infty}\left(1+nx\frac{1}{n}+\frac{nx\left(nx-1\right)}{2!}\left(\frac{1}{n}\right)^2+...+\right)$$
$$e^x=\lim_{n\to\infty}\left(1+x+\frac{x^2-\frac{x}{n}}{2!}+...+\right)$$
$$e^x=1+x+\frac{x^2}{2!}+...+$$
I have seen $e^x$ defined as $$\lim_{n\to\infty}\left(\left(1+\frac{x}{n}\right)^{n}\right)$$ and am trying to reconcile that fact.
Using the binomial expansion
$$\lim_{n\to\infty}\left(\left(1+\frac{x}{n}\right)^{n}\right)=\lim_{n\to\infty}\left(1+n\left(\frac{x}{n}\right)+\frac{n(n-1)}{2!}\left(\frac{x}{n}\right)^2+...+\right)$$
$$=1+x+\frac{x^2}{2!}+...+=e^x$$
So it seems the two are equivalent as $n\to\infty$ but not before.  Is this correct?  I feel it is and that the two functions are equivalent in the limit.
A broader question therefore is:
Are there extra algebraic manipulations such as moving the $x$ inside that are valid in limit situations?  Perhaps under given constraints?
Thanks for your help in advance.  I have scanned the site for the answer but didn't see anything but could have missed it.
Comment: If you already have some definition of $\log$, you may just compare $nx\log\left(1+\frac{1}{n}\right)$ and $n\log\left(1+\frac{x}{n}\right)$. You may easily check that the difference is $O\left(\frac{|x|}{n}\right)$ as $n\to \infty$, so your claim holds by the continuity of $\exp$ and $\log$.
Comment: @JackD'Aurizio Hi Jack.  That reasoning seems dangerously circular if one is beginning with the limit definition of $e$.
Comment: @MarkViola: well, I know, that is the reason for the initial *if*. On the other hand, to apply Bernoulli's inequality or to exploit the Taylor series of $\log(1+x)$ are pretty much the same thing, once $\log$ has been defined in some way.
Answer: You can make the following change of variable $nx=k$ so
 $\lim\limits_{n\rightarrow \infty} \left(1+\dfrac{1}{n} \right)^{n x}=\lim\limits_{k\rightarrow \infty} \left(1+\dfrac{x}{k} \right)^k$.
Comment: Thank you.  It seems obvious now but I'm rarely see the wood for the trees unfortunately.
Comment: @MarkViola that is a subtle comment. I simply hadn't thought about.  Is there a work around?
Comment: I unaccepted the answer. Sorry fabian it seems the right thing given Marks comment.  I will accept it if there is a work around. Hope thats OK, I mean no offence. I should have thought before accepting my fault.
Comment: No problem at all, the idea of math is to be certain... So it's clear that for $x\in\mathbb{N}$ the idea works. So suppose $x\in\mathbb{Q}$, so $x=\dfrac{p}{q}$, since $\lim\limits_{n\rightarrow \infty}\left(1+\dfrac{1}{n} \right)^n$  exists then $\lim\limits_{n\rightarrow \infty}\left(1+\dfrac{1}{n} \right)^{\dfrac{n p}{q}}$ also exists, so take the subsequence $\alpha_n=n q$, so $\lim\limits_{n \rightarrow \infty}\left(1+\dfrac{1}{n} \right)^{\dfrac{\alpha_n p}{q}}=\lim\limits_{n \rightarrow \infty}\left(1+\dfrac{1}{n q} \right)^{n p}$... For $x\in\mathbb{R}$ it follows by a density argument
Comment: @fabian_mc Well done.  I was in the process of writing a solution. but have deleted it after my reading your comment.  (+1)

Proving equivalent definitions of $e$


Symfony2 validation messages translation. Fallback option does not works

Question: I have SF2.3 at my webserver. I am using validatorBuilder to validate my data.
Here is my config:
<code>framework:
    translator:      { fallback: ru }
    default_locale:      ru
</code>
Here is my event listener:
<code>// EventListener.php
...
$validator = Validation::createValidatorBuilder()
        ->enableAnnotationMapping()
        ->getValidator();
</code>
But when I get error messages they are in english, not in 'ru' locale. What am I doing wrong?
Comment: Do you have messages.ru.xliff in your bundle?
Comment: @AlbertoGaona no I don't. But I saw Validator has translation files for many languages.
Answer: Here is the solution:
<code>$trans = new Translator('ru');
$trans->addLoader('xliff', new XliffFileLoader());
$trans->addResource('xliff',  __DIR__.'/../Resources/translations/validators.ru.xlf', 'ru', 'validators');

$this->validator = Validation::createValidatorBuilder()
        ->enableAnnotationMapping()
        ->setTranslator($trans)
        ->setTranslationDomain('validators')
        ->getValidator();
</code>


Rendering OBJ pyopengl

Question: Pls I have been trying this for past few month but all prevail I tried alot of online resources to read and display OBJ file without MTl stuff all in vain, I write my codes still errors so I finally arrive at my self made code that can read obj file of any faces type e.g (v//vn)(v/by/vn)(v) I hope you understand this.
After I read the file I got no error but rendering with pyopengl I got no error but the object didn't show. Pls check my obj loader code, and the opengl code in the screen with the result in another screenshot.
Note I got no error I don't know if I wrote something wrong in the obj loader but pls check and help me pls.
OBJ code:
from OpenGL.GL import *
from pyopengltk import OpenGLFrame
class OBJ:
    def __init__(self,filename):
    self.faces = []
    self.vertices = []
    with open(filename, 'r') as f:
        lines = f.readlines()
        #print(lines)
        if lines:
            for line in lines:
                if line[0] == 'v':
                    index1 = line.find(' ')
                    index2 = line.find(' ', index1+1)
                    index3 = line.find(' ', index2+1)

                    v1 = float(line[index1: index2])
                    v2 = float(line[index2: index3])
                    v3 = float(line[index3:])
                    self.vertices.append((v1,v2,v3))
                    #print(self.vertices)
        for line in open(filename, "r"):
            face = []
            texcoords = []
            norms = []
            if line.startswith('#'): continue
            values = line.split()
            #print(values)
            if not values: continue
            if values[0] == 'v':continue
            elif values[0] == 'vn':continue
            elif values[0] == 'vt':continue
            if values[0] == 'f':
                for v in values[1:]:
                    #print(len(v))
                    if len(v) == 4:
                        if ['/' for s in values[1:]]:
                            w = v.split('//')
                            face.append(int(w[0]))
                            norms.append(int(w[1]))
                            self.faces.extend(tuple((face, norms)))
                            #self.faces = [y for x in self.faces for y in x]
                            #print(self.faces)
                            glBegin(GL_QUADS)
                            glColor3f(0,1,1)
                            for surface in self.faces:
                                for vertex in surface:
                                    glVertex3fv(self.vertices[vertex])
                            glEnd
                        else:
                            self.faces.append(v)
                            glBegin(GL_QUADS)
                            glColor3f(0,1,1)
                            for surface in self.faces:
                                for vertex in surface:
                                    glVertex3fv(self.vertices[vertex])
                            glEnd
                            print(self.faces)
                    elif len(v) == 3:
                        w = v.split('/')
                        face.append(int(w[0]))
                        texcoords.append(int(w[1]))
                        norms.append(int(w[2]))
                        self.faces.append((face, norms, texcoord))
                        glBegin(GL_TRIANGLES)
                        glColor3f(0,1,1)
                        for surface in self.faces:
                            for vertex in surface:
                                glVertex3fv(self.vertices[vertex])
                        glEnd
                        #print('v/vt/vn')
                        print(self.faces)
#to run this code just use file path to any obj file on your pc
#OBJ('filename_path')

Rendering code
import tkinter as tk
from OpenGL.GL import *
from OpenGL.GLU import *
from pyopengltk import OpenGLFrame
from obj import *

class frame(OpenGLFrame):

  def initgl(self):
        glViewport(0,0,self.width,self.height)
        glClearColor(0.902,0.902,1,0.0)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        #glOrtho(-10,10,-10,10,-10,10)
        gluPerspective(60, self.width/self.height,0.1,100.0)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)
        glEnable(GL_CULL_FACE)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

  def redraw(self):
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
        OBJ('C:\\Users\\DANIEL\\Desktop\\v-cam\\me.obj')
        #that is what I did here obj suff
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        gluLookAt(0,-10,0,0,0,0,1,0,20)

root = tk.Tk()
app = frame(root, width=900, height=600)
app.pack(fill=tk.BOTH,expand=tk.YES)
app.mainloop()

Comment: Are you really loading the object each frame? It seems to me that you are perhaps missing parentheses after `glEnd`? Do not post the codes as an image, that does not help anybody. If you want proper help, make a [mcve](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: Ok pls refresh the page I have add every necessary details
Comment: No, you did not. The indentation in obj constructor is wrong. There's no info about how to compile the program - the first file is obj.py? And when I run it, i (obviously) get `FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\DANIEL\\Desktop\\v-cam\\me.obj'`. The easier you make it for someone to run your code, the chance for someone to answer.  Did you try to add the parentheses? That's definitely a mistake and part of the problem.
Comment: *the better chance
Comment: To run the code you use OBJ(filename) in the rendering part!,. In the filename input any obj file path on your PC. Check the code you will see ive add it
Answer: I recommend to use the object loader which you have introduced in one of your previous questions (Pyopengl reading obj file).
Create an OBJ instance in initgl:
self.obj =  OBJ('C:\\Users\\DANIEL\\Desktop\\v-cam\\me.obj')

And use glCallList to draw the mesh in redraw.
glCallList(self.obj.gl_list)

Class frame:
class frame(OpenGLFrame):

    def initgl(self):
        glViewport(0,0,self.width,self.height)
        glClearColor(0.902,0.902,1,0.0)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        #glOrtho(-10,10,-10,10,-10,10)
        gluPerspective(60, self.width/self.height,0.1,100.0)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)
        glEnable(GL_CULL_FACE)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        self.obj =  OBJ('C:\\Users\\DANIEL\\Desktop\\v-cam\\me.obj')

    def redraw(self):
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
        #that is what I did here obj suff
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        gluLookAt(0,-10,0,0,0,0,1,0,20)

        glCallList(self.obj.gl_list)

Rendering OBJ pyopengl


The distribution of the initial point of an AR process

Question: Consider a stochastic process $\{X_t, t = 1, 2, \ldots\}$ following the model $$X_t = \alpha X_{t-1} + e_t,$$ where $e_t \thicksim f$.

Can I say that the distribution of the initial point, $X_1$, is the same as $f$?
Can I say that the stationary marginal density, if it exists, of $\{X_t\}$ is same as $X_2 (\stackrel{D}{=}\alpha X_1 + e_2)$?

I think that the stationary marginal density, if it exists, of $\{X_t\}$ is the same as $X_2$, but not necessarily same as $X_1$.
Answer: Time-series processes defined only by a recursive equation are not fully specified, since they depend on specification of a "starting distribution".  Unless there is some additional restriction you are required to meet, you can use any starting distribution you like, and you will still have an AR model that conforms with the specified recursive equation.  However, having said this, it is usually the case that we want to specify a stationary AR model, which imposes an additional restriction beyond the recursive equation.  If you would like your AR model to be stationary, then you require $|\alpha|<1$ and you also need to choose the marginal distribution of the initial value to be equal to the asymptotic distribution of the process.
To obtain the marginal distribution required for a stationary model, you set the variance for the marginal distribution by setting its variance to $\sigma_X^2 = \mathbb{V}(X_t) = \mathbb{V}(X_{t-1})$.  From the recursive equation defining your AR process you have:
$$\begin{equation} \begin{aligned}
\sigma_X^2 = \mathbb{V}(X_t)
&= \mathbb{V}(\alpha X_{t-1} + e_t) \\[6pt]
&= \alpha^2 \mathbb{V}(X_{t-1}) + \mathbb{V}(e_t) \\[6pt]
&= \alpha^2 \sigma_X^2 + \sigma^2. \\[6pt]
\end{aligned} \end{equation}$$
Solving for $\sigma_X$ yields:
$$\sigma_X^2 = \frac{\sigma^2}{1-\alpha^2}.$$
Hence, in order to obtain a (strongly) stationary AR model (with zero mean), you would use the starting distribution:
$$X_i \sim \text{N} \Big( 0, \frac{\sigma^2}{1-\alpha^2} \Big).$$
Using this starting distribution ensures that the time-series values all have that same marginal distribution, which gives you a stationary process.  You will notice from this result that the marginal variance of the series is larger if the absolute value of the auto-correlation parameter is closer to one.  That is because such processes have high auto-correlation, which leads to large swings in the process, leading to higher (marginal) variance.
One more thing to note here is that you do not have a mean term in your AR model, so it has an asymptotic mean of zero, and so we have used a mean of zero in the starting distribution.  You could generalise your model to have a mean parameter if you wanted to, but that would change the recursive equation slightly.  I have discussed this issue for the more general AR model in another answer to a similar question here, and I recommend you read that answer to supplement this one.
Comment: Hi @Ben, thank you very much for the answer! I was wondering why you have taken the asymptotic distribution of the starting point to be normal. Can it be any stable distribution?
Comment: The stable distribution in this model *is* the asymptotic distribution, but yes, you are just looking for stationarity, so any stable distribution will do it.