Standard errors of hyperbolic distribution estimates using delta-method?

Question: I want to calculate the standard errors of a fitted hyperbolic distribution.
In my notation the density is given by
\begin{align*}
H(l;\alpha,\beta,\mu,\delta)&=\frac{\sqrt{\alpha^2-\beta^2}}{2\alpha \delta K_1 (\delta\sqrt{\alpha^2-\beta^2})} exp\left(-\alpha\sqrt{\delta^2+(l-\mu)^2}+\beta(l-\mu)\right)
\end{align*}
I am using the HyperbolicDistr package in R. I estimate the parameters via the following command:
hyperbFit(mydata,hessian=TRUE)

This gives me a wrong parameterization. I change it into my desired parameterization with the hyperbChangePars(from=1,to=2,c(mu,delta,pi,zeta)) command. Then I want to have the standard errors of my estimates, I can get it for the wrong parameterization with the summary command. But this gives me the standard errors for the other parameterization. According to this thread I have to use the delta-method (I do not want to use bootstrap or cross-validation or so).
The hyperbFit code is here. And the hyperbChangePars is here. Therefore I know, that $\mu$ and $\delta$ stay the same. Therefore also the standard errors are the same, right?
For transforming $\pi$ and $\zeta$ into $\alpha$ and $\beta$ I need the relationship between them. According to the code this is done as follows:
alpha <- zeta * sqrt(1 + hyperbPi^2) / delta
beta <- zeta * hyperbPi / delta

So how do I have to code the delta-method to get the desired standard errors?
EDIT: I am using these data.
I first perform the delta-method according to this thread.
# fit the distribution

hyperbfitdb<-hyperbFit(mydata,hessian=TRUE)
hyperbChangePars(from=1,to=2,hyperbfitdb$Theta)
summary(hyperbfitdb)

summary(hyperbfitdb) gives the following output:
Data:      mydata
Parameter estimates:
        pi           zeta         delta           mu
    0.0007014     1.3779503     0.0186331    -0.0001352
  ( 0.0938886)  ( 0.9795029)  ( 0.0101284)  ( 0.0035774)
Likelihood:         615.992
Method:             Nelder-Mead
Convergence code:   0
Iterations:         315

and hyperbChangePars(from=1,to=2,hyperbfitdb$Theta) gives the following output:
   alpha.zeta     beta.zeta   delta.delta         mu.mu
73.9516898823  0.0518715378  0.0186331187 -0.0001352342

now I define the variables in the following way:
pi<-0.0007014
lzeta<-log(1.3779503)
ldelta<-log(0.0186331)

I now run the code (second edit) and get the following result:
> se.alpha
         [,1]
[1,] 13.18457
> se.beta
        [,1]
[1,] 6.94268

Is this correct? I am wondering about the following: If I use a bootstrap-algorithm in the following way:
B = 1000 # number of bootstraps

alpha<-NA
beta<-NA
delta<-NA
mu<-NA

# Bootstrap
for(i in 1:B){
  print(i)
  subsample = sample(mydata,rep=T)
  hyperboot <- hyperbFit(subsample,hessian=FALSE)
  hyperboottransfparam<- hyperbChangePars(from=1,to=2,hyperboot$Theta)
  alpha[i]    = hyperboottransfparam[1]
  beta[i]    = hyperboottransfparam[2]
  delta[i] = hyperboottransfparam[3]
  mu[i] = hyperboottransfparam[4]

}
# hist(beta,breaks=100,xlim=c(-200,200))
sd(alpha)
sd(beta)
sd(delta)
sd(mu)

I get 119.6 for sd(alpha) and 35.85 for sd(beta). The results are very different? Is there a mistake or what is the problem here?
Answer: In the following solution, I assume hyperbPi to be $\pi$. Also, the variances used in the approximations below are simply the squared standard errors calculated by summary after hyperbFit, so $\mathrm{Var}(X)=\mathrm{SE}(X)^2$. In order to calculate the approximation using the delta-method, we need the partial derivatives of the transformation function s $g_{\alpha}(\zeta, \pi, \delta)$ and $g_{\beta}(\zeta, \pi, \delta)$. The transformation functions for $\alpha$ and $\beta$ are given by:
$$
\begin{align}
    g_{\alpha}(\zeta, \pi, \delta) &=\frac{\zeta\sqrt{1 + \pi^{2}}}{\delta}\\
    g_{\beta}(\zeta, \pi, \delta)  &= \frac{\zeta\pi}{\delta}\\
\end{align}
$$
The partial derivatives of the transformation function for $\alpha$ are then:
$$
\begin{align}
    \frac{\partial}{\partial \zeta} g_{\alpha}(\zeta, \pi, \delta) &=\frac{\sqrt{1+\pi^{2}}}{\delta}\\
    \frac{\partial}{\partial \pi} g_{\alpha}(\zeta, \pi, \delta)   &= \frac{\pi\zeta}{\sqrt{1+\pi^{2}}\delta }\\
    \frac{\partial}{\partial \delta} g_{\alpha}(\zeta, \pi, \delta)   &= -\frac{\sqrt{1+\pi^{2}}\zeta}{\delta^{2}}\\
\end{align}
$$
The partial derivatives of the transformation function for $\beta$ are:
$$
\begin{align}
    \frac{\partial}{\partial \zeta} g_{\beta}(\zeta, \pi, \delta) &=\frac{\pi}{\delta}\\
    \frac{\partial}{\partial \pi} g_{\beta}(\zeta, \pi, \delta)   &= \frac{\zeta}{\delta }\\
    \frac{\partial}{\partial \delta} g_{\beta}(\zeta, \pi, \delta)   &= -\frac{\pi\zeta}{\delta^{2}}\\
\end{align}
$$
Applying the delta-method to the transformations, we get the following approximation for the variance of $\alpha$ (take square roots to get the standard errors):
$$
\mathrm{Var}(\alpha)\approx \frac{1+\pi^{2}}{\delta^{2}}\cdot \mathrm{Var}(\zeta)+\frac{\pi^{2}\zeta^{2}}{(1+\pi^{2})\delta^{2}}\cdot  \mathrm{Var}(\pi) + \frac{(1+\pi^{2})\zeta^{2}}{\delta^{4}}\cdot  \mathrm{Var}(\delta) + \\
2\times \left[ \frac{\pi\zeta}{\delta^{2}}\cdot \mathrm{Cov}(\pi,\zeta) - \frac{(1+\pi^{2})\zeta}{\delta^{3}}\cdot \mathrm{Cov}(\delta,\zeta)- \frac{\pi\zeta^{2}}{\delta^{3}}\cdot \mathrm{Cov}(\delta,\pi)\right]
$$
The approximated variance of $\beta$ is:
$$
\mathrm{Var}(\beta)\approx \frac{\pi^{2}}{\delta^{2}}\cdot \mathrm{Var}(\zeta) + \frac{\zeta^{2}}{\delta^{2}}\cdot \mathrm{Var}(\pi) + \frac{\pi^{2}\zeta^{2}}{\delta^{4}}\cdot \mathrm{Var}(\delta) + \\
2\times \left[ \frac{\pi\zeta}{\delta^{2}}\cdot \mathrm{Cov}(\pi,\zeta) - \frac{\pi^{2}\zeta}{\delta^{3}}\cdot \mathrm{Cov}(\delta, \zeta) - \frac{\pi\zeta^{2}}{\delta^{3}}\cdot \mathrm{Cov}(\pi, \delta) \right]
$$

Coding in R
The fastest way to calculate the above approximations is using matrices. Denote $D$ the row vector containing the partial derivatives of the transformation function for $\alpha$ or $\beta$ with respect to $\zeta, \pi, \delta$. Further, denote $\Sigma$ the $3\times 3$ variance-covariance matrix of $\zeta, \pi, \delta$. The covariance matrix can be retrieved by typing vcov(my.hyperbFit) where my.hyperbFit is the fitted function. The above approximation of the variance of $\alpha$ is then
$$
\mathrm{Var}(\alpha)\approx D_{\alpha}\Sigma D_{\alpha}^\top
$$
The same is true for the approximation of the variance of $\beta$.
In R, this can be easily coded like this:
#-----------------------------------------------------------------------------
# The row vector D of the partial derivatives for alpha
#-----------------------------------------------------------------------------

D.alpha <- matrix(
  c(
    sqrt(1+pi^2)/delta,                 # differentiate wrt zeta
    ((pi*zeta)/(sqrt(1+pi^2)*delta)),   # differentiate wrt pi
    -(sqrt(1+pi^2)*zeta)/(delta^2)      # differentiate wrt delta
  ),
  ncol=3)

#-----------------------------------------------------------------------------
# The row vector D of the partial derivatives for beta
#-----------------------------------------------------------------------------

D.beta <- matrix(
  c(
    (pi/delta),            # differentiate wrt zeta
    (zeta/delta),          # differentiate wrt pi
    -((pi*zeta)/delta^2)   # differentiate wrt delta
  ),
  ncol=3)

#-----------------------------------------------------------------------------
# Calculate the approximations of the variances for alpha and beta
# "sigma" denotes the 3x3 covariance matrix
#-----------------------------------------------------------------------------

var.alpha <- D.alpha %*% sigma %*% t(D.alpha)
var.beta <- D.beta %*% sigma %*% t(D.beta)

#-----------------------------------------------------------------------------
# The standard errors are the square roots of the variances
#-----------------------------------------------------------------------------

se.alpha <- sqrt(var.alpha)
se.beta <- sqrt(var.beta)

Using $\log(\zeta)$ and $\log(\delta)$
If the standard errors/variances are only available for $\zeta^{*}=\log(\zeta)$ and $\delta^{*}=\log(\delta)$ instead of $\zeta$ and $\delta$, the transformation functions change to:
$$
\begin{align}
    g_{\alpha}(\zeta^{*}, \pi, \delta^{*}) &=\frac{\exp(\zeta^{*})\sqrt{1 + \pi^{2}}}{\exp(\zeta^{*})}\\
    g_{\beta}(\zeta^{*}, \pi, \delta^{*})  &= \frac{\exp(\zeta^{*})\pi}{\exp(\delta^{*})}\\
\end{align}
$$
The partial derivatives of the transformation function for $\alpha$ are then:
$$
\begin{align}
    \frac{\partial}{\partial \zeta^{*}} g_{\alpha}(\zeta^{*}, \pi, \delta^{*}) &=\sqrt{1+\pi^{2}}\exp(-\delta^{*}+\zeta^{*})\\
    \frac{\partial}{\partial \pi} g_{\alpha}(\zeta^{*}, \pi, \delta^{*}) &=\frac{\pi\exp(-\delta^{*}+\zeta^{*})}{\sqrt{1+\pi^{2}}} \\
    \frac{\partial}{\partial \delta^{*}} g_{\alpha}(\zeta^{*}, \pi, \delta^{*}) &=-\sqrt{1+\pi^{2}}\exp(-\delta^{*}+\zeta^{*})\\
\end{align}
$$
The partial derivatives of the transformation function for $\beta$ are:
$$
\begin{align}
    \frac{\partial}{\partial \zeta^{*}} g_{\beta}(\zeta^{*}, \pi, \delta^{*}) &=\pi\exp(-\delta^{*}+\zeta^{*})\\
    \frac{\partial}{\partial \pi} g_{\beta}(\zeta^{*}, \pi, \delta^{*}) &=\exp(-\delta^{*}+\zeta^{*})\\
    \frac{\partial}{\partial \delta^{*}} g_{\beta}(\zeta^{*}, \pi, \delta^{*}) &=-\pi\exp(-\delta^{*}+\zeta^{*})\\
\end{align}
$$
Applying the delta-method to the transformations, we get the following approximation for the variance of $\alpha$:
$$
\mathrm{Var}(\alpha)\approx (1+\pi^{2})\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Var}(\zeta^{*})+\frac{\pi^{2}\exp(-2\delta^{*}+2\zeta^{*})}{1+\pi^{2}}\cdot  \mathrm{Var}(\pi) + (1+\pi^{2})\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Var}(\delta^{*}) + \\
2\times \left[ \pi\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Cov}(\pi,\zeta^{*}) - (1+\pi^{2})\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Cov}(\delta^{*},\zeta^{*}) - \pi\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Cov}(\delta^{*},\pi)\right]
$$
The approximated variance of $\beta$ is:
$$
\mathrm{Var}(\beta)\approx \pi^{2}\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Var}(\zeta^{*})+\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Var}(\pi) + \pi^{2}\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Var}(\delta^{*}) + \\
2\times \left[\pi\exp(-2\delta^{*}+2\zeta^{*}) \cdot \mathrm{Cov}(\pi,\zeta^{*}) -\pi^{2}\exp(-2\delta^{*}+2\zeta^{*})\cdot \mathrm{Cov}(\delta^{*},\zeta^{*}) -\pi\exp(-2\delta^{*}+2\zeta^{*}) \cdot \mathrm{Cov}(\delta^{*},\pi)\right]
$$

Coding in R 2
This time, sigma denotes the covariance matrix but including the variances and covariances for $\zeta^{*}=\log(\zeta)$ and $\delta^{*}=\log(\delta)$ instead of $\zeta$ and $\delta$.
#-----------------------------------------------------------------------------
# The row vector D of the partial derivatives for alpha
#-----------------------------------------------------------------------------

D.alpha <- matrix(
  c(
    sqrt(1+pi^2)*exp(-ldelta + lzeta),            # differentiate wrt lzeta
    ((pi*exp(-ldelta + lzeta))/(sqrt(1+pi^2))),   # differentiate wrt pi
    (-sqrt(1+pi^2)*exp(-ldelta + lzeta))          # differentiate wrt ldelta
  ),
  ncol=3)

#-----------------------------------------------------------------------------
# The row vector D of the partial derivatives for beta
#-----------------------------------------------------------------------------

D.beta <- matrix(
  c(
    (pi*exp(-ldelta + lzeta)),    # differentiate wrt lzeta
    exp(-ldelta + lzeta),         # differentiate wrt pi
    (-pi*exp(-ldelta + lzeta))    # differentiate wrt ldelta
  ),
  ncol=3)

#-----------------------------------------------------------------------------
# Calculate the approximations of the variances for alpha and beta
# "sigma" denotes the 3x3 covariance matrix with log(delta) and log(zeta)
#-----------------------------------------------------------------------------

var.alpha <- D.alpha %*% sigma %*% t(D.alpha)
var.beta <- D.beta %*% sigma %*% t(D.beta)

#-----------------------------------------------------------------------------
# The standard errors are the square roots of the variances
#-----------------------------------------------------------------------------

se.alpha <- sqrt(var.alpha)
se.beta <- sqrt(var.beta)

Comment: A big thanks for your answer, but this is EXACTLY the problem, because the parameterization of this hessian is for log(delta) and log(zeta) and not for delta and zeta! See my follow-up posts: http://stats.stackexchange.com/questions/67595/variance-covariance-matrix-of-the-parameter-estimates-wrongly-calculated and especially the answer of CT Zhu here http://stats.stackexchange.com/questions/67602/the-vcov-function-cannot-be-applied
Comment: one has to get the hessian of pi, log(zeta), log(delta), and mu into the hessian of pi, zeta, delta, and mu. Do you know how this could be done?
Comment: I also tried to do it with the "wrong" hessian, so with log(delta) and log(zeta), after this I selected the sub-matrix and did the calculations. The results were not correct, because the values were way too large, so like 60 000 or so.
Comment: @BenBohold The terms inside the brackets before the covariance terms are the products of the respective partial derivatives of the transformation functions. For example: The term before $\mathrm{Cov}(\pi, \zeta)$ is the product of the partial derivative wrt $\pi$ multiplied by the partial derivative wrt $\zeta$. In the case of $\beta$ this would be: $\zeta/\delta \times \pi/\delta = (\zeta\cdot\pi)/\delta^{2}$.
Comment: @BenBohold Strange, but no problem. Try to calculate the covariance matrix in this way: `varcov <- solve(hyperbfitalv$hessian)`. Does this work? After that, you will have to select the sub-matrix containing only $\pi, \zeta, \delta$. The easiest way I could help you would be if you provided a fully working example with data (you don't have to provide all your data).
Comment: @JenBohold Jen, I updated my answer including the case when you only have $\log(\delta)$ and $\log(\zeta)$. I think you can now use the Hessian of the original parametrization (logs), calculate the variance-covariance matrix from that and apply the delta method. Could you give it a try and see if it produces some sensible results?
Comment: @JenBohold Jup, just use `log(zeta)` and `log(delta)`. The `hyperbFit` just prints out `exp(log(zeta))` and `exp(log(delta))`.
Comment: @JenBohold Your implementation seems correct. The reason why the bootstrap standard errors are so much bigger is that there are some very high values among the bootstrap samples (I repeated your bootstrap with $B=10000$). The mean of my bootstrap samples are $104.7$ for $\alpha$ and $2.15$ for $\beta$ which are also much larger than the values obtained by `hyperbChangePars` ($73.95$ and $0.052$). So both the mean and SD are influenced by some very high values among the bootstrap samples. To be honest, I don't know which method is "better". (contd).
Comment: @JenBohold (condt): The delta-method is an approximation whereas the bootstrap takes your data into account without assuming any distribution. I honestly don't know what to recommend as both methods have their drawbacks. Maybe someone else could shed more light on the matter ...
Comment: @JenBohold One additional thing: I also implemented your bootstrap but using the `boot` package. After that, I calculated the BCa-confidence intervals for $\alpha$ and $\beta$. For $\alpha$ the 95%-BCa-CI is $(55.25, 154.14)$ and for $\beta$ $(-22.15, 24.89)$. The naive 95%-CIs using the standard error of the delta-method are $(48.11, 99.79)$ for $\alpha$ and $(-13.56, 13.66)$ for $\beta$. The bootstrap CIs are wider, as they incorporate the shape of the data. This is expected.
Comment: @JenBohold No problem, thank you for the bounty :) You may consider opening a new question about which method to use. Maybe you'll get some good responses.
Comment: @JenBohold Sorry, my phrasing was sloppy: The first-order Talyor approximation (the one we used here) converges to a normal distribution. One caveat that could occur is when the first order approximation, which is linear, isn't very good because the approximated function is highly nonlinear. Then the first-order delta-method doesn't work and a higher order Taylor series may be considered.
Comment: @JenBohold No problem. Please ask if you have further questions.
Comment: one more question: How do you get the terms in the [] brackets before the Cov() ? What are those terms?
Comment: one more question: I tried to apply vcov to the hyperbfit variable, but it does not work? I tried vcov(hyperbfitalv) where hyperbfitalv is defined in the following way: hyperbfitalv<-hyperbFit(mydata,hessian=TRUE)

I get the (german) error message:
Fehler in UseMethod("vcov") :
  nicht anwendbare Methode für 'vcov' auf Objekt der Klasse "hyperbFit" angewendet
Comment: also applied to summary it does not work: vcov(summary(hyperbfitalv))
Comment: one more question: What should I insert for zeta* delta* and pi? The parameter estimates? Because I only have the parameter estimates for pi, zeta and delta, but not for log(zeta) and log(delta)? I guess for pi I insert the parameter estimate for pi and for zeta* and delta* I insert the log value of the parameter estimates, correct?
Comment: I edited my question and implemented your code and I show the results. What do you think? Did I implement it correctly and are the results reliable, especially why is there such a big difference to the results of the bootstrap algorithm? What should I use, bootstrap or delta-method? I think both inherit the problem of instability of the ML estimates, right?
Comment: Well, everything is fine then somehow, since the implementations are correct. Again: A very BIG thanks for your ongoing support, especially for helping me out with the vcov problem!
Comment: Ok one more last question: You say delta-method assumes a certain distribution, what distribution does it assume?
Answer: Possible duplicate: Standard errors of hyperbFit?
I could bet some accounts belong to the same person ...
Comment: I already linked that thread in my post! And if you really read my question you will see, that I DO NOT WANT TO use the bootstrap algorithm, but I am asking about the delta-method.


Find partial derivatives for $\sqrt[3]{(x^3 + y^3)}$ at the point $(0,0)$.

Question: For the function: $\sqrt[3]{(x^3 + y^3)}$ I'm requested to find both partial derivatives at the point $(0,0)$. I believe this is a problem that uses the limit definition of a partial derivative, however I always get 0 as an answer, which is incorrect. Can someone help me to sort this out?
Comment: What did you do, then?
Comment: I performed the partial derivatives without the limit definition, I always get 0/0
Comment: @OscarAguilar As a suggestion, for the next time you should add more detail about your work and effort in order to fullfil the standard for a "good question" and help us to give you some useful advice to conclude that. Bye
Comment: I did say so, for an answer that fulfills the standard of "good answer" see Gio's. Bye :)
Comment: @OscarAguilar Nothing personal from my side, you are free to choose the best answer according to your preference, mine was a suggestion to avoid downvotes or closure to your questions. Bye
Answer: $\frac{\partial f}{\partial x}(0,0)=\lim_{t\to0} \frac{f((0,0)+t(1,0))-f(0,0)}{t}=\lim_{t\to0} \frac{\sqrt[3]{t^3}}{t}=\lim_{t\to0} \frac{t}{t}=1$. It is analogous for $\frac{\partial f}{\partial y}(0,0)$.
Comment: Thank you for the clear explanation!
Answer: HINT
By the definition we have
$$\frac{\partial f}{\partial x}(0,0)=\lim_{h\to 0}\frac{f(h,0)-f(0,0)}{h}=\lim_{h\to 0}\frac{\sqrt[3]{h^3}}{h}$$
and similarly for $\frac{\partial f}{\partial y}(0,0)$.
Comment: Correct. But in both cases the limit is 0, isn't?
Comment: What about $\sqrt[3]{h^3}$?


2 connections per server?

Question: i´ve read somewhere that you can just have 2 connections (eg. ajax requests) to the same server. is this correct?
so you can´t run 3 ajax requests simultaneously? what will happen to the 3rd one?
and if I´ve got one iframe, then i can just run 1 ajax request at the time?
what is the easiest way to get around this?
what keywords could i use to search for more information regarding this on google?
Answer: The 2 connection maximum pr server is mandated in the HTTP RFC 2616 section 8.1 http://www.ietf.org/rfc/rfc2616.txt

Clients that use persistent connections SHOULD limit the number of
     simultaneous connections that they maintain to a given server. A
     single-user client SHOULD NOT maintain more than 2 connections with
     any server or proxy. A proxy SHOULD use up to 2*N connections to
     another server or proxy, where N is the number of simultaneously
     active users. These guidelines are intended to improve HTTP response
     times and avoid congestion.

Q:what will happen to the 3rd one?
The third one will be queued untill one of the other HTTP calls return
Q:and if I´ve got one iframe, then i can just run 1 ajax request at the time?
The iFrame will be loaded through a HTTP connection, but once the HTML content has be returned the HTTP call has been completed and you again have 2 available HTTP connections
Q:what is the easiest way to get around this?
The most important is not to have long running HTTP requests, i.e. speed up processing on the server side. As long as HTTP requests are responded to in less than 100 ms, it is for normal apps not a problem.
Comment: but im using comet and it will use long running requests, which is the purpose. hope the server will handle it..
Comment: Also note wizard@'s response, which states the nice "optimization" that you can force more than two connections to your site if you create several additional CNAMES (e.g. foo1.bar.com, foo2.bar.com).  Hower, this has some other drawbacks.
Answer: You read it right, browsers limit simultaneous connection to the exact same domain to 2 for any type of requests (script src, image src, ajax etc.) originating from a given document, it can be changed in registry for IE and about:config in Firefox.
One way to get around this is to have additional CNAMEs to your host.
Comment: IE 8 / FF3 both increased the default number of concurrent connections per host to 6
Comment: Sorry, I know nothing about PHP
Comment: what lanugage are u using? curious:)

2 connections per server?


How to send email to multiple recipients on creation of new node using rules module?

Question: I have created one node type.
Now, I want to send an email to multiple recipients on creation of new node using rules module.
Comment: Please followup with problems on sending email as a new question (but search first to see if it has been addressed), or consider using chat.  Thanks.
Answer: To send emails to multiple persons on creating a new node, you have to create a new rule and follow these steps :

Create an event After saving a new content type and then select that particular content type.

After that add an action from Select the action to add select list and choose Send Email.

After that you can add multiple email ids in the To textarea separated by comma and space like this :
email@example.com, email@example.com, firstname.lastname@example.com
Comment: i tried this, but this is giving me following error "Unable to send e-mail. Contact the site administrator if the problem persists."
Comment: To enable e-mail services from your local, you have to add and enable a module SMTP module to do this.
Comment: i am not on local server, i am on live server. I am adding email addresses in "To textarea" not in "From textarea"
Comment: Check the logs for what the real error is.


Set dropdown list programmatically in exposed view filters

Question: I have programmatically set a text CCK to a select and given a few choices:
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['field_1hour_currency']['#type'] = 'select';
    $form['field_1hour_currency']['#options'] = array(
      '' => t('<Any>'),
      'USD' => 'USD',
      'EUR' => 'Euro'
    );
  }
}

But this display defaults to a Multiple Choice box, and I want it to be a dropdown list. How can I set programmatically a select to force single so it displays a dropdown list?
Thank you
Answer: Add the following to your form_alter implementation:
$form['field_1hour_currency']['#multiple'] = FALSE;
$form['field_1hour_currency']['#size'] = 0;


Why are Covid-19 cases shown logarithmic?

Question: I think this is a really simple and stupid question, I am sorry for that, but I could not find anything while googling it.
why are covid-19 cases shown also on a logarithmic scale? on worldometer for example.
From my understanding, the ln(x) is the inverse function of the e(x) and so we could better see, if the curve flattens, when plotting the cases on a logarithmic scale? is this true?
Answer: Since COVID-19 is a viral disease, the number of people who get infected grows exponentially (until the curve hits the inflection point). Since exponential graphs grow really fast, its hard to study data from the graph normally.
When you graph them on a logarithmic scale, $\log a^x$ grows linearly since:
$$\log a^x=cx$$
for $c=\log a$. This allows us to study the graph much easier (since it is a linear graph).
Answer: The display on a logarithmic scale has mainly two reasons:

The range of the number of cases is very large. In the beginning there are only a few cases and at the highest point there may be several thousands of cases.
Using a logarithmic scale allows to present details at these different scales in a single graph. Otherwise we would just have a hockey-stick-graphs that all look much the same.
A related principle is to present graphs at a scale such that the prominent features have a slope of 45 degrees (see sparkline theory on Edward Tufte's blog).
The 45-degree principle relates to curves that grow exponentially fast and are in the beginning very flat and at the end very steep, that makes it very difficult to see differences between different curves.
The logarithmic scale will relate to the underlying mechanism. The growth rate of the cases is related to the logarithm
$$\underbrace{\frac{\frac{d}{dt}x}{x}}_{\text{growth rate}} = \underbrace{\frac{d}{dt} \log x}_{\text{change of logarithm}}$$
The slope of a curve on a logarithmic plot relates to the growth rate. See images like these:


Why my free() wrapper function doesn't work?

Question: Why should i use pointer to pointer in my saferFree(void**) function when i want to free  memory inside that function? Why below code does'n free ip pointer?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

void saferFree(void *);

int main()
{
    int *ip;
    ip = (int*) malloc(sizeof(int));
    *ip = 5;

    saferFree(ip);

    return 0;
}

void saferFree(void *pp){
    if((void*)pp != NULL){
        free(pp);
        pp = NULL;
    }
}

Above code doesn't free pp pointer but below code with double pointer works properly.I want to know Why?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

void saferFree(void **);

int main()
{
    int *ip;
    ip = (int*) malloc(sizeof(int));
    *ip = 5;

    saferFree(&ip);
    printf("%p", ip);

    return 0;
}

void saferFree(void **pp){

    if(*pp != NULL){
        free(*pp);
        *pp = NULL;
    }
}

Comment: What doesn't work?
Comment: Please show the part where you get to see `.It doesn't Free the allocated memory.` Some people are getting confused.
Comment: I suspect the problem is OP expects the pointer `ip` main() to be `NULL` because it's set to `NULL` in `safeFree()`. `pp` is local to `safeFree()`, so it doesn't reflect in main(). See this post as well: http://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function
Answer: FWIW, it is perfectly safe to pass NULL to free(). Your wrapper is basically meaningless.
Quoting C11, chapter §18.104.22.168, (emphasis mine)

The free function causes the space pointed to by ptr to be deallocated, that is, made
  available for further allocation. If ptr is a null pointer, no action occurs. [..]

That said, as per your question, it works fine, but because accessing free-d memory is UB, you should not be doing that (which you seem to be doing in main() after calling saferFree() to check if the memory is freed or not. ). Also, maybe worthy to mention that the function arguments are passed by value in C, so any change you make to pp itself  (example: pp = NULL;) will not reflect to ip in main(). free() will work normally, though.
Also, please see this discussion on why not to cast the return value of malloc() and family in C..
Comment: This seems like a comment for me.
Comment: Where's freed memory accessed?
Comment: @SouravGhosh that isn't said anywhere, OP could be just checking if pointer is NULL
Comment: @MikeCAT Wait for the OP to edit the question. :)
Comment: @usr for a hint, see the comparison in the code block in `main()`  as mentioned by OP.
Comment: @usr Seen and understood. OP is checking the memory is actually freed or not by attempt to access the memory.
Comment: @MarkusLaire The problem is, everyone is very keen on finding secondary issues with the question and answer, while the primary point is, the whole wrapper thing OP is trying to code, is rather useless. Once that is removed, the problem is gone.... :)
Comment: `Why my free() wrapper...`. Stop, you don't need one, or least not _this_ one.


actionSheet in iphone application

Question: I am new to iphone.Is it possible to keep 3 textfields, 3 labels and 2 uibuttons in an actionsheet or alertview. Kindly give information.
Thanks in advance.
Comment: Yes, it is possible but it looks like really very awful design
Comment: Yeah, you can do that in alertView. But what is the need of that. in which context you need that. It is not an efficient way of design.
Answer: You can try this as:
<code>UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"\n\n\n\n\n\n\n\n\n\n" message:@"" delegate:self cancelButtonTitle:@"Cancel"  otherButtonTitles:@"OK", nil];

UITextField *textfield1 = [[UITextField alloc] init];
textfield1.frame = CGRectMake(10.0, 30.0,260.0, 15.0);//set your frame as you required
textfield1.text=@"";
[textfield1 setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:textfield1];
[textfield2 release];

UITextField *textfield2 = [[UITextField alloc] init];
textfield2.frame = CGRectMake(10.0, 48.0,260.0, 15.0);//set your frame as you required
textfield2.text=@"";
[textfield2 setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:textfield2];
[textfield2 release];

UITextField *textfield3 = [[UITextField alloc] init];
textfield3.frame = CGRectMake(10.0, 65.0,260.0, 155.0);//set your frame as you required
textfield3.text=@"";
[textfield3 setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:textfield3];
[textfield3 release];

UIView *tempView = [[UIView alloc]initWithFrame:CGRectMake(10.0, 80.0, 260.0, 100.0)];//set your frame as you required
tempView.backgroundColor = [UIColor clearColor];
[alert addSubview:tempView];

UILabel *label1 = [[UILabel alloc]init];
label1.frame = CGRectMake(0, 5, 50, 15);//set your label frame here
label1.text = @"Enter text";
[tempView addSubView:label1];
[label1 release];

UILabel *label2 = [[UILabel alloc]init];
label2.frame = CGRectMake(0, 25, 50, 15);//set your label frame here
label2.text = @"Enter text";
[tempView addSubView:label2];
[label2 release];

UILabel *label3 = [[UILabel alloc]init];
label3.frame = CGRectMake(0, 45, 50, 15);//set your label frame here
label3.text = @"Enter text";
[tempView addSubView:label3];
[label3 release];

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = //set your button frame here
[tempView addSubview:button1];

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = //set your button frame here
[tempView addSubview:button2];

[tempView release];
[alert show];
[alert release];
</code>

actionSheet in iphone application


.empty() jQuery method and undefined value

Question: HTML:

JavaScript:
 var errornbr = 0;
 var mess;
 $("#addclient  input.form-control").each(function (index) {
     if ($(this).val() == "") {
         if ($(this).attr("data-val") != undefined) {
             if ($(this).attr("data-val-required") != undefined) {
                 errornbr = errornbr + 1;
                 mess = mess + "
" + $(this).attr("data-val-required");
             }
         }
     }
 });
 $("#errorsum").empty();
 if (errornbr > 0) {
     $("#errorsum").append("" + mess + "");
 }

First line of the label text is always undefined. the mess didn't contains such value.
So I need to know:

Does the empty() method is the reason of this?
How can I fix this issue?
Comment: change `var mess;` to `var mess = '';`
Comment: @guradio thank you very much, plz post your comment as an answer
Comment: Why not append to current value? `mess += "" + $(t.......`
Answer: change var mess; to var mess = '';
Make the assume text value making it not return undefined
Answer: Please use ( typeof VALUE != 'undefined' ) instead of ( VALUE != undefined )
Please write condition like this
if( typeof $(this).attr("data-val") != 'undefined' ){
 if( typeof $(this).attr("data-val-required") != 'undefined' ){

 }

}


How to avoid the error 'array expected string given' in db_query

Question: I am getting this error: Argument 2 passed to db_query() must be an array,
string given. In db_query in below function.
function uc_guest_checkout_uc_checkout_complete($order, $account) {
  if (!empty($_SESSION['uc_guest_checkout'])  && !user_is_logged_in()) {
    switch ($order->data['complete_sale']) {
      case 'new_user':
        // For guest checkout, we replace the ubercart generated username and email
        // for a new user with one that is more anonymous.
        $name = uniqid('anon-', TRUE);
        $mail = $name . '.' . uc_store_email();
        db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid);
   break;
  case 'logged_in':
    // If the order is marked logged in but anonymous, this means that
    // we must have set the uid to the default account, but still treat
    // this as a new user.
    $order->data['complete_sale'] = 'new_user';
    break;
    }
  }
  _uc_guest_checkout_end();
}

I tried this queries but none were creating account with valid names and emails as per db_query which is throwing error but successfully creating user accounts.where as these below queries creating names with random names.
db_update('users')
        ->fields(array(
            'name' => $name,
            'mail' => $mail
        ))
        ->condition('uid', $account->uid)
        ->execute();

db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
                array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

How do I resolve this?
Answer: You're using Drupal 6 syntax, you need to convert it to Drupal 7 syntax:
db_update('users')
  ->fields(array('name' => $name, 'mail' => $mail))
  ->condition('uid', $account->uid)
  ->execute();

See the Database API docs for more details.
Comment: I have already mentioned in my question that i have already tried like that and its not creating user account with valid names but with random names.So that only i am trying to  exactly replace the query and get exact results, which i am not getting rite now . In above function, You can able to see where it is creating user account with names and email. Where as wit this query its creating random names instead of valid names
Comment: What do you mean by 'random' exactly? Whatever you have in `$name` will be put into the database, you're totally in control of that. Drupal, nor MySQL, will not change that to 'random', it will only do what you tell it to do. You can't use `db_update()` to create a user obviously, is that what you're trying to do?
Comment: This is ubercart guest checkout module and there is a bug in it. I am trying to avoid that error. The error comes when i checkout as guest account and buy the product and then submit,it will create an buyer account with given names in the ubercart form. With above function it does all,creates user account properly. only issue over here is that it says  Argument 2 passed to db_query() must be an array, string given.
Comment: You can't possibly be getting that error if you're using the Drupal 7 code that you've put in your question. If you're still getting that error, it's because you're using `db_query()` incorrectly as in your _first_ code example. You need to use the code I've provided in the answer. If that doesn't "work", then your problem is somewhere else. That query is 100% valid, I can promise you.
Comment: In order to avoid that error i am trying to change that above query db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid); but if change to db_update it creates user account with random names like anon-564556 etc, random mail id firstname.lastname@example.com but not with ubercart filled name and email id.
Comment: I don't know what to tell you. `db_update()` **cannot create an account, it can only update an existing database record**. So I'm not really sure what you're asking
Comment: Its not my module and its a ubercart guest checkout module. why cant you see the above the function. In that it clearly states that "// For guest checkout, we replace the ubercart generated username and email
// for a new user with one that is more anonymous."  So i am guessing account is getting created here only. Hope i am not wrong ?
Comment: I'll say it one last time and then I'm out...`db_update()` cannot be used to create a new user. Never, ever. It can only ever be used to **update an existing record in the database**. You need to accept that, and continue with that knowledge in mind. If it means you have to go back and completely re-assess your understanding of that code, then that's what you'll need to do. But I'm afraid I can't tutor you through Drupal's API functions. I would recommend moving this to the module's issue queue, where you can get help from the guy who actually wrote it, and you can ask him what's going on
Comment: I can understand db_update cant create new user account. Error is coming in that line. Since above given comment "// For guest checkout, we replace the ubercart generated username and email // for a new user with one that is more anonymous." in the module, so  i thought its getting created like that. Sorry For the trouble.
Comment: @Ram No need to apologise it's no trouble, I just don't think the Q+A format here is going to allow us to give you the support it looks like you might need to fix this. The problem you're having isn't being caused by what you're describing. The code in this answer would definitely, 100% fix that error. If that then introduces _new_ problems, and then fixing that one breeds another one, and so on, this really will turn into a support forum


VHDL Up/Down Counter

Question: Good evening everyone. I'll start off by saying that I am very new to VHDL. I have a project that is asking me to model an updown counter that is made by Motorola in VHDL (an MC14510B for anyone curious).
From the datasheet one can see that if the input PE (preset enable) is toggled high, then the 4 preset values at input pin p4...p1 are passed straight through to the output q4...q1.
For some reason, my code refuses to compile, throwing the error Error: COMP96_0143: MC14510B.vhd : (56, 13): Object "p" cannot be written. I'm using Aldec as a compiler and have no idea what I'm doing wrong. I don't want to write to p the input, I want to write to qtemp with the values that are stored in p.
Can anyone see what I've messed up? In the process statement the else statement in the main if-else is what is giving me problems (the p <= qtemp line). Any help would be tremendously appreciated.
library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.std_logic_unsigned.all;

entity MC14510B is
  port (
    signal pe     : in    std_logic;
    signal ci_not : inout std_logic;
    signal reset  : in    std_logic;
    signal updown : in    std_logic;
    signal clk    : in    std_logic;
    signal p      : in    std_logic_vector (3 downto 0);
    signal q      : out   std_logic_vector(3 downto 0);
    signal co_not : inout std_logic
    );
end;

architecture myarch of MC14510B is
begin

  process(pe, ci_not, reset, updown, clk)
    variable qtemp  : std_logic_vector(3 downto 0);
    variable cotemp : std_logic;
  begin
    if reset = '1' then                                     --reset condition
      qtemp := "0000";
    elsif clk'event and updown = '1' and ci_not = '1' then  --count up
      if qtemp < 15 then
        qtemp  := qtemp + 1;
        cotemp := '1';
      else
        qtemp  := "0000";
        cotemp := '0';
      end if;
    elsif clk'event and updown = '0' and ci_not = '1' then  --count down
      if qtemp > 0 then
        qtemp  := qtemp - 1;
        cotemp := '1';
      else
        qtemp  := "0000";
        cotemp := '0';
      end if;
    elsif ci_not = '0' then
      qtemp  := "1010";
      cotemp := '1';
    else
      if pe = '1' then                                      --enable preset
        p      <= qtemp;                                    --output = input presets
        cotemp := '1';
      else
        qtemp  := qtemp;                                    --output = output
        cotemp := '1';
      end if;
    end if;
    q      <= qtemp;
    co_not <= cotemp;
  end process;
end myarch;

Answer: You seem to have an assignment to qtemp turned around where you have p := qtemp and should have qtemp <= p. It also looks like p should be in the sensitivity list for that process.
Your code then analyzes.  No guarantees it's otherwise correct.
p is declared mode in, you can't write to it.
Comment: Sensitivity list? I'm afraid I don't know what that means :/
Comment: A great opportunity to learn a fundamental VHDL concept; try here: [Google VHDL sensitivity list](http://www.google.dk/#q=vhdl%20sensitivity%20list)
Comment: The bit in parentheses:  `process(pe, ci_not, reset, updown, clk)` is the sensitivity list.  There's an implied `wait on pe, ci_not, reset, updown, clk;` statement at the end of the process.  It suspends process execution until a transaction occurs on one of those signals. Along with the clock anything affecting asynchronous assignment should be in the sensitivity list.  In this case, what happens if P changes while PE is '1'? Without P in the sensitivity list the change would get missed.
Comment: Neither updown nor ci_not appear to be needed in the sensitivity list.

VHDL Up/Down Counter


Push notification

Question: How can we make a Magento notification service/API for more than 1 android devices for adding, deleting, and other operations.
If there are two or more devices then it should notify other devices in case one of the devices add, delete, or update a product, user, or category etc.
I am using Magento soap API. Any help would be appreciated
Answer: If you require to build this from scratch, you'll want to take a look at http://framework.zend.com/manual/1.12/en/zend.mobile.push.introduction.html . Magento already makes large use of the Zend Framework, so this would be the easiest solution to implement if having to build from scratch.
If you're open to an off the shelf solution, you will want to consider Magento Mobile ( http://www.magentocommerce.com/product/mobile ). It would be the quickest way to get what you want, and will likely cost less than implementing this API from scratch.
Built right in is a Push Notification Service with Urban Airship ( http://urbanairship.com/products/push-messaging ).
The solution would cover you immediately with Android, and if you needed coverage for iOS you could quickly implement that when needed.

Push notification


Trouble Understanding the Basis for TpM

Question: Let $M$ be a smooth manifold. The tangent space of $M$ at a point $p \in M$ is the set
$$T_pM = \{ v_{\gamma, p} | \text{ for all smooth curves } \gamma \text{ through } p \}.$$
Where $v_{\gamma, p}: C^{\infty}(M) \to \mathbb{R}$, $f \mapsto v_{\gamma, p} f = (f \circ \gamma)'(\lambda_0)$, where $\gamma(\lambda_0) =p$. If we push $v_{\gamma, p}$ into a chart $(U, x)$, the result is not ill-defined, and
\begin{align*}
v_{\gamma, p}f &= (f \circ x^{-1} \circ x \circ \gamma)'(\lambda_0) \\
&= \partial_i (f \circ x^{-1})(x(p)) (x \circ \gamma)^{i'} (\lambda_0) \\
&= \dot{\gamma}^i_x \left( \frac{\partial}{\partial x^i} \right)_p f.
\end{align*}
Which leads me to belive $\{ \partial/\partial x^1, \dots, \partial/\partial x^d \}$ is a basis for $T_pM $. Which means
$$\lambda^i \left( \frac{\partial x^j}{\partial x^i} \right)_p = 0 \implies \lambda^i =0 $$ where $x^j: M \to \mathbb{R}$. Because that is just a notation (not an actual partial derivative),
$$\lambda^i \left( \frac{\partial x^j}{\partial x^i} \right)_p = \lambda^i \partial_i (x^j \circ x^{-1})(x(p)) = 0$$
Then $\lambda^j =0$. However, I'm not sure why $(\partial x^j/\partial x^i)_p = \delta^j_i$ (ignoring the fact that it looks like a partial derivative). Thanks!
Answer: $\left(\frac{\partial}{\partial x^i}\right)_p$ can be (and I usually see it defined) as the vector tangent to the curve $\gamma:I\to M$ given in coordinates by
$$(x\circ\gamma)(t)=\left(x^1(p),\ldots,x^{i-1}(p),x^i(p)+t,x^{i+1}(p),\ldots,x^d(p)\right)$$
So, given $f\in C^\infty(M)$,
$$\left(\frac{\partial}{\partial x^i}\right)_pf=\left.\frac{d}{dt}\right|_{t=0}\left(f\circ\gamma\right)(t)=\left.\frac{d}{dt}\right|_{t=0}\left(f\circ x^{-1}\circ x\circ\gamma\right)(t)$$
which is the directional derivative at $x(p)$ of the function $f\circ x^{-1}:\mathbb{R}^d\to\mathbb{R}$ along the $i^\text{th}$ unit vector in $\mathbb{R}^d$, or, in other words, the partial derivative $$\frac{\partial \left(f\circ x^{-1}\right)}{\partial x^i}$$ (I'm abusing notation a little bit, and $x^i$ here is not the function on $U$ but rather the coordinate in $\mathbb{R}^d$). By taking $f$ as $x^j$, the result follows.
Also, I'm not sure what you mean by "pushing $v_{\gamma,p}$ into a chart", but your definition is not ill-defined to begin with. You just need $(U,x)$ to be a chart around $p$ for the expression that comes after to make sense.
Answer: The $\partial / \partial x^j$ form a basis for the vector space $T_pM$. Declaring that the form an orthonormal basis is a choice of metric on the manifold, turning a smooth manifold into a Riemannian manifold. So you can't prove this from the definition, it does not need to be true. If you only have a smooth manifold you can't compute the inner product of two tangent vectors at a point. You need the additional structure of a Riemannian manifold for that which precisly defines the inner product on each tangent space.
Comment: Where is he computing the inner product?
Comment: Thanks for the response, but I'm not computing any inner product, only proving that the $\partial /\partial x^i$s give a basis for $T_pM$. Sorry if the wording was vague.

Trouble Understanding the Basis for TpM


Wysiwyg in views module

Question: Can I add a wysiwyg field in Views so that users can write and post text on my page?
Would I need to enable this as a block?
I have installed ckeditor and views already.
Answer: The only way WYSIWYG works with Views is with either an embedded comment or using the Editable Views module:

Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.

Wysiwyg in views module


Solving $f''(t) = g(f(t))$

Question: A recent question asked for a solution to $f'(t)= k f^2(t)$.  I could do this.  In fact, it seems that a large class of similar differential equations $f'(t) = g(f(t))$ are not hard to solve.
This led me to consider $f''(t) = g(f(t))$.
I started with a specific example: $f''(t)= k f^2(t)$.  I could solve this but I did so by just guessing that there would be a solution of the form $a x^b$.  I found $f(x) = \frac{6}{k x^2}$ as a specific solution. Obviously, for this case and others of this class, translations of a solution as also solutions.
However, as $g$ becomes more complex, guesswork will probably fail me.  Is there any good way to approach equations of this form?
Answer: Here is an attempt.  Unfortunately, without knowing $g$ exactly, it is difficult to write a solution $f(t)$ to $$f''(t)=g\big(f(t)\big)$$ as a function of $t$ explicitly.
Write $x(t):=f(t)$ and $v(t):=f'(t)$.  Then, you have
$$v\,\frac{\text{d}v}{\text{d}x}=\frac{\text{d}^2x}{\text{d}t^2}=g(x)\,.$$
This implies
$$\frac{1}{2}v^2=G(x)+c\,,$$
where $G$ is an antiderivative of $g$ and $c$ is some constant. That is,
$$\frac{\text{d}x}{\text{d}t}=v=\pm\sqrt{2\,G(x)+2\,c}\,,$$
or
$$\pm \sqrt{2}\,(t-\tau)=H_{c}(x)\,,$$
where $H_{c}$ is an antiderivative of $\dfrac{1}{\sqrt{G+c}}$ and $\tau$ is a constant.  That is, by continuity,
$$x=H_{c}^{-1}\big(+\sqrt{2}\,(t-\tau)\big)\text{ for }+\sqrt{2}\,(t-\tau)\in\text{Range}(H_c)\tag{1}$$
or
$$x=H_{c}^{-1}\big(-\sqrt{2}\,(t-\tau)\big)\text{ for }-\sqrt{2}\,(t-\tau)\in\text{Range}(H_c)\,,\tag{2}$$
given that $H_c$ is injective.

An example with $g(u)=k\,u^2$ for some constant $k\neq 0$.  Then, we can take $G(u)=\dfrac{k}{3}\,u^3$.  That is, we can also take
$$H_c(u)=-\int_{u}^\infty\,\frac{1}{\sqrt{\frac{k}{3}\,s^3+c}}\,\text{d}s\,.$$
I do not know the explicit form of $H_c$ for an arbitrary $c$, but
$$H_0(u)=-\int_u^\infty\,\frac{1}{\sqrt{\frac{k}{3}\,s^3}}\,\text{d}s=-\frac{2\sqrt{3}}{\sqrt{k\,u}}\,.$$
Thus, the range of $H_0$ is $(-\infty,0)$.  On $(-\infty,0)$,
$$H_0^{-1}(z)=\frac{12}{k\,z^2}\text{ for }z<0\,.$$
Combining (1) and (2), a solution is given by
$$x(t)=H_0^{-1}\big(-\sqrt{2}\,|t-\tau|\big)=\frac{6}{k\,(t-\tau)^2}$$
for all $t\in\mathbb{R}\setminus\{\tau\}$.

On the other hand, it is easier to solve for $f$ from $$f'(t)=g\big(f(t)\big)\,,$$
but you will still end up with some implicit relation.  With the same notation as before, we have $$\frac{\text{d}x}{\text{d}t}=g(x)\,,$$
so
$$\gamma(x)=t-\tau$$
for some constant $\tau$, and $\gamma$ is an antiderivative of $\dfrac{1}{g}$.  Therefore,
$$x=\gamma^{-1}(t-\tau)\text{ for }t-\tau\in\text{Range}(\gamma)\,,$$
provided that $\gamma$ is injective.
For $g(u)=k\,u^2$ with $k\neq 0$, we can take
$$\gamma(u):=-\int_u^\infty\,\frac{1}{k\,s^2}\,\text{d}s=-\frac{1}{k\,u}\,.$$
That is, $$\gamma^{-1}(z)=-\frac{1}{k\,z}\text{ for }z\neq 0\,,$$
and we get a solution
$$x(t)=-\frac{1}{k\,(t-\tau)}\text{ for all }t\in\mathbb{R}\setminus\{\tau\}\,.$$
Comment: Thanks, that's what I wanted.  Obviously, I did not expect a specific solution since I did not say what $g$ is.  I just wanted a method to attack this class of equation.  Now, that I see that, I realize that I should have known it and maybe I did once.  It is several decades since I attended a class on this subject.
Answer: $$f''(t)=g(f(t))\implies 2f'(t)f''(t)=2g(f(t))f'(t),$$
then
$$f'^2(t)=2\int g(f(t))f'(t)dt+C.$$
Next,
$$\frac{f'(t)}{\sqrt{2\displaystyle\int g(f(t))f'(t)dt+C}}=\pm1$$
and
$$\int\frac{f'(t)}{\sqrt{2\displaystyle\int g(f(t))f'(t)dt+C}}dt=\pm t+C''.$$

With $g(t)=kt^2$,
$$\int\frac{f'(t)}{\sqrt{2\displaystyle\int kf^2(t))f'(t)dt+C}}dt=\int\frac{f'(t)}{\sqrt{\dfrac{2k}3f^3(t)+C}}dt=\pm t+C''.$$
For $C\ne0$, there is no elementary solution.
https://www.wolframalpha.com/input/?i=integrate+1%2Fsqrt(2k%2F3+x%5E3%2BC)

Solving $f''(t) = g(f(t))$


Como converter uma string em data ou date?

Question: Tenho aqui as declaracoes que preciso converter de string para date, podem me ajudar?
ObjAl.setDataEmissao(TxtDataEmissao.getText());
ObjAl.setDataNascimento(TxtDataNascimento.getText());

Answer: Existe o DateTimeFormatter.
Utilizando ele é possível converter uma string em um objeto LocalDate, que faz parte da nova API de datas do Java, um exemplo:
String data = "13 Janeiro 2016";

DateTimeFormatter format = DateTimeFormatter.ofPattern("d MMMM yyyy");
LocalDate localDate = LocalDate.parse(data, format);

Os padrões aceitos podem ser encontrados no Javadoc, embora eles não sejam nenhuma novidade para quem trabalha com datas em Java.
Tendo o localDate, podemos manipular o objeto para, por exemplo, obter o dia da semana:
String diaDaSemana = localDate.getDayOfWeek()
                              .getDisplayName(TextStyle.FULL, Locale.getDefault());

System.out.println(diaDaSemana); // Quarta-feira

A nova API de datas do Java é inspirada no Joda e seu principal objetivo é trabalhar com datas e tempos.
Diferentemente de um objeto Date que representa um instante na linha do tempo, armazenado em um long que contabiliza os milissegundos desde a meia-noite de 1970.
Se você realmente precisa trabalhar com milissegundos, vá de Date ou Instant. Mas se quer trabalhar de forma simples com objetos de tempo, seja legal e use a nova api.

O LocalDate está aí para manipular datas exclusivamente.
Se quiser trabalhar somente com o tempo/horário, existe o LocalTime.
Se precisar da data e horário, há o LocalDateTime.

Para finalizar, dá para transformar o LocalDateTime em um objeto Date por meio da classe Timestamp:
String data = "13 Janeiro 2016, 16:22";

DateTimeFormatter format = DateTimeFormatter.ofPattern("d MMMM yyyy, HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(data, format);

Date d = Timestamp.valueOf(localDateTime);
System.out.println(d); // 2016-01-13 16:22:00.0

Answer: Algo mais ou menos assim:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date data = new java.sql.Date(format.parse(dataStr).getTime());

Lembra de adaptar para sua necessidade.
Comment: Mto obrigado pela resposta Otto, mas como implemento esse codigo nesta minha questao? porq se fosse para converter uma string para Inteiro, eu colocava simplesmente o Integer.parseInt();
Comment: @yoly  dataStr seria seu TxtDataEmissao.getText() simlpes assim
Comment: Hamm! Agora sim, peguei. Valeu :)
Answer: O SimpleDateFormat tem a finalidade de converter as java.util.Date em String e vice-versa.
Ao construir este objeto é possível informar qual o padrão de data que você deseja transformar ou recuperar.
Caso este padrão não seja informado, será utilizado o prado pelo Locale do Usuário.
Segue a documentação da classe.
Exemplo de utilização:
public static void main(String[] args) {
        Date dataAtual = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

        String DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
        DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
        DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        try {
            Date strToDate = format.parse(DateToStr);
            System.out.println(strToDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

No seu caso, deve se atentar o formato em que o TxtDataEmissao está exibindo para instanciar o seu SimpleDateFormat:
 SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
// Verifique o formato!

    try {
               ObjAl.setDataEmissao(format.parse(TxtDataEmissao.getText()));
       } catch (ParseException e) {
            e.printStackTrace();
       }

Comment: muito boa resposta mestre parabéns.
Comment: Muito boa resposta sim, foi bem claro e resolveu meu problema...Valeu :)
Comment: não esqueça de [aceitar uma das respostas](http://meta.pt.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta)
Answer: Uma Alternativa seria criar uma Classe utilitária com os métodos que convertem as datas, caso você precise fazer conversões em mais lugares. Ou então pode criar os métodos na própria Classe, Exemplo:
    public static Date parseDate(String data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        return sdf.parse(data);
    }

    public static String parseDate(Date data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        return sdf.format(data);
    }

    public static java.sql.Date getSqlDate(Date data) {
        return new java.sql.Date(data.getTime());
    }

Depois é só chamar esses métodos passando uma String ou Date, dessa forma:
//Converte String pra Date
ObjAl.setDataEmissao(parseDate(TxtDataEmissao.getText()));

Comment: Essa é uma boa forma de evitar reescrever o mesmo código em todo lugar! GO DRY CODE!


How can I redirect traffic transparently from one IP to another?

Question: I would like to redirect all incoming traffic on port 1111, to another server again on port 1111, serving as a transparent proxy. After googling around, I've tried using iptables, but it does not work as expected.
root@glider:~# sysctl net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1

root@glider:~# iptables -t nat -A PREROUTING -p tcp --dport 1111 -j DNAT --to-destination 10.2.4.44:1111

root@glider:~# iptables -t nat -A POSTROUTING -j MASQUERADE

root@glider:~# telnet localhost 1111
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

root@glider:~# telnet 10.2.4.44 1111
Trying 10.2.4.44...
Connected to 10.2.4.44.
Escape character is '^]'.

I am using Kubuntu 14.04 LTS.
Comment: Check if forward is not denied in firewall: iptables -L FORWARD -v -n
Answer: The PREROUTING chain is used for incoming packets, but not for locally generated packets. In order to test it, you should not be connecting to localhost. Instead you should test the connection from a different host.
Applying nat rules to all interfaces is potentially problematic. I'd recommend that you restrict the rules to only apply on the interface, where you need them.
The DNAT rule should have -i <interface name> or -d <ip address>, the MASQUERADE rule should have -o <interface name>.
Comment: Indeed, in the real case I have to restrict it to one of the interfaces. Thanks.


How am I supposed to understand the penalty term to penalize lack of smoothness?

Question: The penalty term is written as $\lambda\int f''(t)^2 dt$.
I am told that if $f$ is wiggly, then $f''$ is big, so this term penalizes the lack of smoothness of $f$.
Uh, okay, that makes sense ... but then you take the integral? Why?
How do you know that integral converges? That doesn't make sense. In fact, for many smooth functions, $\int f''(t)^2 dt = \infty$. For example, take $f(x) = x^2$. Then $f''(x) = 2$, and the integral is infinity, so what's the point?
My question is basically what that integral is doing there. Now you can only work with functions for which that integral is finite, which you have no way of knowing??
Comment: You don't really consider the integral to be over $(-\infty, \infty)$, but rather over the range of the values of the data, which is where the estimation occurs.  If I am estimating a function with variable $x \in (0,4)$, I don't really care what the penalty term does to, e.g., a function value for $x = 1\times 10^6$.
Comment: What you have is *a* penalty term. It only gets the definite article "the" in a context where it, specifically the penalty term for that context but you supply no context. Your question would be clearer if you did. For example are you talking about cubic spline smoothing?
Comment: Welcome to CV! The example you give ($f(x)=x^2)$ is a perfectly smooth function, while the point of the penalty is to regularize functions that otherwise aren't smooth. Related: https://stats.stackexchange.com/a/410554/176202
Comment: As to why the integral in the first place: A model with finite parameterization takes a penalty for the sum of (some function of) its coefficients. The continuous version of a sum is an integral.
Comment: The penalty term is often imposed in situations where we are using basis functions, so that $f(x) = \sum b_i(x) \alpha_i$ where $b_i$ is a basis function and $\alpha_i$ is a constant. So how would it then work if we take the basis functions to be polynomials, so that $b_1 = 1, b_2 = x, b_3 = x^2, b_4 = x^3, ...$. In that case, how does the penalty term make sense? Is the integral still not infinity ?
Comment: This integral always converges: it just might be infinite.  However, it is obvious that in such a case $f$ would not be a solution, because we can always find solutions where the integral does converge.
Answer: Several points:

We need to penalize the function, not some of its values, so somehow you need to summarize all the individual values. Taking the integral (continuous sum) seems natural.

We do not think about the integral range as $(-\infty, +\infty)$, but rather as the data range. So divergence of the integral shouldn't be a concern. Even then, if we should have an infinite integral, then the penalty will be $\infty$, so that is regularized away!

Generally, we work with some known basis functions, and know (or can approximate) their second derivatives. So your concerns could be investigated in any concrete case.

See also the comments below the question.
Comment: The reason for (2) is simple: you can always extend $f$ outside the data range linearly.  That implies $f^{\prime\prime}$ is identically zero outside the data range, guaranteeing convergence of the entire integral.  If the space spanned by the basis functions does not include such functions, then we're in trouble: we have to relax our requirements on $f$ near the endpoints of the data range.


Pass initial value using script but keep interacting in terminal with a program

Question: Here's my interactive program:
import sys

print ("what's your name?")

sys.stdout.write("> ")
sys.stdout.flush()

for line in sys.stdin:
    line = line.rstrip()

    if line == "q":
        break

    print ("hello", line)

    sys.stdout.write("> ")
    sys.stdout.flush()

it runs in a loop:
$ python3 name.py
what's your name?
> tom
hello tom
> john
hello john

what I want is to initially pass input, name in this case, but to be able to further interact with the program.
what I have so far is this:
#! /bin/bash

echo "mr. big" | python3 name.py

however this runs the program and immediately exits:
$ ./script
what's your name?
> hello mr. big
> $

Comment: It exits, because it runs on EOF in stdin. Without modifying `name.py` itself, I suggest that you use [expect](https://www2.lib.uchicago.edu/keith/tcl-course/topics/expect.html)  for this task. `expect` has a command `interact`, which hands over control to interactive use.
Answer: Is this what you are trying to do?

#!/bin/bash

(echo "mr. big"; cat) | python3 test.py

In your script the echo "mr. big" | python3 name.py, the input is piped directly from the echo command to your python script. This means that the echo closes the input after the first value you provided and it terminates your script.
And here using (echo "mr. big"; cat) | python3 name.py subshell that first echoes the initial value "mr. big" and then uses cat to read more user inputs from your program basically. Essentially you are piping the output of the subshell to your Python script which keeps the input open for continued interaction.
Comment: Yes, exactly what I wanted. Can you also add an explanation why this works?
Comment: Np, updated the code @d9ngle


Run modules independently with source dependencies in Android Studio (Intellij?)

Question: I am using Android studio but this may be a general Intellij question (I'm used to eclipse). This seems like it should be super simple, but I can't figure it out.
I want to be able to run either module in my project independently, which is from what I understand the purpose of a module. This has worked fine until now when I want to call code from my "app" module in my "testmodule" module. Android Studio lets me import the code I need with no problems until I try to build the module. Then I get the expected "package not found" error. So then I try adding this in my "testmodule" build.gradle:
main.java.srcDirs '../app/src/main/java'

This causes two package import statements in my "app" module to fail. One of the failing packages is the package defined in my "app" manifest and the other is specified in my "app" build.gradle
sourceSets {
    main.java.srcDirs += '../../connectorAPI/trunk/src'
}

I also tried to make one module depend on another but from what I've read in stack overflow (and the vague Android Studio error) one module must be a library file. This obviously doesn't work since I want to be able to run either. I would love to just copy the code I need but then I'd need to change both every time in version control, which is a nightmare.
In eclipse all you have to do is right click and link source. I can't imagine this is impossible or even out of the ordinary, so I must be missing something simple... can someone please help me out?
build.gradle testmodule
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.XXXXX.testmodule"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:+'
}

build.gradle app
apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com.XX.XXX.XXX.XXX"
        minSdkVersion 15
        targetSdkVersion 19
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    packagingOptions {
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    sourceSets {
        main.java.srcDirs += '../../connectorAPI/trunk/src'
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:19.1.0'
    compile 'com.google.android.gms:play-services:+'
    // Add the ArcGIS Android 10.2.5 API
    compile 'com.esri.arcgis.android:arcgis-android:10.2.5'
    compile 'com.googlecode.json-simple:json-simple:1.1'
}

Comment: review - https://developer.android.com/sdk/installing/create-project.html#CreatingAModule  .if your module is of type libraries then locate it under ./libraries .. settings gradle -> include ':app', '':libraries:myLib' ./app/build.gradle.dependencies -> compile project(':libraries:myLib')
Comment: That's the problem, I want to be able to run both modules so neither one can be a library module.
Comment: well , try locating both modules 'underneath' the 'app' level in the AS project with circular dependencies...
Comment: As far as I can tell that's how I have it set up. When I look at the file structure on windows explorer, the app and testmodule modules are both on the same level one below the project folder
Comment: try removing the dependencies in "build.gradle" and just refer  to the other modules "main" in the respective android.manifest.  if it wont build, then i guess your back to circular dependencies and should read up on gradle.depencies
Comment: I will try that and let you know. Are you thinking the problem is with circular dependencies? This was my initial thought...
Comment: put a framework Main activity up at the app level. put the 2 modules below that.  Make each of the 2 modules build on their own ( without dependent on other module ) . Limit your interfaces to what can be passed thru intents/parcels.. IMO that will work.
Answer: I might be late by a few years but here is what I would do : Declare both modules as library, and create another two as application. Then you can easily import the two libriaries while still having two applications, if that is what you want.
As for the duplicate dependency issue that will arise, you can just add an exclude statement in the build.gradle respectively.


Calculating sample size with power analysis

Question: I have to calculate the sample size for an experimental study and took some sample distributions data from a previous similar research and calculated the means and standard variations for before and after the treatment (see picture).

since the sample distribution is not  normally distributed, does it still make sense to calculate the standard deviation?

is it common to use the effect size from previous studies or should one even lower the effect size for sample size calculation?

how do I process further in order to get a sample size, whit power of 80%, alpha .05?

I habe never done a power analysis before, so can anyone help?

The outcomes represent the payouts that come with the reports done by the participants.  In many previous papers, the means were just compared.

Okay, good to know! But how does one come up with the answer? Do I have to look for papers, where no significant difference was found?

I was actually going try to compare the means, but since the outcome distributions are not normally distributed I guess one has to use non parametric test. It would be the wilcoxon rank sum test then?
Answer: Understanding current data. It looks as if the counts from your previous experiment may have
been something like those in the table below, where the first row
is for the control group and the second for the treatment group,
and columns are for 0 through 5.
TAB
    [,1] [,2] [,3] [,4] [,5] [,6]
n.c   10   11    9   10    8    8
n.t   16    4    5    9   21   30

A chi-squared test would have rejected the null hypothesis
that scores 0-5 are independent of group, with P-value 0.002.
chisq.test(TAB)

       Pearson's Chi-squared test

data:  TAB
X-squared = 19.261, df = 5, p-value = 0.001718

But this does not say that scores are higher in the treatment group, only that the distributions differ--as one can readily
see from the histograms your posted.
chisq.test(TAB)

        Pearson's Chi-squared test

data:  TAB
X-squared = 19.261, df = 5, p-value = 0.001718

The lists of individual scores for treatment and control
groups can be reconstructed as follows:
x.t = rep(0:5, times=n.t)
table(x.t)
x.t
 0  1  2  3  4  5
16  4  5  9 21 30
summary(x.t)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  0.000   2.000   4.000   3.235   5.000   5.000

x.c = rep(0:5, times=n.c)
table(x.c)
x.c
 0  1  2  3  4  5
10 11  9 10  8  8
summary(x.c)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  0.000   1.000   2.000   2.339   4.000   5.000

The treatment mean and median are larger than the control mean
and median. A Wilcoxon rank sum test confirms that the treatment
scores are centered above the control scores:
wilcox.test(x.t, x.c, alt="greater")

        Wilcoxon rank sum test
      with continuity correction

data:  x.t and x.c
W = 3068.5, p-value = 0.001552
alternative hypothesis:
 true location shift is greater than 0

One can quibble about what a 2-sample Wilcoxon test means when the two samples have different shapes. However, empirical CDF plots show that the treatment scores (blue) 'stochastically dominate' the control scores; that is, the treatment ECDF is (mainly) to the right of the control ECDF (thus below it on the cumulative probability graph).
plot(ecdf(x.c), col="brown",
     main="ECDF Plots of Data (Control in Brown)")
 lines(ecdf(x.t), col="blue")

Power and sample size. From the one prior experiment of this kind we can guess
that having about 84 subjects in the treatment group and
about 56 in the control group, gives enough power to
detect a difference between the two groups.
If the control group for a subsequent experiment will
give nearly a uniform distribution of the six scores
and you have some idea what distribution among the
treatment group you want to detect, then we can do
a simulation to approximate the power. It is a little
more efficient to have equal sample sizes in the treatment and control groups, so I will start with $n_t = n_c = 75.$
Also, I will suppose we want to detect a treatment
distribution with probabilities pr $= (1,1,2,2,3,3)/12.$
respectively, for the six values $0$ through $5.$
For this particular scenario, you will have power about 78%.
set.seed(112)
pr = c(1,1,2,2,3,3);  n = 75
pv = replicate(10^5, wilcox.test(sample(0:5,n,rep=T),
          sample(0:5,n,rep=T,p=pr),alt="less")$p.val)
mean(pv <=.05)
[1] 0.77812

If you need to detect a less extreme pattern or probabilities, then the power would be smaller; you would reject against this less extreme alternative more than half the time with 75 subjects in each group.
set.seed(112)
pr = c(1,1,1,2,2,2);  n = 75
pv = replicate(10^5, wilcox.test(sample(0:5,n,rep=T),
          sample(0:5,n,rep=T,p=pr),alt="less")$p.val)
mean(pv <=.05)
[1] 0.55869

This smaller effect is more often detected when you have 135 subjects in each group; power about 78%.
  set.seed(112)
  pr = c(1,1,1,2,2,2);  n = 135
  pv = replicate(10^5,wilcox.test(sample(0:5,n,rep=T),
        sample(0:5,n,rep=T,p=pr),alt="less")$p.val)
 mean(pv <=.05)
 [1] 0.779

I don't know any closed-form power formulas for such
Wilcoxon tests, but you can get a reasonably good idea
what sample sizes to use if you can guess the kind of
difference you want to find.
Comment: Thank you for your detailed calculations and explanations! Wow! But you used different frequencies at the beginning, right?
Comment: Could you explain a bit more about the intuition behind the probabilities for the treatment distribution outcomes?
Comment: For our designed experiment we would take the effect size of the previous experiment as the estimated effect size (or even higher), and would use the common 80% power and 0.05 alpha. Though I am not really sure how to calculate an estimate for the standard deviation with the information given. I have one standard deviation for each group that differ.
Comment: The standard deviation is  not of much use for the distinctly on0normal and discrete distributions you are using. Also I know of no way to define effect size for your distributions. I have given you several examples how to find power. // For normal distributions the SD is useful.
Comment: You did not explicitly show the frequencies you had in the current expt. I tried to deduce them from your histograms. // Also I used proportions (1,1,2,2,3,3) for first power simulation because it seemed you wanted higher counts for higher numbers 0 through 5. (You can choose any 6 numbers you want.) // In R, it is OK to use `p =c(1,1,2,2,3,3)` because R supplies denominator 12 to turn the proportions into probabilities.
Answer:
Standard deviation applies to non-normally distributed data.  Since the outcomes are categorical, their numerical labelling are more or less arbitrary.  I could rename them to inflate/deflate the variance at will.  Hence, it might be easier to look at the standard deviation of a single outcome, or to look at the multinomial covariance matrix.

Depends on the quality of the study.  My own advice is to select a smallest meaningful effect size and base your study on that.  Ask yourself "what effect size is small enough but is still interesting to you?".  Another way to ask that would be "At what point would the effect be too small to matter to you?".

Power analysis depends on the analysis you intend to perform.  From the pictures you include, it looks like you're doing a chisquare test.  Is that still what you intend to do?


Windows service accounts without password set

Question: In Unix and Linux based system you usually run services in context of service accounts that have no password set and cannot be logged on. As far as I have understood, the processes are spawned from a higher privileged process and switched to the service account using setuid.
Is the same possible on Windows based systems, or do you always have to set a password for service accounts?
Comment: Some more reading material.  https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/service-accounts
Answer: If you do not want your service to run in an account with a password, you can configure it to run as local system, or as one of the built-in service accounts, NETWORK SERVICE or LOCAL SERVICE.  Or, if you want finer-grained security, you can use a virtual account.
See the section "Using virtual accounts" in the Service Accounts Step-by-Step Guide for more information on virtual accounts.  The Guide also describes managed accounts, which are domain accounts whose passwords are automatically managed by Windows.
Typically, you would just use NETWORK SERVICE or LOCAL SERVICE unless you need to give the service access to sensitive files or folders, or other securable objects such as registry keys.
Managed accounts are more complex than virtual accounts, but in an Active Directory environment you might want to use them if you need to give the service access to sensitive content on the network, such as a remote share or an SQL Server using integrated authentication.
See also Service Accounts, a more recent article applying to Windows Server 2022, 2019, and 2016.
Comment: Yes, that's right.  I've added a paragraph about this to my answer.  Accessing an SQL Server (that is in the same domain as you and is using integrated authentication) is a textbook example of why you might want to go to the extra trouble - if the service needs a level of access to the SQL database that shouldn't be exposed to the risk that other services on the same computer might be compromised.  (If it only needs guest-level access, then using the computer account might be sufficient.)
Comment: Excellent! One thing that is still a bit unclear to me after reading this documentation is when you would choose Managed Service Account over Virtual Account and the other way around. Is it only related to whether you want network access to be in the context of a specific identity rather than the computer identity? Would a Managed Service Account be preferred over Virtual Account for an application that access SQL Server over kerberos?


What to have in mind when traveling by plane with my guitar?

Question: I have to travel by plane to another country in a few months, and I want to bring my guitar with me. I have doubts with what should I do to ensure that my guitar arrives safe and in perfect condition.
Reading this question "When shipping a guitar, what is the best way to package it?", I learned a few important tips, but I still have doubts like:
Do you put your guitar with the rest of the luggage or bring it on board with you?
Also, if you bring it aboard with you, you use a gig bag or a hard case? I don't think a SKB hard case will fit in the hand bag compartments.
Do you know any policy for carrying instruments in airlines?
Thanks.
Comment: "What to have in mind when traveling by plane with my guitar?" I'd keep these videos in mind: [United Breaks Guitars](http://www.youtube.com/watch?v=5YGc4zOqozo), [United Breaks Guitars Song 2](http://www.youtube.com/watch?v=h-UoERHaSQg) and [United Breaks Guitars Song 3](http://www.youtube.com/watch?v=P45E0uGVyeg). It's worth watching some of the interviews Dave Carroll gave discussing the whole incident and strongly consider never checking an instrument you prize. Someone who is negligent or determined could ruin an instrument in any case you put it in if it's checked. Keep it by your side.
Comment: I was following that incident since the first video came out, and at that time I began to worry about travel with a guitar. Thanks for the links.
Comment: Apparently Segovia used to reserve an extra air ticket for his precious guitar, named "Miss Segovia" and she would occupy the seat next to his.
Answer:
Call the airline beforehand and explain your situation.  Policies vary.
See if the aircraft(s) has a suit closet up front which can stow your guitar.  It will not fit in the overhead unless you are very lucky, especially with a hardcase (forget it), and it unfairly denies other people their luggage space. (Others have said they got theirs in, hardcase and all, so there's room for debate on this).
Bring a written copy of the policy if possible.
Be prepared for the gate people to not honor the policy.  This happened to a friend.  He was courteous and didn't lose his temper.  He explained that he had a boarding pass and would let the flight crew determine whether he could take the guitar.  He went to the plane door and allowed the flight crew to have the final word.  If they won't take it, you're out of luck.  This flight crew politely helped him bring the guitar on board even though the ground crew refused to let it on.
Don't check the guitar unless you are prepared to lose it.  Period.
Comment: +1 for "be prepared for the gate people to honor the policy." This happened to me when I actually bought a second ticket for my guitar, a purchase I made over the phone with a ticket agent who assured me it would be okay. In fact, the flight crew gave me a hard time about it, too, and eventually I had to change seats to sit in the very first row (of coach) before they were okay with it.
Comment: I guess its a matter of knowing the transport policies, be prepared, arrive early to the check in and be always polite. Thanks for your advice.
Comment: +1 Some VERY good points.I once had a very heated argument with the lady at the checkin counter about bringing my guitar on board.And then when I asked the flight attendant, she shrugged and said that it was alright if it fits in the overhead compartment.And in my experience, it does so quite nicely, hardcase and all ( we are talking drednought acoustic here )
Comment: I've re-edited the answer so that the part about the flight crew is a recount of what happened in my friend's case, not necessarily instructions for what you should do.  Since it involves potentially disobeying the gate crew, you do so at your own risk and your results may not be the same as my friend's.  Everything at airports is rather tense these days and I take no responsibility should there be adverse consequences...we're adults and make our own decisions.
Answer: After 9-11 I took an acoustic thru TSA and onboard. They made me unzip the case so they could search.
Of course, it is much more intrusive now under the present administration, so I would check with the airline or look on TSA website for more info.
Answer: I've flown with my guitars a handful of times...
The first time around 2003[?], for an important audition, I purchased a seat for it, no problems there... If you have an expensive instrument, crummy case, or are otherwise afraid something might happen, this is the safest way to go. All it takes is a short drop onto the concrete by a baggage handler and your instrument is gone.
Now, if possible, you could always airmail [fedex, etc] your instrument overnight to the location you need to get it to. That round-trip will most likely cost you less than a seat, and the airmail's insurance policies are better than the airlines [last I read airline instrument policy would only pay up to $2500]
If you fly a lot, another option is to buy the strongest, lightest, most form-fitting case you can and still hope you don't have to check it. Something like an Accord case. I like to carry my guitar upside-down with backpack straps, so that the neck points to the ground rather than the sky. This will eliminate lots of issues with checking in, boarding and/or gate-checking your instrument.
Then when boarding, ask the crew to put it in the crew's closet [it's usually near the door as you walk onto the plane]. If they're nice, they'll let you put it in... if not, you'd have to try for an overhead compartment and a few nice people that will put their belongings at you feet.
The key is to be nice to everyone--staff, security people, airplane crew, other passengers-- it goes a long way.
Answer: I took my acoustic guitar with me on a flight once and leaving the UK, the checking counter insisted I check the guitar in with the rest of my heavy luggage.
Conversely on the way out, leaving Turkey, the checking counter insisted I take it on as hand luggage, even though I didn't purchase an extra seat for it. There was no room in the overhead compartment and no suit closet on the plane. I had to sit for 4 hours with the guitar on my lap.
I haven't flown with my guitar since.
My advice would be call the airline you're flying with and get the details from them. As you can tell from the answers to this question already, every airline seems to have different policies on flying with instruments.
Either that or take up the triangle or finger cymbals...? ;)
Answer: as noted, check the airline. Policies vary wildly, even sometimes within departments of a single carrier.
And sometimes those policies contradict themselves. For example KLM has a policy that musical instruments MUST be checked. But then they go on and place restrictions on the size of cases for musical instruments which make it impossible to check a guitarcase (it's too long), so you have to send it as air freight instead (at increased cost, longer delivery time, etc.).
BA has similar policies with slightly different size restrictions, Delta has others again, etc. etc..
Within the US, you're probably safe on carriers with a lot of connections to places like Nashville, where they're used to dealing with musicians.
Answer: I usually take mine in a hard case on board. Not sure since 9/11 and all the p/c crap now though. They might try to get you to buy another seat or strip search you for fun.
If it is an expensive guitar you should try to bring it with you but have a backup plan(have someone be able to take it for you if they say you can't bring it.
Since 9/11 there's no telling what they might do... They might try and strip search your guitar or throw you in jail cause your strings might be used in a bomb.
If it were me I would simply try to take it on board and not ask. If the flight isn't full and they are nice people then chances are you'll get to bring it possibly after a little begging.
This all assumes you are not muslim or flying from such a country... Oh, and you probably don't wanna look muslim or an old white lady either.
You can call up the airlines and find out but I wouldn't give them any specifics just in case.
Best thing though is just to be prepared if you can't get it on board cause they most likely will make you leave it behind in which case you either you have to miss your flight or give your guitar away.
Have a friend willing to pick it up and ship it for you in that case and you should be good to go...
Answer: In addition to the points already noted, the Musician's Union in the UK recommend:

Don't carry anything else in the case other than the instrument - this makes it much easier to screen and saves difficulties
Carry your Musician's Union membership card - again, in the hope of reducing difficulties with authorities
Check with airports at either end of your journey, as you don't want to find that the airport on the return trip has different rules!
Answer: I was in your position, anxious as hell. I wanted to bring an electric guitar with me from USA. I read all kinds of posts on the internet, some were practical and helpful. I gathered bits and pieces of information and did my own planning. Research and planning are very important because this minimises the risk of damage and misplacement.
I'd say don't worry, its not as bad as it's explained by some folks. Now on to the practical aspects.
First you need to identify the guitar you wish to buy and then select a guitar case that will protect your guitar. I got a Fender Strat and selected a Fender ABS military grade plastic case with TSA locks and plush protection inside costing USD 150/-
Next you need to get a guitar case humidifier and fill it with water according to the operating instructions. This protects the guitar wood from extreme cold in the air and heat on the runway. You then have to loosen the strings to insert felt/thin blanket material between the strings and fretboard. This protects the fretboard from damage. Then you need to keep the strings slightly loose, not very loose, to keep slight tension on the neck.
Put the guitar in the case and pack the empty spaces with soft cloth or paper tissues. Then cover the headstock with more tissues and cover the entire guitar from the headstock to the bottom strap pin with paper tissues. After packing with tissues, its important to see that the guitar cannot move at all in the case. Place a sheet of bubble wrap on top of the paper tissue covering the entire length of the case.
You should AVOID the bubble wrap touching the lacquered part of the guitar. DO NOT place anything under the guitar.
Note that you remove all metal allen keys and the tremolo arm and put them in your check in luggage. Do not keep both guitar case keys together. Then lock the case, paste your name, address, mobile number snd email address on the case.
At the airport, the check in counter will get you to put 2 fragile stickers and sign an airline no liability form to load it into the cargo hold. Even after you land it is important to keep your baggage tag and boarding pass safely. Both these documents will be needed in case of a delayed luggage claim. Fragile items may be kept on a side near the luggage belt or may come out last. Clear immigration fast and head to the luggage belt. Look out for theives who can spot an expensive case at once. If you dont see it, complain to the missing baggage claim counter to see if it has been loaded onto your connecting flight.
If the flight comes late then the ground staff may not load all baggages onto the new flight. The airline staff will receive a message from the last airport you embarked that your case was not loaded. The airline staff will tell you on which flight it will arrive and the time to collect it. It may arrive the next day. They also pay for your tranport to come back to the airport. You will need all your boarding passes if there were connecting flights, passport and baggage tags to claim the case.
Don't worry, airport staff are not that bad to destroy your valuable guitar snd case. They will deliver it to you safely.


How do I interpret b and c in this union of sets question?

Question: I've been set the question:
(2) Let A,B, and C be sets with the following properties:(a)|A|= 100,|B|= 50,and|C|= 48.(b) The number of elements that belong to exactly one of the three sets is twice the number that belong to exactly two of the sets.(c) The number of elements that belong to exactly one of the three sets is three times the number that belong to all of the sets.How many elements belong to all three sets?
I'm having a hard time interpreting b and c, as b could imply whats exclusively in A (or B or C) = 2|BnC| (or with others) or |A|= 2|BnC|, and C doesn't use exactly in the final part i.e. 'exactly' all three sets what would imply |AnBnC| however it doesn't do this hence I'm left wondering what the use of exactly would mean in the rest of the question, with not much I can do apart from working out all possible ways to do this and assume one is correct in the end. Any help would be appreciated.
Comment: Please try to make the titles of your questions more informative. For example, *Why does $a<b$ imply $a+c<b+c$?* is much more useful for other users than *A question about inequality.* From [How can I ask a good question?](https://math.meta.stackexchange.com/a/589/): *Make your title as descriptive as possible. In many cases one can actually phrase the title as the question, at least in such a way so as to be comprehensible to an expert reader.* You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/).
Comment: Hi Shaun, my apologies for the lack of clarification first of all, however, on that page you sent. The first point of advice is to make the title the question, which is what I originally did by how do I answer this question. The second is referring to something I am unaware of hence I will check this and how it would've helped me ask the question better. The third doesn't help much as my set question takes around 350 characters and reduced to b and c alone: 250. The fourth, I wouldn't consider myself as a good advertiser of my question however I did consider this and thought that my original
Comment: question would entice whoever saw it to check the contents of the question and read it to see how they would interpret the question. The fifth I believe I have stuck to, as my question without the title fully described what I am asking. I'm aware that my original question wasn't good and will do better in the future.
Answer: What I like to do is divide it into 8 distinct disjoint all encompassing sets.  They are:
1) $A\cap B \cap C$.    These are the only elements in all three sets. This is one of the variables we are asked about.  Lets say there are $x$ elements. This are also some of the elments that compose $A$, $B$ or $C$.

$x =|A\cap B\cap C|$ is the element of elements in all three set. .

2) $A\cap B \cap C^c$. ($C^c$ means $C$'s complement.  All the elements not in see).  These are some but not all elements that are in exactly $2$ sets.  We'll call this $d$ elements. These are also some of the elements in $A$ and $B$.
3) $A \cap B^c \cap C$.  Call this number $e$.
4) $A^c \cap B \cap C$. Call this number $f$.

Sets 2-4 are all the elements in exactly two sets.  $d+e+f=$ number of elements in exactly two sets..

5) $A^c\cap B^c \cap C$.  Call this number $g$.
6) $A^c \cap B \cap C^c$. Call this number $h$
7) $A \cap B^c \cap C^c$. Call this number $i$

Sets 5-7 are the sets with elements in exactly one set.  $g+h+i\le 100$ is the number of elements in exactly one set.

8) $A^c\cap B^c \cap C^c$.  These are the elements not in any of the sets.  This will not have anything to do with our work.

Sets 1) 2) 3) and 7) make up the elements of $A$ so $|A| = 100=x + d+e + i$.
Sets 1) 2) 4) and 6) make up the elements of $B$ so $|B| = 50  = x + d+ f + h$.
Sets 1) 3) 4) and 5) make up the elements of $C$ so $|C| = 48 = x + e+f +g$.

and we know

$g+h+i = 2(d+e +f)$
$g+h+i = 3x$.

5 equations and 7 unknowns. But we are only asked to solve for $x$, and we have restrictions.
Adding $|A| + |B|+|C|$ together we get.
$198 = 3x + 2(d+e+f) + (g+h+i)$
Substituting $2(d+e+f)=(g+h+i) = 3x$ we get
$198 = 3x + 3x  +3x = 9x$
and $x = 22$.
We aren't asked to solve anything more.
Comment: Thank you very much, this answered my question perfectly.
Answer: Let $V=A\cup B\cup C$. Then for any set $S$, we can define a map $1_S\colon V\to \Bbb Z$ given by
$$1_S(x)=\begin{cases}1&\text{if }x\in S\\0&\text{if }x\notin S\end{cases} $$
With this, we can define the map $\operatorname{ct}\colon V\to \Bbb Z$ as
$$\operatorname{ct}(x)=1_A(x)+1_B(x)+1_C(x). $$
It counts, in how many of the three given sets an element is. Then we can let $$f(n):=|\{\,x\in V\mid \operatorname{ct}(x)=n\,\}|$$
be the number of elements that are in exactly $n$ sets.
With this, condition b) and c) amount to
$$f(1)=2f(2)\qquad f(1)=2f(3).$$


erro em progama

Question: def trianguloPascal(n):
    lista = [[1],[1,1]]
    for i in range(1,n):
        linha = [1]
        for j in range(0,len(lista[i])-1):
            linha += [ lista[i][j] + lista[i][j+1] ]
        linha += [1]
        lista += [linha]
    return lista

n = input("Digite o número de linhas para o triângulo de Pascal: ")
resultado = trianguloPascal(n)

for i in range(len(resultado)):
    print(resultado[i])

Comment: Por favor clique em [edit] acima, selecione todo o código e clique no botão `{}` do editor para formatar corretamente. E por favor explique qual é o problema do código e qual é a sua dúvida.
Comment: João, adicione sempre um título que acrescente conteúdo a sua dúvida e descreva o seu problema de forma detalhada no escopo do post, assim fica mais fácil para receber ajuda
Answer: Você se esqueceu de converter a entrada do usuário de string para inteiro:
resultado = trianguloPascal(int(n))

Veja aqui funcionando no ideone.

erro em progama


git tree is broken

Question: How do I get my git tree to show correctly on a GUI git viewer?
My git tree in all GUI apps has no beginning and actually goes further below than the initial commit. I am the only one facing this problem in my company. I have no idea why but my git tree looks completely different than everyone else in my company.
I tried the following two apps to view the tree:

gitkraken
source tree

I with both apps I deleted all my repositories and cloned from a fresh directory.
Below are 2 image from the start and end of the git log in source tree
The first image shows my develop branch (the red one) is permanently stuck in a weird spot where I am not sure if I can push to that branch to master without history breaking.
The second image shows my branch (the red line) next to master (the blue line) going down into infinity with other branches.
This is not a problem with the repos as everyone else in the company has a nice branching tree when looking at a GUI. Where would I start to identify the problem with git?
Comment: why the downvote? no comment?
Comment: It's because there are a number of unclear things with your question: (1) Are you referring to the blue branch when you say "_crazy broken tree_"? (2) What do you mean by "_looks completely different_"? What does _theirs_ look like? (3) What do you mean by "_permanently stuck in a weird spot_"? (4) Where did all the other "infinity" branches branch-out from? Basically, it's hard to understand what the issue is.
Comment: 1 the blue branch was my develop branch until it broke off. the broken tree I am talking about is the entire tree not just one branch
2 theirs looks like a normal looking git tree. The tree has a root and no branches that have no beginning, and all branches their branches break off of another branch. My git tree looks more like a git forest.
Comment: The graph is dynamically generated, not stored in git. Check the settings at the top of the history tab, most likely you are either looking at one branch instead of all, or looking at ancestor order instead of date order.
Comment: I checked that.The closest to fixing the problem is if I change the settings to show only the current branch, the problem is hidden. until I return to show all branches.
Answer: I have found the true answer, I reformatted the computer and now it works great for reference here is what the tree should look like. Notice there are no line going into nothing.
Comment: That is technically an answer, and does work. I just wish there were some way to do this without reformatting the computer.

git tree is broken