Why does the Arima() method in the forecast package in R not calculate standard errors for coefficients passed to 'fixed'?

Question: In the Arima() method, in the forecast package in R, I can provide a vector of parameters to the fixed argument, and the model is estimated while ensuring the provided parameters are fixed to the supplied values.
However, when I do this, the model returns no standard errors for these coefficients. Why is this the case? Is it not possible to estimate standard errors of coefficients that are manually provided? Would love an explanation as to why this might be the case.
Moreover, the forecast method still calculates confidence intervals when forecasting from a model that has fixed parameters. Are these intervals still statistically valid? I would have thought such would rely on the standard errors of the estimated coefficients, which it seems we may not know in the case of manually-entered parameters?
Comment: I'd say you have it backwards. If we enter coefficients, we believe that we *know* them. On what basis would we calculate standard errors, which are a measure of the parameter estimates' variability? For your 3rd paragraph, are you asking about *confidence* intervals (for parameters) or *prediction* intervals (for future realizations)?
Comment: Hi Stephan. But say these fixed coefficients are not known, but rather a good guess. Purely theoretically is it possible to calculate standard errors in this case? And I'm asking about prediction intervals for future realisations in my last paragraph.
Comment: Consider this example: I am trying to predict Sales as a function of GDP and Employment with a linear regression model. I search the entire parameter space and find there is one global minimum, where GDP has a negative coefficient and Employment has a large positive coefficient: due to my data sample and collinearity, one coefficient is offsetting the other. But say there is another minimum, where both have positive coefficients. I think this must be the 'correct' minimum, due to economic intuition, so I supply these coefficients as fixed parameters. Are confidence intervals still feasible?
Answer: Fixed parameters entered into Arima() will be interpreted as known parameters. (Whether this makes sense is a different question.) As such, it would rather be questionable if standard errors were calculated for them - after all, SEs are measures of the parameter estimates' variability, and in this interpretation, there is none.
The prediction intervals should still be valid - of course, under the assumption of known parameters. They should therefore only include the variability from the noise or innovations term. As above, whether this makes sense or not is a different question.
(Note that there is a difference between a confidence interval, which refers to an unobservable parameter, and a prediction interval, which refers to a realization that is in principle observable later on.)
If the parameters you provide are not known, but rather "a good guess", then the best way of dealing with this is quantifying your uncertainty and running a Bayesian ARIMA model. This would allow the model to update your guesses, and resulting prediction intervals should reflect both your posterior uncertainty and the remaining noise terms. Unfortunately, I don't know of an implementation of Bayesian ARIMA, but I assume there is one.
Comment: Thanks Stephan for a very clear answer. Yes, a Bayesian approach could indeed be the answer. If I think about it, what I'm really trying to do here is embed my prior economic intuition into the estimation process of an ARIMAX model. If you (or anyone else) has any thoughts on this I'd be greatly appreciative!
Comment: [This may be helpful.](http://stats.stackexchange.com/q/51256/1352)


How to add a default Field when creating a Content Type?

Question: I use to add a image field every time I create any content type. Just wondering if is there any way to add this field by default when the content type is created.
I found the http://drupal.org/project/content_type_extras module which provides some additional features to content types, but it doesn't include this feature.
Answer: Not fully what you're asking. But once you have defined your image field you can easily reuse it in any content type. Since defining new content types is not something you do every day, this shouldn't be to much of extra work.
Comment: What's the reason you have to add content types every day? A content type is something very basic of your site setup. This should not be an every day job, unless you are setting up new sites every day,
Comment: Using the "Add existing field" feature is what I usually do. But I since I find myself doing this every day I was just wondering if I can make this automatically.


Missing data and internal and external validity

Question: There are quite a number of questions about missing data, but I can't find one related to its consequences on validity in the context of regression. Please correct me if this is not the case. The article on Wikipedia is quite vague on the issue too, with phrases like "with different impacts on the validity of conclusions from research", without really specifying what it means by "conclusions".
Question: it is clear to me that under missing completely at random (MCAR), results from a regression are both internally (i.e. consistency) and externally (inference to wider population) valid (minding no other problems of course). What about MAR and NMAR?
Answer: I think maybe you are confused because you are looking for some kind of firm estimation of the consequences. But here is the rub with missing data. The data is missing so in many cases one cannot say what it's affect on your regression coefficients, SEs etc. would be.
Having data that has some points that are pleasantly MCAR will reduce the power of your model as there is a loss in statistical efficiency. But that is all.
Having data that has some points that are MAR is a bit annoying. Listwise deletion (also termed complete case analysis) may lead to results that are biased, but as the term suggests, one should be able to make good judgemental use of the observations and avoid such bias. Obviously the problem is to be able to say unequivocally that the data is MAR and for this you need 'separability': where the parameters for the missingness process are distinct from the model explaining the primary dependent. Most methods for dealing with incomplete data rest on the MAR assumption.
Having data that has some points which are MNAR is is a complete and very common b*tch. Here, we are trying to say something about the world (by modelling it, in say your LR) but we have observed too little of it to say anything. Going ahead and modelling the complete data will mean you cannot infer anything about the wider population, because your results will be biased - you don't have external validity. You won't know how because the information is, well, missing. You cannot make causal interpretations (internal validity) because you are missing data and the missingness indicators are dependent on that unobserved data.  Without collecting more data or, in some cases, imputing the missing data... you are only able to talk about your incomplete sample. We have to go beyond the data and the model.
Sensitivity analysis is a good idea as if you wish to continue to model the data. You could think of doing a logistic regression using the missingness indicators as binary variables as a starting point to understand your patterns of missingness.


Configuration Errors: Elastic Load Balancer + EC2 + Route 53

Question: I am trying to configure my website to have a secure connection (https://) via Amazon's EC2, ELB, and Route 53.
I am running a t2.micro instance (no Elastic IP or anything). My Elastic Load Balancer has the SSL certificate attached. My SecurityGroup allows for https connections through port 443. I'm not sure what I'm doing wrong here.
All of my configurations are below. Any help is appreciated because, as it stands, I can't access my website at all.
Thank you in advance!
EC2 - - -

Load Balancer - - -

Route 53 - - -
Answer: Step 1: Hit the EC2 instance directly and verify that the health check URL responds with an HTTP 200 status code. If not, then get that working first.
You aren't clear about your security group configuration. You should have a security group on your load balancer that allows HTTP and HTTPS connections. Then you should have a security group on your EC2 instance that allows HTTP (port 80) connections from the load balancer's group.
The issue is obviously the failing health check on the load balancer at this point, so no need to look at Route 53 settings right now. You need to concentrate on getting the communication working between the EC2 instance and the load balancer to get that health check to start working. Until then the load balancer won't accept any traffic because it doesn't have instances it considers healthy that it can forward traffic to.
Comment: The instance is working properly from the public DNS route. The security group on my load balancer and EC2 instance are the same. The allowed inbound requests are: HTTP, PostgreSQL, Custom TCP Rule, SSH, and HTTPS - all with TCP protocol and corresponding port ranges. Is there something I'm missing within the security group protocols?
Comment: Do you have any of those ports restricted? Or are they all open to the world?
Comment: They're all open. I'll change that down the road, but I just wanted to make sure I could get it working first
Comment: I was able to get the instance and the load balancer to communicate. It says its InService, and I am able to visit the load balancer's DNS with no trouble. My Route 53 does not let me visit the custom domain, however. Would you happen to know how to fix that?
Comment: Did you update your name servers at your domain registrar to the name servers provided by Route 53?
Comment: I'm using Route 53 as my domain registrar, so it should be defaulted to the given name servers.
Comment: When did you register the domain then? I'm unable to resolve your domain name.
Comment: I originally purchased it via Google Domains a few months ago. Yesterday, I transferred it into Route 53. It said the transfer was completed on Amazon's site.
Comment: I was able to get it working now. Thank you for your help!


Aumentar um index até determinado número e depois diminuir até zerar com jquery

Question: Como posso fazer um script em jquery para aumentar um index até determinado número e depois diminuir um por um até zerar.
Estou fazendo da seguinte forma para aumentar mas gostaria que quando chegasse no 5 ele diminuísse até zerar.
var index = 0;

setInterval(function ()
{
    teste();

}, 10000, true );

function teste()
{
    index++;
}

Answer: Você precisa de uma variável de controle indicando se é para incrementar ou decrementar, ou então usar alguma aritmética modular:
Usando uma variável de controle:
var index = 0;
var inc = +1;

var handle = setInterval(teste, 10000, true); // como o @bfavaretto indicou!

function teste()
{
    if (index == 5)
        inc = -1;

    index += inc;

    if (index == 0)
        clearInterval(handle);
}

Comment: Verdade, minha resposta (removida) estava falida.
Comment: Realmente, ela iria ficar alternando entre 4 e 5 no final... aliás eu não tinha percebido a função chamando outra função diretamente. Vou melhorar isso nessa resposta!
Comment: Boa solução `+1`
Answer: Aqui vai mais uma ideia, usando um objeto para guardar o valor do index e também a direcao; porque não ví a pergunta a tempo e sem desprestígio para a resposta do Miguel Angelo que já estava aceite quando coloquei a minha.
var index = {    // um objeto para guardar ...
    valor: 0,    // o valor inicial e que vai mudar
    direcao: ,   // a direccao, se sobe (1) ou desce (0)
    maximo: 5    // o máximo que pode atingir
};

var contador = setInterval(teste, 10000);

function teste() {
    // usar o valor
    console.log(index.valor);

    index.direcao ? index.valor++ : index.valor--;
    if(index.valor == index.maximo) index.direcao = !index.direcao;
    if (!index.direcao && index.valor < 0) clearInterval(contador);

}

Exemplo


Mathematica - How to solve for the equilibrium?

Question: So, I used Mathematica to create a basic SIR Disease model using the following equations:
Neqs=eqs/.{b->u,a->0}

eqs={

S'[t] == b N[t] - u S[t] - B S[t](I[t] / N[t]),

I'[t] == B S[t] (I[t] / N[t]) - u I[t] - a I[t] - g I[t],

R'[t] == g I[t] - u R[t],

N'[t] == b N[t] - u N[t] - a I[t],

S[0] == N[0] - I[0],

I[0] == 1,

R[0] == 0,

N[0] == n

}

I then used Manipulate to find the solution using NDSolve and then plot it.
This code all worked and I have some neat sliders for $u$, $B$, $g$, and $n$ that are pretty fun to play around with.
Now, I am supposed to solve for the equilibrium, or when the disease spreads ($dI/dt  > 0$), and plot the isoclines for $S$ and $I$ populations. I tried to write an if loop to do this, but I am really confused and it just gives me errors. Does anyone know a way to approach this? Any help is appreciated!
Answer: Is that "BSt" supposed to be B*S[t] or is it B*S[t]*t?  If the latter, this is a time-dependent system, not an autonomous system, and there is no such thing as an equilibrium.  All the SIR models I've seen would have a term involving S[t]*I[t], to model susceptibles becoming infective by contact with infectives.


methods of prevent a user (or group) to be able to login

Question: is the only method to prevent a user from logging into the server setting the users shell to /dev/null?
Answer: Another alternative to using passwd -l would be to use passwd -d and delete the user's password.
Comment: As dangerous as this sounds at first glance, it worked for me when I tested it. I was worried that it would allow a user to login with literally no password, but it doesn't. After investigating, I found that the PAM configuration line "password   requisite   pam_unix.so nullok obscure md5" treats any passwordless account as being locked, and it won't auth, even over something like telnet (which I tried). Good answer. +1
Comment: that's why it says "delete", and not "remove" :)
Answer: Agree with ironchef regarding that configuring your sshd with AllowUsers or AllowGroups alternatively DenyUsers or DenyGroups might be a good solution, depending on what you are specifically trying to accomplish.
Regarding the option of setting a denying shell. If you have a /sbin/nologin available that might be preferable to /dev/null or /bin/false. Using /sbin/nologin will basicly have the same effect (non-zero exit), but with the extra bonus of the user getting a short message about the login being disabled.
Since you seem to want to keep the account around I assume you might be using them for something else? Depending on what that is, the locking of accounts may or may not be a good idea.
As already stated, please let people know what problem you are trying to solve, etc. Usually you can get a lot better advice that way.
Answer: I would aks what you're trying to do to get a better idea.  For sake of expediency, if you only allow ssh as the access method, you can limit who can login by using AllowUser (only users explicitly in AllowUser will be allowed by sshd to login).
Answer: You should set it to /bin/false instead of /dev/null.
usermod -L myaccountname
disables the password for that user
If the user have a SSH public key, you might wanna disable it too :
rm /home/clem/.ssh/authorized_keys*
(use mv if you want to restore it later)
You could also explicitely restrict allowed users with sshd's AllowUser directive (in /etc/ssh/sshd.conf).
Answer: Pam_access provides a good method to restrict access to a subset of users.  Check out "man pam_access" for more details.  The pam configuration will have to be modified.  Most of the configuration happens in /etc/security/access.conf.  This module is pretty flexibly in restricting access to just particular users, or users who belong in particular groups.  The restrictions can be applied across all services, or just to particular services, depending on where pam_access is included within pam.
I've actually gone as far as running two separate access.conf like files, using one for shell access, and one for ftp/rcp access.  Pam_access allows us to maintain separate policies for various protocols.  The downfall of this flexibility is the configuration is a bit more complex, which may not be needed.


How to add a field to Browsing Widgets partial form?

Question: I have a content type Task which has a field that references to other content type Project, so when I create a new Task, I can reference it to a project. I would like to add this to the Commons Browsing Widgets partial form.

How can I add a dropdown list to this form that shows the projects where user can link the task? I was trying to add it by adding it to code in .module file, in the form_commons_bw_partial_node_form_alter() part but I didnt manage to get it working..
Answer: It seems that you can just do this by going to your content type, edit the field you want to show and check the "Display in the browsing widget mini-form". After all the trouble it seems quite simple..


Ubuntu 22.04 php8.1-fpm wifth Apache - 403 Forbidden You don't have permission to access this resource

Question: I installed php8.1-fpm on Ubuntu 22.04. In principle, I set everything up, but still "403 Forbidden
You do not have permission to access this resource "error message is displayed. The system is configured on an internal network with a self-signed certificate for development purposes.
I've done it with virtualmin so far, but now I want to get used to it ... I bought the configuration basics from there, but obviously something is still missing
/etc/apache2/sites-available/mydomain.dev.conf:
<VirtualHost 192.168.0.4:443>
    SuexecUserGroup "#1000" "#1000"

    ServerName "mydomain.dev"

    DocumentRoot "/home/mydomain/public_html"

    ErrorLog "/home/mydomain/etc/log/md_error_log"
    CustomLog "/home/mydomain/etc/log/md_access_log" "combined"

    ScriptAlias "/cgi-bin/" "/home/mydomain/etc/cgi-bin/"

    DirectoryIndex index.php index.html

    <Directory "/home/mydomain/public_html">
        Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI
        allow from all
        AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
        Require all granted
        AddType application/x-httpd-php .php
        AddHandler fcgid-script .php
        AddHandler fcgid-script .php8.1
        FCGIWrapper /home/mydomain/etc/fcgi-bin/php8.1.fcgi .php
        FCGIWrapper /home/mydomain/etc/fcgi-bin/php8.1.fcgi .php8.1
    </Directory>

    <Directory "/home/mydomain/etc/cgi-bin">
        allow from all
        AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
        Require all granted
    </Directory>

    SSLEngine on
    SSLCertificateFile /home/mydomain/etc/certs/mydomain.dev+4.pem
    SSLCertificateKeyFile /home/mydomain/etc/certs/mydomain.dev+4-key.pem
    SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
    SSLCACertificateFile /home/mydomain/.local/share/mkcert/rootCA.pem
    IPCCommTimeout 31
</VirtualHost>

/home/mydomain/etc/fcgi-bin/php8.1.fcgi:
#!bin/bash
PHPRC=$PWD/../etc/php8.1
export PHPRC
unmask 022
PHP_FCGI_CHILDREN=20
export PHP_FCGI_CHILDREN
PHP_FCGI_MAX_REQUESTS=99999
export PHP_FCGI_MAX_REQUESTS
exec /bin/php-cgi8.1

/etc/mydomain/public_html and subdirectories permissions: 0755
files permissions: 0644
error log (there is no link to /favicon.ico):
[Mon Apr 25 14:22:06.490822 2022] [core:error] [pid 24678] (13)Permission denied: [client 192.168.0.4:51818] AH00035: access to / denied (filesystem path '/home/mydomain/public_html') because search permissions are missing on a component of the path
[Mon Apr 25 14:22:06.721894 2022] [core:error] [pid 24678] (13)Permission denied: [client 192.168.0.4:51818] AH00035: access to /favicon.ico denied (filesystem path '/home/mydomain/public_html') because search permissions are missing on a component of the path, referer: https://mydomain.dev/

Thank you very much in advance for your help
Comment: What are the file permissions for /home/mydomain/public_html ?
Comment: You are mixing Apache 2.2 and Apache 2.4 syntax, which [leads to indeterminate results and is discouraged](https://httpd.apache.org/docs/2.4/upgrading.html#run-time). Use the proper syntax for your version.
Comment: Additionally: Your site config file is missing the VirtualHost definition. This could collide with other VirtualHosts. And is the site enabled  (meaning does a symlink to it in `sites-enabled` exist)?
Comment: /etc/mydomain/public_html/ and subdirectories
owner/group: mydomain
permissions: rwx r-x r-x
/etc/mydomain/public_html/*.php *.css etc
owner/group: mydomain
permissions: rw- r-- r--
Comment: yes: exists the sites-enabled
Comment: only this one VirtualHost exists outside the 00-default.conf and default-ssl.conf
Comment: this is behind the original question:
/etc/apache2/sites-available/mydomain.dev.conf:
 ...
Comment: you do not really host your web files in `/etc`? Moreover, administration Panel are off-topic for serverfault.com
Answer: Add the user to the www-data group:
usermod -g www-data username

Source: http://www.anoneh.com/208.php
Comment: That solved my problem, thank you


Como realizar um Count em várias colunas?

Question: Gostaria de fazer um COUNT utilizando LINQ / LAMBDA, mas estou tendo dificuldades. Podem me ajudar?
A ideia é reproduzir a seguinte consulta:
SELECT Conta, Tipo, Documento, Nome, COUNT(0) AS Qtde
FROM TaxaPrecificacao
GROUP BY Conta, Tipo, Documento, Nome

Abaixo algumas formas que tentei fazer mas, claro, todas estão erradas.
//Funciona mas a coluna do Count não está sendo calculada
var view = TaxaPrecificacao
.Select(
x => new PrecTxContas
{
    Conta = x.Conta,
    Tipo = x.Tipo,
    Documento = x.Documento,
    Nome = x.Nome,
    Qtde = 0
});

//Erro de sintaxe
var view = TaxaPrecificacao
.Select(
x => new PrecTxContas
{
    Conta = x.Conta,
    Tipo = x.Tipo,
    Documento = x.Documento,
    Nome = x.Nome,
    Qtde = x.Count()
});

/*Sintaxe OK mas não compila The type appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order*/
var view = TaxaPrecificacao
.GroupBy(
x => new PrecTxContas
{
    Conta = x.Conta,
    Tipo = x.Tipo,
    Documento = x.Documento,
    Nome = x.Nome
})
.Select
(
x => new PrecTxContas
{
    Conta = x.Conta,
    Tipo = x.Tipo,
    Documento = x.Documento,
    Nome = x.Nome,
    Qtde = x.Count()
});

Comment: É um sistema bem específico mesmo, mas seria o seguinte: Eu tenho uma tabela onde cadastro taxas para as contas. Uma conta pode ter várias taxas cadastradas na mesma tabela, eu gostaria de contar quantas taxas cada conta tem e exibir dessa maneira: Numero da conta, Tipo da Conta, Documento (CPF ou CNPJ), Nome do cliente e a quantidade de taxas. Acreditem, no meu sistema isso faz sentido. Mas o que estou tendo dificuldade é reproduzir isso via LINQ/Lambda. Ajudou a explicação?
Comment: Não, na verdade não explicou nada do que eu pretendia saber. A regra do seu sistema é irrelevante pra questão, mas vamos lá, **o que você quer é fazer uma consulta agrupando por estes quatro campos e obter a quantidade de cada agrupamento?**
Comment: Sim, como no SELECT de cima.
Comment: Uma boa ideia de leitura: https://pt.stackoverflow.com/q/176853/18246
Answer: Você precisa ter em mente que o GroupBy retorna uma estrutura de agrupamento.
Esta estrutura contém todos os dados de determinado agrupamento e também a chave (Key) dele. Por exemplo:  se você tem 5 itens cujas chaves de agrupamento são Conta = 01, Tipo = 1, Documento = 2 e Nome = "Foo", esta estrutura conterá, dentre outras coisas, todos os dados do respectivo agrupamento e um membro Key que também será uma estrutura com todos os membros do agrupamento, algo como:
{ Conta = 1, Tipo = 1, Documento = 2, Nome = "Foo" }

Então, após usar o método GroupBy(), você pode trabalhar em cima desta estrutura e usar o método Count() para retornar a quantidade de elementos de cada agrupamento, ou Sum() para somar os valores de alguma propriedade e assim por diante.
O código seria, basicamente, assim:
var view = TaxaPrecificacao.GroupBy(t => new { t.Conta, t.Tipo, t.Documento, t.Nome })
                           .Select(gp => new
                                   {
                                       Key = gp.Key,
                                       Qtd = gp.Count(),
                                       Itens = gp.ToList()
                                   });

O uso seria algo como:
foreach(var v in view)
{
    WriteLine(v.Qtd);

    foreach(var item in v.Itens)
    {
        WriteLine(item.Conta);
    }

    WriteLine();
}

Veja um exemplo funcionando no .NET Fiddle.
Código completo do exemplo:
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;

public class Program
{
    public static void Main()
    {
        var view = TaxaPrecificacao
                     .GroupBy(t => new { t.Conta, t.Tipo, t.Documento, t.Nome })
                     .Select(gp => new
                             {
                                 Key = gp.Key,
                                 Qtd = gp.Count(),
                                 Itens = gp.ToList()
                             });

        foreach(var v in view)
        {
            WriteLine(v.Qtd);

            foreach(var item in v.Itens)
            {
                WriteLine($"{item.Conta} - {item.Valor}");
            }
            WriteLine();
        }
    }

    static List<TaxaPrecificacao> TaxaPrecificacao = new List<TaxaPrecificacao>
    {
        new TaxaPrecificacao { Conta = "001", Tipo = 1, Documento = "A",
                               Nome = "Tx 1", Valor = 5m },
        new TaxaPrecificacao { Conta = "001", Tipo = 1, Documento = "A",
                               Nome = "Tx 1", Valor = 10m },
        new TaxaPrecificacao { Conta = "001", Tipo = 1, Documento = "A",
                               Nome = "Tx 1", Valor = 52m },
        new TaxaPrecificacao { Conta = "002", Tipo = 2, Documento = "B",
                               Nome = "Tx 2", Valor = 56m },
        new TaxaPrecificacao { Conta = "002", Tipo = 2, Documento = "B",
                               Nome = "Tx 2", Valor = 59m },
        new TaxaPrecificacao { Conta = "002", Tipo = 2, Documento = "B",
                               Nome = "Tx 2", Valor = 19m },
    };
}

class TaxaPrecificacao
{
    public string Conta { get; set; }
    public int Tipo { get; set; }
    public string Documento { get; set; }
    public string Nome { get; set; }
    public decimal Valor { get; set; }
}

Comment: consegui chegar no resultado que eu precisava. Na verdade eu fiz uma modificação no meu terceiro exemplo que postei na pergunta e funcionou. Onde eu estava instanciando 'x => new PrecTxContas {...}' dentro do GroupBy eu removi a tipagem da Classe, ficando apenas 'x => new {... }'. Mas eu entendi como fazer a partir da sua resposta, quando você explica sobre o membro Key ser uma estrutura de todos os agrupamentos. Obrigado.


Semicircle Question

Question: I need help with the question in the image. I just need someone to help by pointing me in the right direction. I don't want a full solution. I want to try to work out this question myself but I just need someone to direct me.

I was thinking if the question had something to do with joining the three points in the circle where the circle is touching the semicircles?
Or perhaps this question has something to do with similar triangles? I know that an angle subtended by an arc inside a semicircle is 90 degrees.
Answer: Hint: You may try using the tangent-secant version of the power of point theorem, remember that if two circles are tangent to each other (internally or externally), their centers and the point of tangency are collinear and draw all radii possible.
Answer: The hint:
Solve the following equation:
$$\sqrt{(1+x)^2-x^2}=1+\sqrt{(2-x)^2-x^2},$$ where $x$ is a needed radius.
Answer: HINT
Try with an approach by Circular Inversion which leads to $r=\frac 8 9$.
Answer: Let the center of small semi-circle be C, point on the AB where circle touches touches is D, p denotes center of the circle, E is the point where circle touches bigger semi-circle. Le the circle touch the smaller semi-circle at T. Let the radius of the circle be $r$, then
$$OP=2-r, OD=\sqrt{(2-r)^2-r^2}=\sqrt{4-4r}, CD=\sqrt{(1+r)^2-r^2}=\sqrt{2r+1}.$$
Finally,  $$CD-OD=1 \implies \sqrt{1+2r}-\sqrt{4-4r}=1 \implies r=8/9.$$
Comment: OP says "**I don't want a full solution.** I want to try to work out this question myself but I just need someone to direct me." (emphasis theirs).
Answer: Hint
Try to join all centres and points of contact.

Semicircle Question


How to compute $(i^2-i^4+i^6-i^8+...+i^{38})^2$

Question: How can i compute $(i^2-i^4+i^6-i^8+...+i^{38})^2$ ?
I can see that the powers are arithmetic progression with $d=2$ but i tried to compute
$S_{19}$ but it didn't work.
Thanks.
Comment: You should notice that this is a geometric series such that $a_1=i^2 \ , \ q=-i^2 \ , \ n=19$. What is the sum of it?
Comment: what does $i$ means here? $i^2=-1$
Comment: yes, if you can see i tag it as complex numbers.
Comment: @Galc127 - so $S_{19}=\frac{i^2[(-i)^{38}-1]}{(-i)^2-1}$?
Comment: This is exact. Now what to you know about $\displaystyle i^{4n+k}$ where k such that $k\in[1,4]$? And do you see the problem?
Comment: $i^4 = i^8 = i^{12} = \ldots$ and $i^2 = i^6 = i^{10} = \ldots$..
Comment: @Galc127 - yes so how do i continue?
Comment: As simple as $(-19)^2$
Comment: @david, you should look on the given answers - using sum of geometric series doesn't work when $q=1$.
Comment: @Galc127: Are you sure? There seem to be $19$ times "$-1$" here...
Comment: @Galc127 why? as the Answer of Hagen it's really $(19i^2)^2$
Comment: You are right, I will delete my comment.
Answer: Note that $i^2=-i^4=i^6=-i^8=\ldots$ so that the sum simplifies significantly.
Answer: $\textbf{Hint:}$ Note that $i^{4n}-i^{4n+2}=2$  for $n \in \mathbb{N}$.
Answer: So we know that $i^2$ = -1, and that squared is $i^4$ which is 1. As aforementioned, $i^2 = -i^4$. Because, $i^4=1$, $i^2=i^6=i^{10}...i^{38}$, and $i^4=i^8..i^{36}$. Therefore, canceling out terms leaves us with $(i^{38})^2$, which evaluates to $(-1)^2$, which we know to be one.
==> $(((i^2-i^4)+(i^6-i^8)...(i^{34}-i^{36})+i^{38})^2$ = $(0+0+0+..+(-1))^2$ = (-1)^2 = 1


wordpress advance custom field plugin showing broken image?

Question: I am using wordpress acf plugin to show some custom images with their description and some text. So first I just made the acf plugin fileds like this and assigned the page to the home page with the conditional tags Location-> Rules-> Page->is equal to-> Home
now when I made my content-page.php to show the image code like this
<?php
if( get_field('image') ):
    ?><img src="<?php the_field('image'); ?>" alt="" /><?php
endif;
?>

I am getting only a broken image. The firebug is showing image source like this
Kindly help me to solve this. I have already wasted one day behind it. So any help and suggestions will be really appreciable. Thanks
Here is the screen shot for my custom fields setup

Here is the firebug html code which is showing the image source
Answer: Had this problem too.  This is what I came up with that works:
<?php if (get_field('staff_photo')) {
    $imgarray = get_field( 'staff_photo' );
?>
    <img src="<?php echo $imgarray['url'] ; ?>" alt="" class="staff-photo" />
<?php } ?>

So, what I did was put get_field('field_name') array into a variable, then took a WAG that the key was 'url', which it was.  Seems like the ACF people need to update their documentation.
Answer: Hah!  Discovered another way -- this way you can pick a size:
<?php
if ( get_field('staff_photo') ) {
   $imgarray = get_field( 'staff_photo' );
   $size = "thumbnail"; // (thumbnail, medium, large, full or custom size)
   echo wp_get_attachment_image( $imgarray['id'], $size );
}
?>

For wp_get_attachemnt_image to work, you have to extract the image id, for which the key is, ta-da! 'id'.
Comment: I'd still like to know what the problem is. While both these answers work, it's frustrating that `the_field('field_name');` doesn't work in this case.


Can calling a complex function inhibit $.when?

Question: I have a function:
function someFunction(params) {
//Creates an object
//$.each(collection, funct() { /*do work on collection, essentially pushes items into an array */});

//JSON.stringify(results)

//$.ajax POST...this is what I want $.when to wait for

}

I setup
$.when(someFunction(params)
).then(doNextThing);

I also tried
$.when(function() {someFunction(params) }
).then(doNextThing);

doNextThing is invoked before the callback.  Is it possible that $.each or stringify is causing $.when to fail?
Comment: is someFunction returning anything?  It should be returning $.ajax
Comment: There are no `return` statements.  Do you mean I just stick a return in front of $.ajax.  E.G. `return $.ajax{...`?
Comment: doing `return $.ajax` fixed it.  Man, I've been struggling with this for a couple of hours.  If you post an answer I will definitely give you answer credit.
Answer: someFunction needs to return an object for $.when to work.  Otherwise it is the equivalent of someFunction(params);$.when(undefined).then(doNextThing).  In this setup doNextThing will never be called.
Since you are waiting on the ajax call, it should look something like this:
function someFunction(params) {
    ...
    return $.ajax(...);
}

$.when(someFunction(params)).then(doNextThing);


Embedding $\aleph_1$ into $\mathbb R$

Question: I am having trouble proving that one cannot construct an order-preserving map from $\aleph_1$ into $\mathbb R$.
I know that $\aleph_1$ equals the set of countable ordinals, but the fact that the map need not be surjective has made this trickier than I thought.
Is there a relatively elementary proof out there?
Answer: Let $\omega_1$ be the first uncountable ordinal.
Assume it order-embedded in $\Bbb R$. Each $\alpha\in\omega_1$ has a successor
$\alpha'$ in $\omega_1$. Between $\alpha$ and $\alpha'$ in $\Bbb R$ there is a rational
number $c_\alpha$. All the $c_\alpha$ are distinct, and the rationals
are countable....

Embedding $\aleph_1$ into $\mathbb R$


PDF of Ratio of Normal and Gamma Random Variables

Question: Let $X \sim N(0,1)$ and $Y \sim \Gamma\left(\frac{k}{2}, \frac{1}{2}\right)$. If $X$ and $Y$ are independent, find the pdf of $$V=\frac{X}{\sqrt{Y/k}}.$$
For this problem, I introduced $U=X$, and attempted to find the joint pdf of $U$ and $V$. However, as I was getting the marginal pdf of $V$, I got stuck. Can anyone help me on this?
Answer: $\Gamma\left(\frac{k}{2},\frac{1}{2}\right)$ is the same distribution as $\chi^2_k$. Hence the given statistic has Student's $t$ distribution with $k$ degrees of freedom. See t-distribution wiki


Multiple Regression Coefficient output

Question: I am a University student running an analysis of data collected during a field trip.
The goal of this analysis is to determine whether the length and species of a limpet are good predictors of where on a rock the limpet may be found (variable = height).
I have run a multiple regression on R, using the model:
limpets.2 <- lm(height ~ length + species, data = limpets)
The response variable height is continuous, as is the predictor variable length.
The predictor variable species is a factor with three levels for the three species. Co, Cr and Cd.
Output:
Call:
lm(formula = height ~ length + species, data = limpets)

Residuals:
    Min      1Q  Median      3Q     Max
-73.190 -23.358  -0.449  18.919 102.919

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 126.3523     4.8989  25.792  < 2e-16 ***
length       -1.6840     0.1446 -11.644  < 2e-16 ***
speciesCo     6.0416     3.0087   2.008  0.04494 *
speciesCr   -12.6376     3.8076  -3.319  0.00094 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 32.14 on 889 degrees of freedom
Multiple R-squared:  0.2554,    Adjusted R-squared:  0.2529
F-statistic: 101.7 on 3 and 889 DF,  p-value: < 2.2e-16

My question is, while R has given the coefficients of Co and Cr, where do I find the coefficient for Cd?
Thank you in advance.
Answer: It just gets 'absorbed' into the intercept term. It turns out that to represent a factor with $n$ levels, you need $n-1$ 'dummy' variables in your regression equation. In your case, species has levels Co, Cr and Cd, so $n = 3$. This means you need $n - 1 = 2$ dummy variables. Using these two dummy variables, you can represent your factor, species, like this

Cd: $x_0 = x_1  = 0$,
Co: $x_0 = 1, x_1  = 0$ and,
Cr: $x_0 = 0, x_1  = 1$
Comment: would this mean that my model equation; "height = 126.35 + (-1.684 length) + (6.042 speciesCo) + (12.638 speciesCr)"    is correct?
Comment: Yes, that's right

Multiple Regression Coefficient output


What is the value of $\int x^x~dx$?

Question: I am struggling with this puzzle.
Question 1. Is it possible to determine the value of the indefinite integral $\int x^x~dx$ explicitly?
By "explicit" I mean without power series.
Question 2. What are known theorems in the following form?
"$\int x^x~dx$ is not expressible by an expression given by functions in a family $\mathfrak{F}$" e.g. $\mathfrak{F}=\{\sin, \cos, \text{polynomials}\}$
Comment: I don't see how you can prove that you cannot explicitly take an integral.  The Fundamental Theorem of Calculus states that an anti-derivative exists for every integrable function--just because you cannot do it analytically doesn't mean _a_ function doesn't exist.
Comment: @Jared By "impossibility" I mean non-existence of an expression given by a set of "fundamental functions" e.g. polynomials, sin, cos, etc.
Comment: [This](http://math.stackexchange.com/questions/265780/how-to-determine-with-certainty-that-a-function-has-no-elementary-antiderivative) should help.
Comment: @Jared : Great idea to invent the function Jared(x). So great that it was already done (Unfortunately with a different name ! ) : See the paper "The Sophomores Dream Function" published on Sribd : http://www.scribd.com/JJacquelin/documents . I hope that an agreement will be achieved for a common name for this magnificent function.
Comment: If Mathematica can't do it, then likely, no one can: http://integrals.wolfram.com/index.jsp?expr=x%5Ex&random=false
Comment: Define fundamental functions, because I'm not sure I would consider $\sin$, $\cos$, $\sqrt{}$, etc. any more "fundamental" than merely stating $\int x^x dx = \text{Jared}(x) + C$ where $\frac{d\text{Jared}}{dx} = x^x$.
Comment: It should be theoretically possible to write this as a power series, however getting an explicit form of $x^x$ would be next to impossible (since you have $e^{x\ln(x)} = \sum \frac{x^i\ln^i(x))}{i!}$)
Comment: There's a bit of a problem with this function for negative values of $x$.
Answer: According to the Risch algorithm and Liouville's theorem, the primitive of this function cannot be expressed in terms of elementary functions. Nor can it be expressed in terms of special functions, such as Gaussian or error functions, etc. either, since $x^x=e^{x\ln x}$.
Answer: Indefinite intgerals of the form $\displaystyle{\int \mathrm{f}(x)\, \mathrm{d}x}$ do not have a value.
The "answer" to an integral like this is a function and not a number. For example:
$$\int 3x^2 \, \mathrm{d}x = x^3 + C$$
All of the function $x^3+C$ have the property that their derivatives, with respect to $x$, are $3x^2$.
It is definite integrals (and some infinite indefinite integrals) that take values. For example:
$$\int_1^2 3x^2 \, \mathrm{d}x = \left[x^3\right]_1^2 = 8 - 1 = 7$$
The basic difference is that definite integrals find areas and give numbers. Indefinite integrals find anti-derivatives and give functions. In most simple examples, we need to be able to find the anti-derivative to find an exact value for the area - as I did in the example above. However, in the case of $x^x$, the is no know anti-derivative. To prove this, you need to use Picard–Vessiot theory. This shows that there is no elementary anti-derivative.
However, it is possible to find the value of the definite integrals
$$\int_a^b x^x \, \mathrm{d}x$$
using numerical methods, e.g. the Trapezium Rule or Simpson's Rule. These can be used to find a value that is correct to any desired degree of accuracy.
There are some indefinite integrals that take values, e.g.
$$\int_{-\infty}^{\infty} \frac{\mathrm{d}x}{x^2+1} = \pi$$
Comment: Still $\exists F:\mathbb{R} \mapsto \mathbb{R}. \int_a^b x^x = F(b) - F(a)$.  The question is how do you prove $F$ is transcendental, which I guess Differential Galois Theory can be used to prove.
Comment: @Jared The question has been changed since I made my post.
Comment: I shouldn't use the term "transcendental" since this has a very restrictive definition (e.g. $f(x) = \sin(x)$ is transcendental).
Answer: $x^x$ is an integrable function as already said a number of times. The question is to know if a closed form exists. As usual for special functions, no closed form exists until one is defined and referenced. They are some conditions to define a new special function but I will not discuss this point here : it should be outside the scope of the question.
About the search for antiderivatives of $x^x$, there is an amusing anecdote told in the introduction of the paper "The Sophomores Dream Function" published on Scribd :
http://www.scribd.com/JJacquelin/documents
By the way, $\int_0^X x^x \, \mathrm{d}x =$ Sphd$(1;X)$
Answer: $\int x^x~dx=\int e^{x\ln x}~dx=\int\sum\limits_{n=0}^\infty\dfrac{x^n(\ln x)^n}{n!}dx$
For $\int x^n(\ln x)^n~dx$ , where $n$ is any non-negative integers,
$\int x^n(\ln x)^n~dx$
$=\int(\ln x)^n~d\left(\dfrac{x^{n+1}}{n+1}\right)$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\int\dfrac{x^{n+1}}{n+1}d((\ln x)^n)$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\int\dfrac{nx^{n+1}(\ln x)^{n-1}}{(n+1)x}dx$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\int\dfrac{nx^n(\ln x)^{n-1}}{n+1}dx$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\int\dfrac{n(\ln x)^{n-1}}{n+1}d\left(\dfrac{x^{n+1}}{n+1}\right)$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\dfrac{nx^{n+1}(\ln x)^{n-1}}{(n+1)^2}+\int\dfrac{x^{n+1}}{n+1}d\left(\dfrac{n(\ln x)^{n-1}}{n+1}\right)$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\dfrac{nx^{n+1}(\ln x)^{n-1}}{(n+1)^2}+\int\dfrac{n(n-1)x^{n+1}(\ln x)^{n-2}}{(n+1)^2x}dx$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\dfrac{nx^{n+1}(\ln x)^{n-1}}{(n+1)^2}+\int\dfrac{n(n-1)x^n(\ln x)^{n-2}}{(n+1)^2}dx$
$=\cdots\cdots$
$\vdots$
$\vdots$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\dfrac{nx^{n+1}(\ln x)^{n-1}}{(n+1)^2}+\cdots\cdots+\dfrac{(-1)^{n-1}(n(n-1)\cdots\cdots\times2)x^{n+1}\ln x}{(n+1)^n}-\int\dfrac{(-1)^{n-1}(n(n-1)\cdots\cdots\times1)x^n}{(n+1)^n}dx$
$=\dfrac{x^{n+1}(\ln x)^n}{n+1}-\dfrac{nx^{n+1}(\ln x)^{n-1}}{(n+1)^2}+\cdots\cdots+\dfrac{(-1)^{n-1}(n(n-1)\cdots\cdots\times2)x^{n+1}\ln x}{(n+1)^n}+\dfrac{(-1)^n(n(n-1)\cdots\cdots\times1)x^{n+1}}{(n+1)^{n+1}}+C$
$=\dfrac{(n+1)x^{n+1}(\ln x)^n}{(n+1)^2}-\dfrac{(n+1)nx^{n+1}(\ln x)^{n-1}}{(n+1)^3}+\cdots\cdots+\dfrac{(-1)^{n-1}((n+1)n(n-1)\cdots\cdots\times2)x^{n+1}\ln x}{(n+1)^{n+1}}+\dfrac{(-1)^n((n+1)n(n-1)\cdots\cdots\times1)x^{n+1}}{(n+1)^{n+2}}+C$
$=\sum\limits_{k=0}^n\dfrac{(-1)^{n+k}(n+1)!x^{n+1}(\ln x)^k}{k!(n+1)^{n-k+2}}+C$
$=\sum\limits_{k=0}^n\dfrac{(-1)^{n+k}n!x^{n+1}(\ln x)^k}{k!(n+1)^{n-k+1}}+C$
$\therefore\int\sum\limits_{k=0}^n\dfrac{(x\ln x)}{n!}dx=\sum\limits_{n=0}^\infty\sum\limits_{k=0}^n\dfrac{(-1)^{n+k}x^{n+1}(\ln x)^k}{k!(n+1)^{n-k+1}}+C$
Hence $\int x^x~dx=\sum\limits_{n=0}^\infty\sum\limits_{k=0}^n\dfrac{(-1)^{n+k}x^{n+1}(\ln x)^k}{k!(n+1)^{n-k+1}}+C$

What is the value of $\int x^x~dx$?


Fitting multimodal distributions in R; generating new values from fitted distribution

Question: I am working with small sample size data:
>dput(dat.demand2050.unique)
c(79, 56, 69, 61, 53, 73, 72, 86, 75, 68, 74.2, 80, 65.6, 60, 54)

for which the density distribution looks like this:

I know that the values are from two regimes - low and high - and assuming that the underlying process is normal, I used the mixtools package to fit a bimodal distribution:
set.seed(99)
dat.demand2050.mixmdl <- normalmixEM(dat.demand2050.unique, lambda=c(0.3,0.7), mu=c(60,70), k=2)

which gives me the following result:

(the solid lines are fitted curves and the dashed line is the original density).
# get the parameters of the mixture
dat.demand2050.mixmdl.prop <- dat.demand2050.mixmdl$lambda    #mix proportions
dat.demand2050.mixmdl.means <- dat.demand2050.mixmdl$mu    #modal means
dat.demand2050.mixmdl.dev <- dat.demand2050.mixmdl$sigma   #modal std dev

The mixture parameters are:
>dat.demand2050.mixmdl.prop  #mix proportions
[1] 0.2783939 0.7216061
>dat.demand2050.mixmdl.means  #modal means
[1] 56.21150 73.08389
>dat.demand2050.mixmdl.dev  #modal std dev
[1] 3.098292 6.413906

I have the following questions:

To generate a new set of values that approximates the underlying distribution, is my approach correct or is there a better workflow?
If my approach is correct, how can I use this result to generate a set of random values from this mixed distribution?
Comment: The question is what you want to infer from the random numbers. Your sample size might be too small to infer anything sensible from your approach.
Comment: I think this question might be better suited for CrossValidated: http://stats.stackexchange.com
Comment: @DavidMarx yes, I debated that and even whether to cross-post, but ultimately decided to write here since my 2nd question is more about coding. However, I'd gladly do so if the mods think it is better suited there.
Comment: I am not sure if your approach is sensible. You do not specify what you plan to do with the random numbers. Also, your sample size is very small and estimating normal distributions from such small sample sizes is a bit dubious. Maybe the bootstrap would be a better approach for your ultimate goal?
Comment: @Roland true, the sample size is small but that is what I have. the data are from a set of studies and only so many. I thought of bootstrapping using `sample()`, but will have to go back to my notes why i did not take that approach..perhaps this part of the discussion should go on CrossValidated..
Answer: Your sample size is a bit dubious to be fitting mixtures, but never mind that. You can sample from the fitted mixture as follows:
probs <- dat.demand2050.mixmdl$lambda
m <- dat.demand2050.mixmdl$mu
s <- at.demand2050.mixmdl$sigma

N <- 1e5
grp <- sample(length(probs), N, replace=TRUE, prob=probs)
x <- rnorm(N, m[grp], s[grp])

Comment: The results are exactly the same as @CnrL's. Run their solution with N = 1e5. As for the starting density; who knows what's going to happen with 15 data points.
Comment: your method seems to overemphasize the lower distribution in the same way Roland's solution did. Compare your output density with the starting density and the output of @CnrL's solution. This code looks right, but the result seems off. I'm not sure why.
Comment: @DavidMarx Both solutions don't give the same density plot as the original sample. That's a sample size problem.
Comment: see my comment on the question for why i am working with the small size. I ran @CnrL solution with the large N (check the link in my earlier comment) and it still gives a lower peak..
Comment: @HongOoi I don't get the same result for your solution as with CrnL's solution. Here's a comparison of the density I'm getting from your solution (N=1e5), his solution (N=1e5) and the original small dataset.: http://i.imgur.com/cMKnhhf.jpg
Comment: @DavidMarx Then you're doing something wrong. I just ran both with N=1e6 and got virtually identical results. In particular, make sure you're using the same bandwidth for everything.
Comment: Yeah, disregard. I just tried clearing out CrnL's example code and re-copy pasting and yours and his looks the same (and frankly, both look like Roland's deleted solution as well). Sorry forraising the alarm.
Comment: @AdvaitGodbole Nobody can access your Google drive. Regardless, all the answers here will give you the same solution (some may take a bit longer than others). If they don't happen to match what you intuitively think the density should look like, well... people have already pointed you to CrossValidated.
Comment: i assumed the links could be accessed, i havent used drive before. also, i ran your code again and it seems i made a was looking at the wrong plot earlier. so, yes it is giving me the expected shape. thanks.
Answer: Your approach is correct.
For each sample from your mixed distribution you just need to choose which of the two component Gaussian distributions the sample should come from and then draw the sample from that distribution.
You can choose between the two distributions using the mixture proportions you have found: simulate a random number between 0 and 1 and sample from the first distribution if it the random number is less than the first proportion, otherwise sample from the second distribution.
Finally, sample from the relevant Gaussian distribution using the rnorm function.
dat.demand2050.mixmdl.prop=c(0.2783939,0.7216061)
dat.demand2050.mixmdl.means=c(56.21150,73.08389)
dat.demand2050.mixmdl.dev=c(3.098292,6.413906)

sampleMixture=function(prop,means,dev){
    # Generate a uniformly distributed random number between 0 and 1
    # in order to choose between the two component distributions
    distTest=runif(1)
    if(distTest<prop[1]){
        # Then sample from the first component of the mixture
        sample=rnorm(1,mean=means[1],sd=dev[1])
    }else{
        # Sample from the second component of the mixture
        sample=rnorm(1,mean=means[2],sd=dev[2])
    }
    return(sample)
}

# Generate a single sample
sampleMixture(dat.demand2050.mixmdl.prop,dat.demand2050.mixmdl.means,dat.demand2050.mixmdl.dev)

# Generate 100 samples and plot resulting distribution
samples=replicate(100,sampleMixture(dat.demand2050.mixmdl.prop,dat.demand2050.mixmdl.means,dat.demand2050.mixmdl.dev))
plot(density(samples))

Comment: You're welcome.  No, it doesn't imply that.  This is because of the "if" condition.  Using runif() is only a way to introduce randomness into the choice between the distributions.  There is an exactly 28% chance that the value returned by runif() will be less than 0.28 (and conversely a 72% chance that it returns a value greater).  By checking whether runif is greater than or less than the first proportion (0.28 in this case) and choosing the first or second component of the mixture accordingly, we weight the probabilities correctly.
Comment: You should avoid the loop. Create 100 samples each from the two normal distributions and the uniform distribution and use `ifelse`.
Comment: @Roland Your suggestion above would certainly make things faster and your answer below is very elegant, however I prefer the less speedy code above for this question as I think it makes it clearer to the OP how the sampling works.
Comment: thanks, your solution seems to work well. However, doesnt the choice of `runif()` for `distTest` imply that it a value being from either distribution is equally probable, whereas the data (and the fit) suggest that the "probabilities" are about .3 and .7?
Comment: @AdvaitGodbole Those probabilities are taken into consideration in the `if` statement. The function samples from the uniform distribution so that we randomly select from one mixture or the other, but that selection will occur as specified by those probabilites.
Comment: @AdvaitGodbole I deleted the answer because after some testing and reading the documentation I was not absolutely certain that the sampling wouldn't be biased.
Comment: @Roland, ok perhaps that is what is causing the higher peak for the 'left' distribution..
Comment: @Roland I found the same thing, your earlier solution seems to overemphasize the lower distribution. I tried refactoring @CnrL's solution to use ifelse and found I got the same result: `sampleMixture=function(prop,means,dev, N){
  distTest=runif(N);
  l_sample = rnorm(N,mean=means[1],sd=dev[1]);
  u_sample = rnorm(N,mean=means[2],sd=dev[2]);
  sample = ifelse(distTest<prop[1], l_sample,u_sample);
  return(sample);
}`
Comment: Nevermind, I think your solution worked find @Roland, and I actually somehow mucked up CnrL's solution to give a different result.
Comment: For what it's worth, I would expect the two solutions to sample from the same distribution, I can't see a reason for a difference.
Comment: The difference was that I mucked something up in your code, which gave a less pronouncedly bimodal solution than it should have.
Comment: i am accepting @HongOoi's answer for 2 reasons - its less code and when i have multiple modes it will be easily extendable. however, as you rightly pointed out earlier, your answer was great to get an intuitive sense of the sampling process.


Does the Daytona International Speedway have more crashes than other tracks?

Question: I'm watching the coverage of the delayed Coke Zero 400 on NBC, and as I write this, the race is about to begin.  The commentators seemed to suggest that drivers are much more likely to experience crashes at Daytona then they are on other tracks.  Is this true?  If so, why?
Admittedly, the start of the race has been delayed for a while now, and the commentators are probably running out of things to say.  I know very little about NASCAR, so I have no idea if it is true or not.
Comment: On the surface this seems true (more crashes) but you know how those things go.  I like this question.  Now wondering how to get the data   :-)
Answer: I'm actually having a really tough time finding stats for this, which is kind of odd given the public's propensity for crashes. The best I've been able to find is this USA Today article, which takes a look at crashes throughout the 2009 season. It also includes an infographic breaking down crashes by track for the season:

As you can see, Daytona is relatively average when it comes to crash rate. The article says:

"Not surprisingly, Martinsville Speedway, Bristol Motor Speedway and Richmond International Raceway, the three shortest tracks on the circuit, recorded the most crashes and spins in 2009."

It seems the shorter tracks tend to have more crashes, which I suppose makes more sense given that most passes occur during/coming out of a turn.
Comment: One thing to consider is how many cars are involved per crash.  At the short tracks, it is typically one or 2. Since the cars are all in a large pack, the crashes at Daytona and Talladega will involve more cars per crash.


What function or $user variable do I edit to manually increase a user's session timeout?

Question: I'm using the simpleSAMLphp module which redirects the user offsite to login and then hits them back to drupal in a logged in state, but for some reason the sessions aren't getting applied. When the user closes the browser it causes the user to be logged out.
But when I login via the drupal login page, the user session persists even if the browser is closed.

What function should I look for in the simpleSAMLphp module where it logs the user in?
What might I need to know or edit to make a assign a session time to a user?
Is the session information stored in the $user variable and can I manipulate it from there? or is it a database edit?
Comment: It would be useful to see the code you're using to auto login the user. It's probably relevant
Comment: hi clive! actually i just updated the question, its not a module i wrote, but its the simpleSAMLphp module. thanks!
Answer: There are several modules that can do this for you.
https://www.drupal.org/project/session_cookie_lifetime
https://www.drupal.org/project/remember_me
https://www.drupal.org/project/persistent_login
I've had some problems with remember me and am still testing the others, but they give you more control over the session lenght.
By default drupals session expire after about 3 weeks, according to
<code>ini_set('session.cookie_lifetime',  2000000);
</code>
You should be able to override this variable at database level as well, if you want to.


Hide a radio button visibility once it is clicked for the whole project in C# for a Windows Phone 8 application

Question: I have code as :
           if (rb1.IsChecked.Value)
            {
            NavigationService.Navigate(new Uri("/enterque.xaml?chkd=" + rb1.IsChecked,
            UriKind.Relative));
            this.rb1.Visibility = Visibility.Collapsed;
            }

When rb1 is checked it collapse its visibility on coming back to this page. But When I navigate to same page again via MainPage it is again visible ??
Is rb1.visibility is having only local scope ?
Answer: You should use listener event, once radio button click, you need to handle clicked event
and then hide the radio button.
Hope following link may helpful.
https://groups.google.com/forum/#!topic/codenameone-discussions/WSRld91pSas
Answer: you can take one Visibility Variable in App.xaml.cs file n it would hold the value for state for Visibility IN Application.
Declaration:
public static Visibility radVisibility = Visibility.Collapsed;

Use:
rb1.Visibility = App.radVisibility;

Declare it in App.xaml.cs
public static Visibility radVisibility = Visibility.Visible;

MainPage.cs:
if (rb1.IsChecked.Value)
{
    App.radVisibility = Visibility.Collapsed;
    this.rb1.Visibility = App.radVisibility;
    NavigationService.Navigate(new Uri("/enterque.xaml?chkd=" + rb1.IsChecked,UriKind.Relative));
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    this.rb1.Visibility = App.radVisibility;
}

Comment: it is working same as  this.rb1.Visibility = Visibility.Collapsed;   I need radiobutton should be disabled once it is clicked in the project. The problem with rb1.visibility = app.radvisibility is that once i comes to same page where radiobuttons are placed via "BACK" button it is visible.
Comment: you would also need to set value of radiobutton at onNavigatedTo as it is static so you can hold it in whole application
Comment: i am not able to do it, can you please help with the code.
Comment: now the new issue arised... rb1 is collapsed once the app starts... #serious_trouble
Comment: It should not be. but you can set radVisibility = Visibility.Visible; in Constructor for the Application object that is App(){radVisibility = Visibility.Visible;}, Try it out.


Doing a scipy.optimize.root runs out of memory, what are good alternatives?

Question: So I'm trying to use scipy.optimize.root but I'm running out of memory, the reason being there isn't enough memory to calculate the jacobian.
I was wondering what alternative I might be able to use given my memory constraint?, or is there a way to circumvent it somehow?
My input size is ~400,000 and the output is similar, meaning the jacobian is 400,000^2 which is a killer...
Please let me know if you have any suggestions to make the question clearer.
UPDATE
I think I've figured out a way to calculate the jacobian at any given point efficiently. The documentation of scipy.optimize.root states the following:

If jac is a Boolean and is True, fun is assumed to return the value of Jacobian along with the objective function. If False, the Jacobian will be estimated numerically. jac can also be a callable returning the Jacobian of fun. In this case, it must accept the same arguments as fun.

I'm guessing from the highlighted point what it means is if fun(x) is my funcion it gives something like:
f, jac = fun(x)

where f = f(x) and jac = jacobian(x).
right?
Comment: Which _method_ are you using and what is your _jac_ argument set to?
Comment: Using default for both, ie not passing anything
Answer: Try using method='krylov'.
See also http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#root-finding-for-large-problems
If you know the jacobian, you can write your function so that f, jac = fun(x) and give the jac=True option to root. However, given that several of the methods do not support sparse jacobians, this may not help you.
The next best thing is then to use use the sparse jacobian as a preconditioner for the Krylov method.


From $\Bbb R^n$ to $\Bbb R^m$?

Question: I have some questions that are all related.
They all revolve around getting a better understanding of phrases like "the column space of $A$ is a subspace of $\Bbb R^m$, not $\Bbb R^n$).
Similarly, a linear transformation is said to take something from $\Bbb R^n$ to $\Bbb R^m$. What exactly does that mean to take something from $\Bbb R^n$ to $\Bbb R^m$?
Does $\Bbb R^n$ represent the number of column vectors?
Does $\Bbb R^m$ represent the number of components/elements of those vectors? (I.e.. So if I had two column vectors that would be $\Bbb R^n$ but if those two columns had $5$ components/elements that be $\Bbb R^m$?)
If it does represent these things, I'm still not sure what it means that something "lives in" $\Bbb R^m$ as opposed to $\Bbb R^n$.
Thanks for any help
Comment: It's the number of dimensions in the space. Generally, $\mathbb{R}^k$ is a $k$-dimensional space, where each element is a real number. So, if a vector is an element of $\mathbb{R}^k$, it has $k$ components, one for each dimension. A vector with 3 real components is an element of $\mathbb{R}^3$, a coordinate pair of the form $(x,y)$ where $x$ and $y$ are both real is an element of $\mathbb{R}^2$, etc.
Comment: A linear transformation doesn't "live" in either space, as you frame it, but maps elements from one space to the other. Let's say you have a matrix $T$ that maps from $\mathbb{R}^n$ to $\mathbb{R}^m$. Then, given a vector $x$ in $\mathbb{R}^n$ (so $x$ has $n$ components), the vector that results from the operation $Tx$ is an element of $\mathbb{R}^m$ (it has $m$ components).
Comment: The vector x would be based on the number of columns/variables , correct? And the vector that results from the Matrix/Vector product is an element of Rm because???
Comment: The vector $x$ would be an $n \times 1$ matrix, just a single column with $n$ elements. If $T$ maps from $\mathbb{R}^n$ to $\mathbb{R}^m$, then $T$ is an $m \times n$ matrix. And then, when you multiply $Tx$, you have an $m \times n$ matrix times an $n \times 1$ vector, resulting in an $m \times 1$ vector (column with $m$ elements), and that's an element of $\mathbb{R}^m$.
Answer: The fundamental concept you need to understand is that of a function/mapping. Roughly speaking, a function consists of a triple of information $(f,X,Y)$. Here, $X$ and $Y$ are sets, and $f$ is a "rule" which assigns to each element of $X$ a uniquely determined element of $Y$. We write this as $f:X\to Y$. The set $X$ is called the domain of $f$, the set $Y$ is called the target space/codomain of $f$; also given an element $x\in X$, we denote by $f(x)\in Y$ the uniquely determined element of the set $Y$ which corresponds to $x$ via the rule $f$.
Now, I've mentioned that $X$ is the domain and $Y$ is the target space. There is another important subset to keep in mind, namely the image $f[X]:=\{f(x)\,|\, x\in X\}$. This is the set of all possible outputs. Note that $f[X]$ is always contained  in $Y$, meaning $f[X]\subset Y$, but it need not be equal (think of $Y$ as a dart board, and $f$ as a machine which shoots darts (i.e elements of $X$). Then all the places on the dart board which actually get hit by a dart is called the image).
In the context of linear algebra and matrices, what is going on is that if you're given an $m\times n$ matrix $A$ with real entries, then we can define a function $f_A:\Bbb{R}^n\to\Bbb{R}^m$. How? Essentially by matrix multiplication:
\begin{align}
f_A(x):= A\cdot x
\end{align}
where we think of $x$ as a column vector ( $A$ is $m\times n$ and $x$ is $n\times 1$ so the result $A\cdot x$ is $m\times 1$ so everything makes sense). Note that all we're doing is giving a certain rule for how elements of one set, $\Bbb{R}^n$, get mapped to the elements of another set, $\Bbb{R}^m$.
When talking about the column space of the matrix $A$, this is nothing but the image of the function $f_A$ in the sense I have defined above, i.e
\begin{align}
\text{column space}(A)&\equiv f_A[\Bbb{R}^n]=\{f_A(x)\,|\, x\in \Bbb{R}^n\}=\{A\cdot x\,|\, x\in \Bbb{R}^n\}\subset\Bbb{R}^m
\end{align}
In words, it is the set of all possible outputs of the function $f_A$. As you can see from the definition itself, the column space of $A$/ the image of the function $f_A$ is a subset of the target space $\Bbb{R}^m$.
Note that you shouldn't place so much emphasis on the letters $m,n$. What is important is to keep track of the domain and target space. For example, if $A$ is a $4\times 7$ matrix (i.e $4$ horizontal rows and $7$ vertical columns) then we get an associated function $f_A:\Bbb{R}^7\to\Bbb{R}^4$. So, the column space of the matrix will be a certain subset of $\Bbb{R}^4$.
Perhaps one slightly confusing situation is when $m=n$. For example, suppose $A$ is an $8\times 8$ matrix. Then, the function is $f_A:\Bbb{R}^8\to\Bbb{R}^8$. In this case, the image is a subset of $\Bbb{R}^8$, which is both the domain and target space. But in this situation, conceptually we should think of two different copies of $\Bbb{R}^8$, one which represents the domain and another which represents the target space.

From $\Bbb R^n$ to $\Bbb R^m$?


Finding the limit based upon following condition!

Question: Consider the function
$$
f(x)=\lim _{n \rightarrow \infty} \frac{\log _{e}(2+x)-x^{2 n} \sin x}{1+x^{2 n}}, x>0
$$
Is $f(x)$ continuous at $x=1 ?$ Justify your answer.

Applying basic theorem of continuity,calculating  the function value $\lim_{h\to1^{+}} f(h+1)$ and $\lim_{h\to1^{-}} f(1-h)$, and then $f(1)$ ..I am getting this as non continous. Am I wrong?
Comment: Why $f(h+1)$ and $f(1-h)$ when $h$ is around $1$? Did you intend to write those limits as $h\to 0^+$?
Answer: Hint: Recall that $x^{k} \to 0$ as $k \to \infty$ if $0<x<1$ and $x^{k} \to \infty$ as $k \to \infty$ if $x>1$. Hence. $f(x)=\log_2(2+x)$ for $x <1$ and $f(x)=-\sin x $ for $x >1$. The left hand limit is $\log_e 3$ and the right hand limit  is $-\sin 1$ These are not equal so $f$ is  not continuous at $1$.


Is there a more suitable way to merge video and audio files in Python than ffmpeg?

Question: Somehow only 1080p60fps files can be rendered with the following command:
ffmpeg.output(input_au, input_vi,"movie.mp4").run()

For example, if I use a YouTube video that has only 1080p but no 60fps, the error message:
"ffmpeg error (see stderr output for detail)"

appears. So how can I render video and audio files in case you want to download YouTube videos with bigger resolutions than 720p? (I'm using pytube dash download, i.e. getting video without audio and the audio as an extra file). Maybe there is also solution to come without ffmpeg, e.g. download the highest available resolution. But as far as I know the pytube library doesn't support progressive downloads for higher resolutions.
Answer: I use MEncoder for video rendering. Here is the doc : http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.html
This is not a Python library but you can use it with os.system("mencoder ...") or subprocess.
You can use scale and aspect options to render your video with the wanted resolution.


Nem sempre usar o botao anexo

Question: tenho uma duvida
o meu programa consiste em enviar e-mail com anexos mas as vezes quando não quero enviar um email com anexos da-me um erro
Alguém pode ajudar?
Eu consigo enviar e-mail com anexos sem problemas mas sem anexos não funciona
codigo:
 private void button4_Click(object sender, EventArgs e){
SmtpClient cliente = new SmtpClient();
            MailMessage msg = new MailMessage();

        msg.Attachments.Add(new Attachment(Anexostxt.Text));
        msg.Attachments.Add(new Attachment(anexos2.Text));
    }

private void button6_Click(object sender, EventArgs e){
    OpenFileDialog dlg = new OpenFileDialog();

    if(dlg.ShowDialog()==DialogResult.OK){
        string picpath = dlg.FileName.ToString();
        Anexostxt.Text = picpath;
    }
}

Erro  Additional information: O parâmetro 'fileName' não pode ser uma cadeia vazia.
Comment: Pela imagem está obvio que `Anexostxt.Text` está vazio, o porquê? Só o vendo o código. Mostre o trecho de código onde `Anexostxt.Text` é setado.
Comment: Prefira colocar codigo e nao imagens. Coloque a mensagem da excepçao e o *stack trace* da mesma.
Comment: este print ajuda?
Comment: Não, pelo que entendi, `Anexostxt.Text` refere-se ao arquivo anexo. Portando onde está setando este método? Algo assim: `Anexostxt.Text = "c:\meuanexo.txt"`
Comment: a mensagem é : "O parâmetro 'fileName' não pode ser uma cadeia vazia.\r\nNome do parâmetro: fileName"}
Answer: Supondo que o button4 seja o que envia o email, se você não quer anexos precisa verificar se o seu campo de anexo está em branco. Por exemplo:
private void button4_Click(object sender, EventArgs e){
    if(Anexostxt.Text != "") {
        msg.Attachments.Add(new Attachment(Anexostxt.Text));
    }
    if(anexos2.Text != "") {
        msg.Attachments.Add(new Attachment(anexos2.Text));
    }
}

Isso é só um princípio básico, provavelmente você irá precisar de validações adicionais (por exemplo, verificar se os campos não contêm somente espaços, ou se apontam para um arquivo válido, etc.)
Comment: nao identifica o msg :/
Comment: Funciona!! obrigado!

Nem sempre usar o botao anexo


Remove multiplication symbol (×) from URL

Question: Below is a URL in which multiplication symbol × is coming. It is not 'x'. I checked for its ascii value but was not able to find it. I only got how to create it (alt+158).URL: http://localhost:6000/SearchService/SearchService.svc/GetSearchResults?srchKeyword=test×projectId=2&user=3I am creating this url in javascript. I tried replacing %C3%97with empty string but it didn't worked. Kindly tell me how to remove it as i am getting incorrect result.
Answer: You can simply replace this character using String.prototype.replace:

var url = "http://localhost:6000/SearchService/SearchService.svc/GetSearchResults?srchKeyword=test×projectId=2&user=3";

document.body.innerHTML += "
" + url + "
";

url = url.replace('×', '');

document.body.innerHTML += "
" + url + "
";

At the same time, it is a good idea to understand the reason of appearance of this character instead of handling the consequences.
Comment: This will only replace the first occurrence. To replace all, use `url = url.replace(/×/g, '')`
Comment: I am using token input in search textbox and in that there is an image to delete the keyword. Its my guess that I might be getting that as multiplication symbol but I am not sure about it. :(


db_query(); -- list of files attached to a node?

Question: I have a DRUPAL_BOOTSTRAP_DATABASE .php -script that loads info based on the nid it gets via POST request.
I need to list files attached to the requested node, and I know how to do this in D6, but after spending 30min trying to understand the new table structure of Drupal 7, I cannot fathom how to pull the fid (or any other file info related to the node) via a db_query();
I've been trying to read Devel query log to get a hang of how Drupal handles this to no avail. Any insight into my problem would be greatly appreciated. :)
Answer: replace uppercase by your data:
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$sql = 'SELECT f.* FROM {field_data_field_YOURFIELDFILENAME} ff INNER JOIN {file_managed} f ON ff.field_file_fid=f.fid WHERE ff.entity_type = :etype AND entity_id=:nid';
$result = db_query($sql, array(':etype'=>'node', ':nid' => YOURNID));

foreach($result as $row) {
  print_r($row);
}

Create custom function for processing uri: public://FILENAME.EXT and getting right path from this.
Comment: You can either create your own answer or you can edit the answer from Nikit. This is like a wiki, everyone can edit everything (although edits require review of someone else if you don't have enough points)
Comment: I only have the nid to begin with, and I'm working with DRUPAL_BOOTSTRAP_DATABASE due performance reasons. Did you even read the question?
Comment: Changed due to comment.
Comment: Did not work for me, but led me on the right track so upvoting for that. I guess the schema difference might be due using field_collections so I had to INNER JOIN more tables. Here is my solution: http://pastie.org/private/fsi1xdasqat8dnhbkgnz4a
Comment: 2red: what error it's show, as I wrote you should replace uppercase text.
Comment: I decided to reply separately as Nikits post could be more helpful as a generic reply to others compared to my final solution.
Answer: Here's the final solution to pull the data from {file_managed} and another field to be returned as json based on GET parameter nid.
<?php
  // only take action on GET parameters
  if ( !empty($_GET) ) {

    // escape and map GET parameters
    $post = array_map('mysql_escape_string', $_GET);
    $nid  = $post['nid'];

    // we have a numerical nid
    if ( is_numeric($nid) && !empty($nid) ) {
        // switch to drupal root, as relative to our module path
        chdir('../../../../../../');
        // define root dir
        define('DRUPAL_ROOT', getcwd());

        // load drupal db layer
        require_once './includes/bootstrap.inc';
        drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

        // regardless of is audio data found, we return the edit path of the node
        $temp = new stdClass();
        $temp->path = "node/$nid/edit/";
        $temp->nid  = $nid;

        // grab audio urls and slot states
        $params = array(':nid' => $nid);
        $sql    = "SELECT      f.filename,
                               f.uri,
                               fss.field_slot_state_value state
                    FROM       field_revision_field_related_audio AS fra
                    INNER JOIN field_revision_field_audio_file AS faf
                            ON faf.entity_id = fra.field_related_audio_value
                    INNER JOIN file_managed f
                            ON faf.field_audio_file_fid = f.fid
                    INNER JOIN field_revision_field_slot_state fss
                            ON fss.entity_id = fra.entity_id
                    JOIN       node n
                            ON (fra.revision_id = n.vid AND fss.revision_id = n.vid)
                    WHERE      n.nid = :nid
                    AND        fra.entity_type = 'node'";

        $results = db_query($sql, $params);

        // if we have results, display them in json format
        if (!empty($results)) {
          $i = 0;

          foreach ($results AS $result) {
            // add the state just once, as it's the same for each file
            if ( $i == 0 ) {
                  $temp->state = $result->state;
            }

            // add all audios related to production
            $temp->audio->{$i++} = $result->uri;
          }
        }

        // encode to json and spit out
        $json = json_encode($temp);
        print $json;
      }
    }

?>


Show markers on gmap from all nodes exposed in view

Question: I'm using gmap module to mark job locations on a map. It now shows all locations of content type: jobs. Is there any way I can only mark the displayed jobs from my view block? I filter the jobs through exposed filters.
EDIT:
Just going to add this code here, might be useful for some. It puts the attachment in a block so you have more control over it.
<code><?php
//Puts gmap attachment in block so it's easier to theme

function gmap_block_block_info() {
  $blocks['gmap_attachment'] = array(
    'info' => t('Gmap Attachment'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function gmap_block_block_view($delta = '') {
  $block = array();
  if ($delta == 'gmap_attachment') {
   // $block['subject'] = t('Gmap Attachment');
    // Load the view.
    $view = views_embed_view('jobs_view_block', 'gmap_attachment');
                        //('machine_name_view', 'machine_name_display)
    if ($view) {
      $block['content'] = $view;
    }
    else {
      $block['content'] = t('The view is empty');
    }
  }
  return $block;
}
</code>
Answer: If you set up the map display as an attachment, you can set it to inherit the exposed filters that you've defined for your job listing. You'll get one set of exposed filters that controls both the listing and the map.
There may be some issues - see this blog post by someone solving what looks like the same problem.
Comment: Thanks, just adding it as an attachment did the trick, really simple!


Qual a vantagem de se utilizar getters/setters em classes com JavaScript?

Question: Por exemplo neste código abaixo utilizo de métodos getters e setters na classe:

class Pessoa {
  constructor(nome) {
    this.nomePessoa = nome;
  }
  get _nomes() {
    return this.nomePessoa;
  }
  set _nomes(valor) {
    this.nomePessoa = valor;
  }
}

const nomes = new Pessoa("Fulano");
console.log(nomes._nomes);                         // Fulano

nomes._nomes = "Ciclano";
console.log(nomes._nomes);                         // Ciclano

O programa retorna os dados corretamente, porém, posso obter os mesmos resultados com uma sintaxe muito mais simples:

class Pessoa {
  constructor(nome) {
    this.nomePessoa = nome;
  }
  _nomes() {
    return this.nomePessoa;
  }
}

const nomes = new Pessoa("Fulano");
console.log(nomes._nomes());                       // Fulano

nomes._nomes = "Ciclano";
console.log(nomes._nomes);                         // Ciclano

Qual seria o real emprego de métodos getters/setters em classes JavaScript?
Há alguma vantagem em utilizá-los, se é que são necessários?
Comment: LeAndrade, você está sobrescrevendo o método com uma string. O que acontecerá se você invocar `nomes._nomes()` depois de fazer `nomes._nomes = "Ciclano"`?
Comment: E como ficaria o *setter* no segundo exemplo?
Comment: `nomes._nome = "Ciclano"` eu não estou setando um novo valor?
Answer: Vantagens gerais
A vantagem é mais ou menos a mesma do uso em outras linguagens do ponto de vista conceitual, desde que seja necessário fazer algo relevante ali, o que não tem no exemplo.
O padrão de projeto getter e setter é uma forma de acessar um estado do objeto através de um método que pega o valor de um campo ou modificar o seu valor.
Se você faz isso pode executar algumas coisas em vez de simplesmente acessar o estado, então o getter pode não dar o valor bruto de um campo, mas sim algo calculado usando zero, um ou mais campos para obter o resultado, portanto ele nem precisa estar vinculado a um campo específico. Um setter pode manipular o valor recebido antes de gravar em um campo, ou pelo menos validar se o valor recebido está dentro do que se espera.
Em geral esse padrão é feito com métodos normais. Algumas linguagens provem uma sintaxe que faz com que estes métodos se confundam com o acesso ao campo, é o caso do JavaScript, e é disso que você está falando. Desta forma é possível fazer com que esses métodos se passem como se fossem campos (que as pessoas chamam erroneamente de atributos), mas é um truque de sintaxe.
Algumas pessoas não gostam disto porque esconde alguma lógica que está por trás de algo que parece ser um simples acesso ou atribuição a uma variável. Mas se essa execução é detalhe de implementação então não importa, quem consome não deveria saber mesmo.
Uma vantagem que essas linguagens dão é que você pode começar usar o campo normalmente e depois mudar para um getter e setter sem mudar nada na sintaxe, então fica transparente uma mudança, você não precisa criar esse padrão antecipadamente.
Em outras linguagens pode ser útil já criar esse padrão de getter/setter mesmo que não vá usar porque se um dia precisa implementar alguma lógica já tem a sintaxe de método e não de campo. Em JS não precisa fazer isto porque a sintaxe do campo de do getter/setter é a mesma. Exemplo de linguagem que precisa é Java. Por isso Java pode se beneficiar mais de usar esses métodos mesmo que eles não façam nada, se um dia mudar, não precisa sair mudando os códigos consumidores.
Outras linguagens possuem sintaxe igual ao JS, mas elas possuem binding* antecipado, então mesmo que não precise de uma mudança de sintaxe se você passar de um campo para um getter/setter precisa recompilar o código todo de novo para ele fazer um novo binding e assim o código chamado se referenciar à nova forma agora com métodos transparentes sendo chamados para fazer o get e o set. Exemplo é C#. Se você muda um código consumidor de uma chamada ao campo para uma chamada ao método, tudo bem com a sintaxe, o problema é que se o código consumidor é compilado em ciclo diferente do código da sua classe que teve uma mudança de campo para método getter/setter (mesmo com sintaxe de campo como ocorre em C# ou JS), o código consumidor só saberá disso quando ele for recompilado olhando para a nova classe.
"Vantagem" de usar getter/setter que acrescenta nada
Em JS não existe compilação, o binding é feito na execução, então nem isso é problema para ela. Se está perguntando se deveria usar getter/setter todas as vezes mesmo que não tenha lógica alguma, então, não, em JS não tem vantagem. A vantagem se dá no momento que tenha alguma lógica no acessador ou modificador, portanto, algum algoritmo executando seja no getter, seja no setter.
Use a sintaxe simples até precisar de algo mais complicado.
Mas claro, se um dia achar uma implementação de JS compilada, tem que pensar. Sua classe será consumida por sua equipe e poderá garantir que o código consumidor dela sempre será recompilado se a classe mudar também vai bem, mas se for usada por terceiros, se você não puder controlar quando o código consumidor for recompilado, aí você pode estar em problemas. Mas não vamos dar certeza, vai depender de como isso for implementado nesta hipotética implementação de JavaSrript.
Algumas pessoas usam o getter/setter mesmo sem precisar porque leram em algum lugar que é pra fazer assim e como elas não aprenderam a programar mas sim a seguir receitas de bolo que não entendem elas fazem coisas sem sentido e prejudicam seu próprio código. Algumas pessoas só fazem porque a equipe é gerenciada por alguém assim que obriga fazer isso.
Coloquei no GitHub para referência futura.

*O momento que o código real é efetivamente vinculado à chamada. Em linguagens compiladas costuma ser o momento da compilação (em alguns casos pode ser no momento do linking (em alguns casos momento da carga) ou até do JITer do código, mas não assuma nada, cada implementação é de um jeito. Em linguagens interpretadas, a não ser que tenha alguma otimização ou algo na especificação que diga algo diferente, o vínculo é sempre no momento que vai executar, então qualquer mudança em uma parte do que está sendo executado para rodar a aplicação já é percebido pela aplicação toda, a não ser que use algum truque específico.
Comment: Perfeito man, mas, uma vez bastante esclarecedor.
Comment: O negativo deve ter sido dado porque alguém que aprendeu que a receita de bolo deve ser seguida sempre.
Comment: Muito provavelmente :)
Answer: É mais uma questão de opinião. Creio que a corrente mais comum de opinião desencoraja o uso de tal forma de declaração, alguns motivos incluem:

Legibilidade de código, código não-explícito (um acesso a uma propriedade está na verdade chamando uma função);
É mais complicado de sobrescrever a função (você terá que usar um dos métodos base de objeto do javascript);
Otimizações de empacotadores. Empacotadores de código javascript (webpack, rollup) usam lógicas pra determinar se uma seção de código é ou não usada e removê-la da compilação final. O uso de getters e setters pode evitar a marcação de uma seção de código pra remoção (o bundler não tem como saber se aquele código é acessado por poder gerar "side-effects").

Você pode ver o uso frequente desses recursos na própria API DOM, por exemplo, ao escrever window.location.href = 'xxx' você está na verdade invocando um setter. Pode ser até útil em casos de refactor mas realmente fica mais a seu critério e do problema que você precisa solucionar.
Comment: Boa explanação, realmente é de se pensar o uso. Obrigado por responder.
Answer: Primeiro: Qual o motivo de usar os Getters and Setters?
Eles são utilizados se outros objetos precisam de acesso aos atributos, o objeto
fornece operações públicas (conhecidas como getters e setters) para manipular esses atributos. Ou seja, uma forma de acessa seus atributos em uma classe que é privada e está encapsulada.
Getters é conhecido como Acessor e Setters como Mutator, ambos estão na padronização do ECMAScript. Exemplo de uso: https://www.w3schools.com/js/js_object_accessors.asp
Então não é a questão de ser algo apenas relevante, é como se pega valores dos atributos em POO seguindo a padronização.
Qual a vantagem? - talvez alguns já façam isso e nem sabe que está utilizando Acessors ou Mutator, que nada mais é que pegar valores e atribuir valores de uma classe como já explicado, porém, de forma encapsulada.
É a prática da POO, em acessar as variáveis de um objeto, não é questão de vantagem, ou ser um super projeto, é nada mais que a maneira correta de se fazer. Como já citei, está no padrão estabelecido pelo JavaScript e quem procurar vai ver que é um padrão de POO.
Independente da linguagem é esse o conceito e o motivo de ser utilizado, agora como vai ser utilizado cada linguagem tem a maneira correta de se fazer.
Exemplo: getter

// Create an object:

var person = {
  firstName: "John",
  lastName : "Doe",
  language : "en",
  get lang() {
    return this.language;
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;

Exemplo: setters

  var person = {
  firstName: "John",
  lastName : "Doe",
  language : "",
  set lang(lang) {
    this.language = lang;
  }
};

// Set an object property using a setter:
person.lang = "en";

// Display data from the object:
document.getElementById("demo").innerHTML = person.language;


Passing parameters between Velocity templates

Question: I am trying to find out how to pass parameter while calling a velocity template from another.
it looks like this
File: _reading_tracker.vm
#parse("student/shared/_bio_data.vm")

I need to pass some arguments to the _bio_data.vm. Not sure how to do this
Answer: Instead of parsing _bio_data.vm, try creating a macro, and then calling that macro from _reading_tracker.vm.
Or, if you don't want to use a macro, then you should be able to #set($var="value") any number of variables in the outer template, and refer to those variables in the inner (parsed) template.
Comment: thank you...i was under assumption macros are meant only for common functions and should not contain html code


Finding difference between Mathematica code and R code for solving set of equations

Question: I have this Mathematica code trying to solve a set of equations:
f[k_, n_, p_, a_, b_] :=p*(Binomial[n, k]*a^k*(1 - a)^(n - k)) + (1 - p)*Binomial[n, k]*b^k*(1 - b)^(n - k));

    mom1 = Sum[k^1 *f[k, n, p, a, b], {k, 0, n}] - 3.3;
    mom2 = Sum[k^2*f[k, n, p, a, b], {k, 0, n}] - 13.04;
    mom3 = Sum[k^3*f[k, n, p, a, b], {k, 0, n}] - 58.08;
    mom4 = Sum[k^4*f[k, n, p, a, b], {k, 0, n}] - 281.96;

estimate = NSolve[{mom1 == 0, mom2 == 0, mom3 == 0, mom4 == 0, n > 6}, {p, a, b, n}, Reals]

And gives me the following output:
{{p -> -0.0000925709, a -> -1.15159, b -> 0.343157, n -> 9.61271}}

I am trying to do the same thing using R Software instead, by using the following code:
init=c(0.2, 9, 0.2, 0.2);

GetMoment<-function(x, k, ord){
  (k^ord)*DensityFn(x, k)
}

DensityFn<-function(x, k){
  x[1]*dbinom(k, x[2], x[3])+(1-x[1])*dbinom(k, x[2], x[4])
}

target<-function(x){

  y <- integer(4)

  x[2]=floor(x[2]);

  y[1]=sum(GetMoment(x, 0:x[2], 1))-3.3;
  y[2]=sum(GetMoment(x, 0:x[2], 2))-13.04;
  y[3]=sum(GetMoment(x, 0:x[2], 3))-58.08;
  y[4]=sum(GetMoment(x, 0:x[2], 4))-281.96;
  y
}

out=nleqslv(init, target);

print(out)

These should be equivalent, however the R output gives me the following output:
$x
[1] 0.2 9.0 0.2 0.2

$fvec
[1]    -2.438   -24.314  -226.394 -2120.652

$termcd
[1] 6

$message
[1] "Jacobian is singular (1/condition=0.0e+000) (see allowSingular option)"

$scalex
[1] 1 1 1 1

$nfcnt
[1] 0

$njcnt
[1] 1

$iter
[1] 1

Are the in fact the same? How come Mathematica manages to find a solution while my R code does not?
Comment: Also include `library(nleqslv)` in your code which is now incomplete. Rewrite the solution from `Mathematica` as vector in your R code. Use it as starting value and see if it is regarded as a solution.
Comment: Can you write out the moments and the constraints in mathematical notation instead of letting us debug R code based on Mathematica code?
Answer: Note that the values of a and p (since I presume that you are assuming a mixture distribution) given by Mathematica do not make sense theoretically.
Hence, R does not find this solutions since you are using dbinom and it does not accept negative probabilities. Thus, there seems to be no solution to your problem.
Comment: @DylanZammit, in depends on your problem. If you were given these moments as the true, theoretical ones, then you could conclude that there is no solution and perhaps consider a different distribution. Notice also that if we set `p` to zero, then `a` doesn't matter; and `p` is indeed almost zero. So, if possible, you could add a couple of more digits to the moment values to hopefully make `p` even closer to zero..
Comment: ..However, probably the moments are estimated, and then instead of solving a system of equations you could do some optimization. Then it will probably give you `p=0` as a solution.
Comment: maybe this is more of a statistical question, but if the solution is given by a negative probability as in this case, should I just consider it as 'p=0' and 'a=0' in practice?


Using version control/deployments with Context

Question: I've started to use Context. It actually works pretty well. I've created a context locally. It looks like, in order to get that context remotely, I have to export it and then copy and paste that into the remote server.
It's not a major pain, but we have dev, stage and live servers, plus the context isn't under version control, so any changes (or in fact the context itself) aren't stored in code.
Ideally, I'd have a situation like Views where I export the View, paste it into a file, deploy that file from version control to remote servers and the View updates on those servers.
Is this possible for context? Maybe using CTools?
The slight quirk is: I don't really like Features, and, at the moment, it seems overkill to add that as a module just for the sake of one context.
Answer: OK; so I swear I did look reasonably hard for this before I posted the question, but I have done the thing where I've genuinely found the answer 15 minutes after posting.
http://www.mcdruid.co.uk/content/default-drupal-contexts-like-default-views was the blogpost I needed - he's created an issue to get this information into the module, but it looks like it won't happened.
This seems to work really well, and I've created a separate submodule just for contexts.


Range of function $y=(e^x-e^{-x})/(e^x+e^{-x})$

Question: What will be the range of function $y=(e^x-e^{-x})/(e^x+e^{-x})$ ?
How should I approach this category of problems with exponential functions?  Please Help.
Comment: **Hint:** $y = \frac{e^{2x}-1}{e^{2x}+1}$.
Comment: It's very useful. Building on the algebraic step Sammy just gave

$$e^{2x} = \frac{1+y}{1-y}$$

which necessarily means that $\frac{1+y}{1-y} > 0$. We have immediately that $y < 1$ and $y > -1$. There is a value of $x$ that attains every value of $y$ in that open interval, hence the range is $(-1, + 1)$.
Comment: Solve that equation for $x$ and you'll see what are the valid values of $y$.
Comment: @SimonS: you're right, I was under the mistaken impression that it was difficult to do such an inversion.
Comment: @SanchayanDutta, look again at what I've written. Same thing.
Comment: Just to verify, you are talking about the function otherwise described as $y=\tanh x$, yes?
Comment: You are right.But actually I don't really know much about hyperbolic functions,so for the time being lets not use tanh x.  :-P
Comment: @SimonS: I'm not sure that's useful in this context...
Comment: -1<y<1 am i right ?
Comment: I guess you made a calculation mistake @SimonS its -1<y<1
Answer: One way to analyze the possible values the given function can take on is to transform it into the "simplest possible" form.  Some arithmetic we might apply could look like this:
$$y=\frac{e^x-e^{-x}}{e^x+e^{-x}}\\
=\frac {e^{2x}-1}{e^{2x}+1}\\
=1-\frac 2{e^{2x}+1}$$
We could go further with this directly and fully invert the function, but we can immediately make some conclusions from where we are now:

$e^{2x}+1\in(1,\infty)$
$\frac 2{e^{2x}+1}\in(0,2)$

This leads us to $y\in(-1,1)$.
Answer: You have $y=f(x)$. Solve for $x=g(y)$. Now find the domain for $g(y)$. That would be your "range".


Why Laravel reply 200 http code when MethodNotAllowedHttpException?

Question: Why Laravel reply 200 http code when MethodNotAllowedHttpException?
I Would like to recieve a diferent code, like 500.
I consume laravel routes using angular or postman, and recieve 200 code and is dificult to deal with this.
Below one example:
Comment: Share your controller
Answer: This is not a error, but the usage of the dd() dump and die helper method. This will always return a 200.
Find all dd(); methods in your project and it should work and return a proper error code. But secondly due to that error being thrown, it could seem like your url is invalid and or not allowing POST calls.


Using an electric bass guitar with a guitar amp / hi-fi system?

Question: I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment..
So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system..
I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
Answer: It is actually nowhere near as dangerous as you might think, as long as you keep the volume relatively low. You won't get an ideal frequency response, as a guitar amp is designed for the frequencies a guitar produces, but it will do as a stop-gap until you get a suitable amp.
The reason for keeping the volume lower than you might want to is that the large transients produced by a bass guitar could damage the electronics or the cone.
My experience has been that most amps cope with a lot more than they are officially specced for:-)
-oh, and depending on where you hook in, you can use a hifi as an amplifier. I have previously modified a 1956 radiogram and an original Sony Walkman to be guitar amps - both worked fine. In fact the radiogram had a wonderful sound!
Comment: I use a home stereo for bass training too. But to do it, you must be careful not only with the volume setting, but also the 'Bass' or 'Tone' setting (or equalizer, depending on the model). My 80's stereo performs great, but if the settings are too high, it starts to sound strange, and I'm afraid of damaging the speakers.
Comment: My parents' home hi-fi system is a very old Pioneer tube-based system, and it's got a lovely clean sound, but it has circuitry that cuts power to the tubes if you push it too hard, so like all non-bass amps you have to be careful with the volume.
Answer: With regard to hi-fis, one option that's not yet been discussed here is to use an amp-modelling pedal, such as the ones made by Line 6 and Zoom.
These take instrument-level inputs, and have line-level outputs. So you can safely connect them to the phono inputs of a hi-fi, or PC speakers, etc, while getting the sound of a "proper" bass amp.
Hi-fi speakers and amps are designed to play back recordings of bass parts, so they should be able to handle actual bass parts. Just don't crank it up louder than it's designed for.
Answer: Keep the volume low if your using a guitar amp for a bass. Last thing you want to do is crack the speakers in your amp if your playing the bass with high volume. Try to lower the bass on the amp as well.
Answer: I used a Line 6 Pod and a Midi-Man 6 channel mixer to get Line Out and piped it into my stereo system for over 10 years when I didn't have room for an amp for my Bass.
It sounded awesome with the sub that I have, it would shake the walls of the house. And a bonus I was able to run my drum machine and a few other things through the mini-mixer and get a clean balanced mix just like it was recorded. Way better than an amp in my opinion.
Now that I have more room, I still don't have any amps, I have a Bose L1 Model II instead, personally I don't have any use for bass or guitar amps.
I use a Roland V-Bass now and only use my Bass Pod Pro for when friends come over with their bass, but the idea is the same, as long as it is a Line Level output it is safe to run into a home stereo amplifier.
Answer: Keyboard amps and Electronic Drum Amps will work fine for bass. They both produce frequencies in the same range that a bass does. I'll leave the discussion of guitar amps and hifi's to what has already been contributed.
Answer: I was rehearsing at either guitar amp or home hi-fi.
First of all, you should low down all your switches, and only after that slowly add all of them. You should decide for yourself then to stop, generally you should simply avoid extraneous sounds from your hi-fi or amp.
I've switched into small Fender amp, something like that:

and standard hi-fi system, switched into the microphone hole,
and there were no problems at all, just in somewhat strange sound (not very bass).
This level is good for rehearsing, but if you are going to make some show, do not use this way - it's not worth.