Unable to get access token from Paypal sdk. Got an Exception says "Authentication needed"

Question: I am using PayPal SDK for adaptive payment...I get PayPal Payment Success message in
 - (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
    NSLog(@"PayPal Payment Success!");
    [self sendCompletedPaymentToServer:completedPayment]; // Payment was processed successfully;    send to server for verification and fulfillment
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendCompletedPaymentToServer:(PayPalPayment *)completedPayment {
    // TODO: Send completedPayment.confirmation to server

    NSLog(@"Here is your proof of payment:\n\n%@\n\nSend this to your server for confirmation and    fulfillment.", completedPayment.confirmation);

    payId=[[completedPayment.confirmation objectForKey:@"response"] objectForKey:@"id"];

    [self callForAccessToken];  ///////calll webservice to get access token
}

- (void)callForAccessToken {
    NSString *shippingURL=[NSString stringWithFormat:@"https://api.sandbox.paypal.com/v1/oauth2/token"];
    ASIFormDataRequest *shippingRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:shippingURL]];
    [shippingRequest setRequestMethod:@"POST"];
    shippingRequest.tag=1010;
    [shippingRequest setPostValue:@"application/json" forKey:@"Accept"];
    [shippingRequest setPostValue:@"en_US" forKey:@"Accept-Language"];
    NSString *clientIDSecret=[NSString stringWithFormat:@"kClientID:kClientsecret"];
    [shippingRequest setPostValue:clientIDSecret forKey:@"clientId:secret"];
    [shippingRequest setPostValue:@"client_credentials" forKey:@"grant_type"];
    [shippingRequest setDelegate:self];
    [shippingRequest setDidFinishSelector:@selector(uploadFinishedLocation:)];
    [shippingRequest setDidFailSelector:@selector(uploadFailLocation:)];
    [shippingRequest startAsynchronous];
}

- (void)uploadFinishedLocation:(ASIHTTPRequest *)requestObj {
    NSString *response = [requestObj responseString];
    NSLog(@"\n\nReq tag %ld Response string in Payment Didload %@\n\n",(long)requestObj.tag,response);
}

- (void)uploadFailLocation:(ASIHTTPRequest *)requestObj {
    NSLog(@"%@",requestObj.error.description);
}

When I execute code uploadFailLocation is called...
And I get error:

" Authentication needed "

I got reference to pass all data in post form in key-valuse combination by this link.
https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/#get-an-access-token
So have I pass client id and secredt right way or something is missing.......
Or is there any other way to do this things.....
Answer: The generating of an access token is a server to server call and is not done from your App itself.  Also, when doing so, the client ID and secret are sent in the headers and not just posted as key>value.  The steps to verify a mobile payment can be found here.
Comment: I don't how how to make correct url from these curl syntex..will you please help me..
Comment: I'm not sure I understand your request.  You aren't going to make a URL to simply redirect/post to.  You send the information back to your server and use a server side script to do the payment verification.

Unable to get access token from Paypal sdk. Got an Exception says “Authentication needed”


Optimization with implicit differentiation

Question: I want to find the extrema of a function $F(x,y,z)$ subject to a constraint $g(x,y,z)=c$. This means that implicitely $z=z(x,y)$. So I find $ \frac {\partial F}{\partial x}$ and $ \frac {\partial F}{\partial y}$, using the chain rule to take into account that $z=z(x,y)$. Then I find the points $(x,y,z)$ that solve $\frac {\partial F}{\partial x}=0$ and  $\frac {\partial F}{\partial x}=0$.
For example, let $F(x,y,z)=20+2x+2y+z^2$ and $g(x,y,z)=x^2+y^2+z^2=11$. So
$$\frac {\partial F}{\partial x}=2+2z\frac {\partial z}{\partial x}$$ and $$\frac {\partial F}{\partial y}=2+2z\frac {\partial z}{\partial y}$$
To find $\frac {\partial z}{\partial x}$ and $\frac{\partial z}{\partial y}$ I use the constraint equation,  taking into consideration that the implicit derivatives are $\frac{\partial z}{\partial x}=-\frac{g_x}{g_z}$ and $\frac{\partial z}{\partial y}=-\frac{g_y}{g_z}$. Given that $g_x=2x$, $g_y=2z$ and $g_z=2z$, then $\frac{\partial z}{\partial x}=-\frac{2x}{2z}=-\frac{x}{z}$ and $\frac{\partial z}{\partial y}=-\frac{2y}{2z}=-\frac{y}{z}$. So,
$$0=\frac {\partial F}{\partial x}=2+2z\frac {-x}{z}=2(1-x)$$ and $$0=\frac {\partial F}{\partial y}=2+2z\frac {-y}{z}=2(1-y)$$ We see that $x=1$ and $y=1$. Replazing this values in the constraint equation we found $z$. $$1^2+1^2+z^2=11 \Rightarrow z=\pm 3$$
We can check that $(x,y,z)=(1,1,3)$ and $(x,y,z)=(1,1,-3)$ are maxima.
The real question start here. How to apply this method of optimization (I think it's called "constrained optimization with implicit differentiation") if I have two (o more) constraint equations instead of one?
For example, I want to optimize the (same) function $F(x,y,z)=20+2x+2y+z^2$ constrained by $g_1(x,y,z)=x^2+y^2+z^2=11$ and $g_2(x,y,z)=x+y+z=3$.
$\frac {\partial F}{\partial x}$ and $\frac {\partial F}{\partial y}$ still are
$$\frac {\partial F}{\partial x}=2+2z\frac {\partial z}{\partial x} \tag{1} $$ and $$\frac {\partial F}{\partial y}=2+2z\frac {\partial z}{\partial y} \tag{2} $$ but now
$$\frac{\partial z}{\partial x}=-\frac{{g_1}_x}{{g_1}_z}=-\frac{2x}{2z}=-\frac{x}{z} \ \  and \ also \ \ \frac{\partial z}{\partial x}=-\frac{{g_2}_x}{{g_2}_z}=-\frac{1}{1}=-1 \tag{3}$$
and
$$\frac{\partial z}{\partial y}=-\frac{{g_1}_y}{{g_1}_z}=-\frac{2y}{2z}=-\frac{y}{z} \ \  and \ also \ \ \frac{\partial z}{\partial y}=-\frac{{g_2}_y}{{g_2}_z}=-\frac{1}{1}=-1 \tag{4}$$
(This might suggest that the extrema satisfies $x=y=z$, but I've checked with other method of optimiztion and this is wrong.) So, which of this $\frac{\partial z}{\partial x}$ and $\frac{\partial z}{\partial y}$ should I plug into equations $(1)$ and $(2)$ in order to find the extrema of $F(x,y,z)$ constrained?
(I know that I could solve this problem using direct substitution or Lagrange multipliers, but that's not what I ask in this question)

Edit: Reading the answers and reading about the implicit function theorem (in chapter 2 of Advanced Calculus, by Kaplan), finally I understood how to solve it.
For handier notation I rename the constraints $g_1(x,y,z)=c_1$ and $g_2(x,y,z)=c_2$ as $g(x,y,z)=c_1$ and $h(x,y,z)=c_2$, respectively.
First of all, we shall realize that the equations $g(x,y,z)=c_1$ and $h(x,y,z)=c_2$ imply that there are two dependent variables and one independent variable, for example: $y=y(x$) and $z=z(x)$, with $x$ the independent variable.
Taking differentials of $g(x,y,z)=c_1$ and $h(x,y,z)=c_2$, we have
$dg=g_x dx+g_y dy+g_z dz=0$ and $dh=h_x dx+h_y dy+h_z dz=0$. This can be arranged as $-g_x dx=g_y dy+g_z dz=0$ and $-h_x dx=h_y dy+h_z dz=0$ which in matrix is
$$
\binom{-g_x dx}{-h_x dx} = \begin{bmatrix} g_y & g_z \\  h_y & h_z \end{bmatrix} \binom{dy}{dz}
$$
Here we want to solve solve $dy$ as $dy=G(x,y,z)\ dx$ and $dz$ as $dz=H(x,y,z)\ dx$, where G and H are two yet unknown functions. We could solve it by row operations o Cramer's rule. Using Cramer's rule we get:
$$ dy = \frac{\begin{vmatrix} - g_x\ dx & g_z \\ - h_x\ dx & h_z \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } = - \frac{\begin{vmatrix} g_x & g_z \\ h_x & h_z \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } dx$$
$$ dz = \frac{\begin{vmatrix} g_y & - g_x\ dx \\ h_y & - h_x\ dx \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } = - \frac{\begin{vmatrix} g_y & g_x \\ h_y & h_x \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } dx $$
Rearranging and realizing that the determinants are Jacobians, we get
$$ \frac{dy}{dx} = - \frac{\begin{vmatrix} g_x & g_z \\ h_x & h_z \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } = - \frac{ \frac{\partial(g,h)}{\partial(x,z)} }{ \frac{\partial(g,h)}{\partial(y,z)} } $$
$$ \frac{dz}{dx}  = - \frac{\begin{vmatrix} g_y & g_x \\ h_y & h_x \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } = - \frac{ \frac{\partial(g,h)}{\partial(y,x)} }{ \frac{\partial(g,h)}{\partial(y,z)} } $$
Now I will use this to solve the constrained optimization exercise put above, which is:

Optimize $F(x,y,z)=20+2x+2y+z^2$ constrained by $g(x,y,z)=x^2+y^2+z^2=11$ and $h(x,y,z)=x+y+z=3$.

This constraints imply that two variable are dependent and one is independent. For example, $y=y(x)$ and $z=z(x)$. So, using the chain rule
$$ \frac{\partial F}{\partial x} = \frac{\partial}{\partial x} \left (  2x \right ) + \frac{\partial}{\partial y} \left (  2y \right ) \frac{dy}{dx} + \frac{\partial}{\partial z} \left (  z^2 \right ) \frac{dz}{dx} =2+2\frac{dy}{dx}+2z\frac{dz}{dx}=0$$
To compute $\frac{dy}{dx}$ and $\frac{dz}{dx}$ I use the above result,
$$g_x=2x\ \ \ \ \ \ g_y=2y\ \ \ \ \ \ g_z=2z$$
$$h_x=1\ \ \ \ \ \ h_y=1\ \ \ \ \ \ h_z=1$$
$$ \frac{dy}{dx} = - \frac{\begin{vmatrix} g_x & g_z \\ h_x & h_z \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } = - \frac{\begin{vmatrix} 2x & 2z \\ 1 & 1 \end{vmatrix}}{\begin{vmatrix} 2y & 2z \\  1 & 1 \end{vmatrix} } = -\frac{2x-2z}{2y-2z}= -\frac{x-z}{y-z} $$
$$ \frac{dz}{dx}  = - \frac{\begin{vmatrix} g_y & g_x \\ h_y & h_x \end{vmatrix}}{\begin{vmatrix} g_y & g_z \\  h_y & h_z \end{vmatrix} } = \frac{\begin{vmatrix} 2y & 2x \\ 1 & 1 \end{vmatrix}}{\begin{vmatrix} 2y & 2z \\  1 & 1 \end{vmatrix} } = - \frac{2y-2x}{2y-2z}=- \frac{y-x}{y-z} $$
So, we get
$$ \frac{\partial F}{\partial x} = 2-2 \frac{x-z}{y-z}-2z \frac{y-x}{y-z}=2\frac{(y-z)-(x-z)-z(y-x)}{y-z}=2\frac{(y-x)-z(y-x)}{y-z}=2\frac{(y-x)(1-z)}{y-z}=0 \  \  \  \ (y\neq z) $$
Solving the system of equations
$$ 2\frac{(y-x)(1-z)}{y-z}=0 \tag{E1} $$
$$ x^2+y^2+z^2=11 \tag{E2} $$
$$ x+y+z=3 \tag{E3} $$
we obtain that the extrema are in the points
$$ \left (x,y,z\right )= \left \{ \left (1+\frac{2}{\sqrt{3}},1+\frac{2}{\sqrt{3}},1-\frac{4}{\sqrt{3}} \right ),\left (1-\frac{2}{\sqrt{3}},1-\frac{2}{\sqrt{3}},1+\frac{4}{\sqrt{3}} \right ),\left (3,-1,1\right ),\left (-1,3,1\right )  \right \} $$
which is correct acording to Wolfram Alpha (the first and second points are maximum and the third and fourth are minimum).
By the way, the system of equations that arise from Lagrange multipliers is
$$2=2\lambda x +\mu $$
$$2=2\lambda y+\mu $$
$$2z=2\lambda z+\mu $$
$$ x^2+y^2+z^2=11 $$
$$ x+y+z=3 $$
In this particular example I think this method (implicit derivative) is easier than Lagrange multipliers. From equation $E1$ it's readily seen that either $x=y$ or either $z=1$, so the system is almost solved.
Comment: For instance, one way you could do this in your case would be to write $z=3-x-y$ and then substitute into the other constraint, obtaining $x^2+y^2+(3-x-y)^2=11$. Now you're back to the previous case with two variables and one constraint. Of course usually you cannot explicitly solve either constraint in order to eliminate a variable, but this is the idea.
Comment: With more constraints, the implicit function theorem still goes through, but you have one fewer parameter specifying the surface. For instance, with three variables and two constraints, you have an implicit function $u(x):=\begin{bmatrix} y(x) \\ z(x) \end{bmatrix}$. (Rather, you have possibly several such functions on different neighborhoods, but you already knew about this issue.)
Comment: Thank you for answer. Yes, we could do that, but isn't another way, using the partial derivative equations?
Comment: Using directly equations $(3)$ and $(4)$.
Comment: I'd say the Lagrange multiplier system is still easier. For instance, subtracting the first two equations give either $x=y$ or $\lambda=0$. Substituting $\lambda=0$ into the first equation gives $\mu=2$, then substituting both into the third gives $z=1$. Now you're in pretty much the same situation: either $x=y$ or $z=1,\lambda=0,\mu=2$.
Answer: Let $g:\mathbb{R}^3 \to \mathbb{R}^2$ be given by $g((x,y,z)) = (g_1(x,y,z)-11, g_2(x,y,z)-3)$. The feasible set is described by $g^{-1}(\{0\})$, and you are trying to find $z$ as a function of $x,y$ locally.
Let me abuse notation and write $g(p,z)$ with $p=(x,y)$ to simplify my life.
Then you need to show that ${\partial g(p,z)) \over \partial p}$ is invertible at a solution $(\hat{p}, \hat{z})$, and the implicit function theorem gives some $\pi$ defined locally around $\hat{z}$ such that $g(\pi(z),z) =0$ for
$z$ near $\hat{z}$, and we have
${\partial \pi(\hat{z})) \over \partial z} = - {\partial g(\hat{p},\hat{z})) \over \partial p}^{-1} {\partial g(\hat{p},\hat{z})) \over \partial z}$.
If we let $\phi(z) = f(\pi(z),z)$ (abusing notation again), then at a solution we will have ${\partial \phi(\hat{z})) \over \partial z} = 0$, using the
chain rule this reduces to
${\partial f(\hat{z},\hat{p})) \over \partial z} = {\partial f(\hat{z},\hat{p})) \over \partial p} {\partial g(\hat{p},\hat{z})) \over \partial p}^{-1} {\partial g(\hat{p},\hat{z})) \over \partial z}$.
(As an aside, when used as a method for numerical optimization, this is known as 'reduced gradients'.)
Answer: Extremising functions which satisfy one or more constraints is the topic of Lagrange multipliers (see book 'Calculus' by Stewart, chapter 15.8, for instance).
To extremise a function $f(x,y,z)$ subject to two constraints $g(x,y,z) = k$ and $h(x,y,z) = c$ we need to solve the following equation: $\nabla f(x_{0},y_{0},z_{0}) = \lambda \nabla g(x_{0},y_{0},z_{0}) + \mu \nabla h(x_{0},y_{0},z_{0})$, where $\lambda$ and $\mu$ are called Lagrange multipliers and the point $(x_{0},y_{0},z_{0})$ is a solution point.
Essentially, this means solving the following five equations: $f_{x} = \lambda g_{x} + \mu h_{x}, f_{y} = \lambda g_{y} + \mu h_{y}, f_{z} = \lambda g_{z} + \mu h_{z}, g(x,y,z) = k, h(x,y,z) = c$.
We have five equations, five unknowns. Of course, these may not be easily solved, but the usual procedure is to use the first three equations to find the Lagrange multipliers $\lambda$ and $\mu$ (possibly in terms of $x,y,z$), then use the last two equations to find the values of $x,y,z$. Finally, evaluate $f$ at the values $x,y,z$.
There is a nice geometrical explanation of where the above equation comes from, again I refer to Stewart, section 15.8.
EDIT: sorry, I did not realise you were looking for a method using the Implicit Function Theorem.
Comment: The OP already mentioned that (s)he knows how to do it with Lagrange multipliers and would like to know how one might do it with implicit functions.
Answer: If you want to do this with the implicit function theorem, you have to formulate it in the multivariable setting.
You have a function $G : \mathbb{R}^3 \to \mathbb{R}^2$ which defines your constraint. You think of $\mathbb{R}^3$ as $\mathbb{R} \times \mathbb{R}^2$, where the two are the "$y$" variables and the one is the "$x$" variable.
Then $DG(x,y) : \mathbb{R}^3 \to \mathbb{R}^2$ is the Jacobian of $G$ at $(x,y) \in \mathbb{R}^3$. Now $G(x,y)=c$ defines an implicit function $g : \mathbb{R} \to \mathbb{R}^2$, which we think of as $y=g(x)$. $DG$ can be broken up into two blocks, $DG_y \in \mathbb{R}^{2 \times 2}$ from the $y$ derivatives and $DG_x \in \mathbb{R}^{2 \times 1}$ from the $x$ derivatives.
Now the implicit function theorem tells you that
$$\frac{dg}{dx} = -\left ( \left (DG_y \right )(x,g(x)) \right )^{-1} DG_x(x,g(x)).$$
Now you use this with the chain rule to find $\frac{dF}{dx}$, that is, the derivative of $F$ with respect to $x$ while taking into account how $y$ and $z$ respond to changes in $x$. (Here I am slightly lapsing into physicist notation, I hope you will excuse this.) This is given by (choosing $g_1=y,g_2=z$)
$$\frac{dF}{dx} = \frac{\partial F}{\partial x} + \frac{\partial F}{\partial y} \frac{dg_1}{dx} + \frac{\partial F}{\partial z} \frac{dg_2}{dx}.$$
Now you set that equal to zero.
(Another thing to be excused is that I have written the implicitly defined functions as defined on the whole space when they are really only locally defined. Please excuse this abuse as well; the point is really to label how many free parameters each function has.)
Comment: Although I don't fully understand your answer, it motivated me to search more about the implicit function theorem, and there I found the answer to my question. Now I've edited my question and added the answer to it. Tell me if what I've found is what you were telling in your post.
Comment: @user246185 What you wrote is essentially the same as what I wrote, just written in terms of differentials.
Comment: @user246185 Note that you can also write my equation as $\frac{dF(x,g(x))}{dx} = \frac{\partial F}{\partial x} + \nabla_u F \cdot \frac{dg}{dx}$ (where $u$ is the vector $\begin{bmatrix} y \\ z \end{bmatrix}$). Understood this way, all I have really done is write the chain rule and then told you how to calculate $\frac{dg}{dx}$.


Contour Integration

Question: I'm having trouble with the step highlighted in green. As the angle $2\pi /n$is maintained as R goes to infinity, I don't see how you end up just integrating on the x axis.
Answer: Since the notes you attached are a little cavalier, I have added the details for the problem. Let $f(z) = \frac{1}{1+z^n}$ and $\Gamma$ is the arc. From the contour, we have
$$
\int_0^{\infty}\frac{dx}{1 + x^n}  = \lim_{R\to\infty}\biggl[\int_0^R+\int_{\Gamma}+\int_R^0\biggr]f(z)dz = 2i\pi\sum_j\operatorname{Res}\{f(z);z_j\}
$$
The only pole in the sector is then $z = e^{i\pi/n}$. The residue is then
$$
\lim_{z\to e^{i\pi/n}}\frac{z-e^{i\pi/n}}{1+z^n}=\lim_{z\to e^{i\pi/n}}\frac{1}{nz^{n-1}}=\frac{-e^{i\pi/n}}{n}
$$
Therefore, we now have
$$
\frac{-2i\pi e^{i\pi/n}}{n} = \int_0^{\infty}\frac{dz}{1+z^n}+\lim_{R\to\infty}\int_0^{2\pi/n}\frac{iRe^{i\theta}}{1+R^ne^{in\theta}}d\theta+\int_{\infty}^0\frac{dz}{1+z^n}
$$
where, for the third integral, $z = re^{2i\pi/n}$, $r\in[0,R]$, and $dz = e^{2i\pi/n}dr$. Then the third integral can be written as
$$
-\int_0^{\infty}\frac{e^{2i\pi/n}}{1+r^n}dr
$$
Since $r$ is a dummy variable, let $r = z$.
\begin{align}
\int_0^{\infty}\frac{dz}{1+z^n} &= -\lim_{R\to\infty}\int_0^{2\pi/n}\frac{iRe^{i\theta}}{1+R^ne^{in\theta}}d\theta+\int_0^{\infty}\frac{e^{2i\pi/n}}{1+z^n}dz - \frac{2i\pi e^{i\pi/n}}{n}\\
(1-e^{2i\pi/n})\int_0^{\infty}\frac{dz}{1+z^n}&= -\lim_{R\to\infty}\int_0^{2\pi/n}\frac{iRe^{i\theta}}{1+R^ne^{in\theta}}d\theta -
\frac{2i\pi e^{i\pi/n}}{n}
\end{align}
Let's consider the first integral only now.
$$
\Biggl\lvert\int_0^{2\pi/n}\frac{iRe^{i\theta}}{1+R^ne^{in\theta}}d\theta\Biggr\rvert\leq\int_0^{2\pi/n}\biggl\lvert\frac{iRe^{i\theta}}{1+R^ne^{in\theta}}\biggr\rvert d\theta\leq\int_0^{2\pi/n}\biggl\lvert\frac{Re^{i\theta}}{R^ne^{in\theta}}\biggr\rvert d\theta = \frac{2\pi}{nR^{n-1}}
$$
Since our contour is a wedge, $n>1$. If $n=1$, we would be integrating over a circle instead.
$$
\lim_{R\to\infty}\int_0^{2\pi/n}\frac{iRe^{i\theta}}{1+R^ne^{in\theta}}d\theta\leq\lim_{R\to\infty}\frac{2\pi}{nR^{n-1}} = 0
$$
We are now only left with
\begin{align}
(1-e^{2i\pi/n})\int_0^{\infty}\frac{dz}{1+z^n}&= \frac{-2i\pi e^{i\pi/n}}{n}\\
\int_0^{\infty}\frac{dx}{1+x^n} &= \frac{-2i\pi e^{i\pi/n}}{n(1-e^{2i\pi/n})}\\
&=\frac{\pi}{n}\csc(\pi/n)
\end{align}
Answer: On  $\gamma_3$ we have $z = e^{2 \pi i/n} x$ where $x$ goes from $R$ to $0$, so
$dz = e^{2\pi i/n} dx$ and $\int_{\gamma_3} \dfrac{1}{1+z^n} dz = e^{2\pi i/n} \int_R^0 \ldots$

Contour Integration


Why do we resample in bootstrap estimation?

Question: Why do we need to resample from an initial set of samples when using bootstrapping? Why don't we just take fresh sets of samples from the original distribution? What is the justification behind resampling? Or is it just a computational trick?
EDIT: I understand that it is usually very expensive to get fresh samples, but assuming we have access to a generator of the original distribution, does it still make sense to resample due to some theoretical reasons?
Comment: Fresh samples would presumably mean using other similar datasets, and that would often be a very good idea. The problem is that often there is little or no scope for collecting more data, at least with available resources. (You wouldn't relaunch the _Titanic_ and crash it into another iceberg.) So the idea is to use the present dataset itself to tell you about variability. And no, it's not just a computational trick.
Comment: In life, sampling from the true distribution is expensive, impossible.  It's the money.  https://www.youtube.com/watch?v=s2VG53RIJ50
Comment: I read the first few pages of the Bootstrap paper (http://projecteuclid.org/download/pdf_1/euclid.aos/1176344552 ) , now it makes more sense. The problem bootstrap is trying to solve is when you don't have access to the "generator" of the samples and just have one set of samples. Thanks
Comment: @NickCox: I don't think [this](http://stats.stackexchange.com/questions/26088/explaining-to-laypeople-why-bootstrapping-works) is a duplicate. Yes, the answers address why you wouldn't simply sample again... but only in passing. I searched a bit for "why resample is:q" and similar and came up empty-handed.
Comment: The question is good but I think we need to be clear that it isn't already answered.
Comment: @StephanKolassa Done.
Comment: Updated the question. @NickCox My question is more about in what ways is it more than a computational trick?
Comment: I think it would be better to add to an existing strong thread than to start a new one. Our problems in middle age are getting bigger and splitting up!
Comment: I remain unconvinced that the question as edited is genuinely new (or, a different matter, precise and focused enough to be answered with reasonable effort).
Answer: In real life, sample points have real costs, so sampling from the true distribution is, at best, expensive, and at worst, impossible.  So, it's the money.  The bootstrap is mostly free.
As @NickCox puts it with exceptional visual aplomb:

You wouldn't relaunch the Titanic and crash it into another iceberg

Because, you know, that would be expensive (in many, many ways).

I understand that it is usually very expensive to get fresh samples, but assuming we have access to a generator of the original distribution, does it still make sense to re-sample due to some theoretical reasons?

No.  If it's free to sample from the population distribution, you should do so.


What is at the tip of large string concert instruments, and does it damage the floor?

Question: I sat very close to the stage Friday night for the Pops.
I could see a cellist in the front row and noticed the bottom tip of a metal rod where the cello stands, making contact with the wooden floor.
What is the construction of the tip of the stand, and doesn't it mark up the wooden floor?  I think it would be even more of an issue with the large basses.
Comment: I really don't think they'd be allowed if they damaged the floor.
Comment: If you're playing dive bars then nobody cares about anything except selling more liquor. Kick drums have two legs that swing out. Each has a rubber boot that can screw up or down, exposing a spike, and they most certainly *do* damage the floor, as does the two spikes in the kick pedal itself that keep it from getting pushed away. If there's no rug on the stage then it all sucks and everything goes everywhere. Which is why I removed the rubber boots and just had spikes. The show must go on and it can't if the kick drum is trying to run away.
Comment: @Mazura - nearly all the drummers I've played with arrive with their own roll of carpet or such like. Shows respect, and keeps the drummer from encroaching on the rest of the band. Also, possibly dampens the noise slightly. Win-win. Yet to play with the drummer who arrives with a hammer and 6" nails, but it wouldn't surprise me...
Comment: @Tim I call them rock star rugs.
Comment: @JasonPSallinger - I thought that's what they wore on their chests...
Comment: And the High Hat has two spikes as would a second kick pedal. So that's eight spikes going into the floor. If you're worried about the finish on the floor then don't book rock bands.
Comment: @Tim  As the answers suggest, it depends a LOT on what kind of floor and what the general use is.
Comment: All the drummers I know have a carpet rolled up in the van as an essential part of their kit. But this is Germany...
Comment: @RedSonja - I can't remember ever playing with a drummer who didn't use a carpet, anywhere - it also helps the hi-hat stay in its place. But would a carpet help with a 'cello?
Comment: In my distant youth I played in a string orchestra. The cellos had little round rubber mats. There was a stack of them behind stage, so maybe every venue has their own. Anyway, the janitor/housemaster/music teacher does their best not to leave holes in the nice wooden floor.
Comment: @Mazura I don't see a lot of cellists playing in dive bars.
Comment: @ibonyun how about stand up bass?
Comment: @ibonyun I do know a baroque group that played Bach's Art of the Fugue in the local indie-rock venue. But then, it's baroque cello so no endpin ;)
Comment: @Damila  I am sure the Barenaked Ladies must have started out in smaller venues.
Comment: @JasonPSallinger and the Piano Guys- one plays all sorts of cellos. Must have started small.
Answer: The device is an 'endpin' or just 'spike'.
Floor damage is prevented by addition of a protector, variously called endpin stoppers, pinstops, donuts, black holes, endpin anchors, endpin holders, spike holders or rock stops.
Available in a myriad styles, from a simple rubber stopper to more complex and stable designs.

Comment: This is really interesting but the cellists in our orchestra always had "cello Ts" (pronounced "Tees") which were two pieces of wood in a T shape which sat under the chair with the cross-bar braced on the legs of the chair and the base on the T protruding out the front. There may have been dimples already there for cellists to choose their angle. Hearing the slap of these being dished out on the concert stage is a lasting memory, but I cannot find a picture of one. They were sturdy and cheap but not portable. Are they still common?
Comment: I can elaborate on this comment a little later, but you could add a bit about why they're there in the first place (in the case of cello, they weren't always, but like the violin's chinrest and shoulder rest, they  free up the  playing posture so you don't have to hold the cello up with your legs), And the fact that most of those endpin stops, or the spiky tip, are about making sure that the end pin doesn't simply slide away from you.
Comment: All of this is information I wanted to know.  I am happy with all of this.
Comment: I got the impression the OP was talking about the metal spike itself, not the ways to protect the floors from it...
Comment: Yeah, second reading does feel more that way - edited to cover both
Comment: My bass clarinet has a round rubber blob on the bottom of its spike. It actually slips on most floors, so I tuck it behind my foot. But this inspires me to get a better blob.
Comment: What are those figures on the blue one?  They seem to be related to beamed notes, but they aren't exactly beamed notes.
Comment: @phoog Dropping it into a Google image search yielded a lot of listings on Amazon, AliBaba, etc, [like this one](https://www.walmart.com/ip/Peach-Blossom-Anti-Slip-Cushion-with-Hole-for-Musical-Instrument-Parts-8x8-8x1-3cm/1043277344?wmlspartner=wlpa&selectedSellerId=101126664), where it can be admired in all its peculiar glory (and one can appreciate the rather poetic description). I'd like to think the figure started its life as some kind of logo, intentionally melding a pair of notes with the letter "A"? Though I can't explain the "smokestack" sticking up on the right...
Answer: This is really an "extra" answer augmenting, since Tetsujin has the important part.
Yes, endpin spikes definitely can damage floors. The cellist's main concern is that their instrument stay in place, not the health of the floor. The acute angle formed between the endpin and the floor means that, on a slick floor, the endpin would simply slide away from the player. This is a frequent irritation to cellists, and you sometimes see them jab their endpin aggressively into a wood floor to get a good purchase.
Mind you, many things are hard on the floor of a commercial theatre (tap shoes!), and the surface often gets a thick coat of black paint; on some stages the actual wood might be quite a ways below the paint. But when cellists meet valuable floors that proprietors feel strongly about, there can be some tension. All of the "endpin stops" that Testsujin pictured protect the floors; more importantly (from the cellist's point of view) they can reduce the chance of the endpin slipping. (The ones with straps do best at this; one end of the strap goes under a chair leg.) Also, when the floor is tile, stone, etc, the cellist can't simply gouge into the floor, so these devices become more important. Lacking them, they might look for a spot where four tiles come together; in my music school there were often small divots at these joints from decades of endpins.
So what's the point of the endpin? It "fills up the space" between the cello and the floor. With a larger instrument like a double bass there's less space to "fill up"; it's already so tall that the "playing parts" are in the right place. But if there were no endpin, then the bare wood of the bottom of the instrument would rest on the floor. This would have a number of problems; it might scratch up the instrument, it might vibrate in a buzzing way, and I suppose it might have an effect on the sound, if part of the wood were muffled. Plus, depending on the size of the instrument and the player, some height is needed to put the instrument in the perfect playing position. So even historically, we see large instruments like this with endpins, like in this picture from Marin Mersenne's 1627 Harmonie Universelle:

Smaller instruments, like the viol or the "cello-sized cello" (it's complicated) were held in a variety of ways. There was a lot of variety among bass-register bowed strings in the renaissance and baroque—they came in many shapes and sizes, had varying numbers of strings (note the five pegs in the picture above), used varying tuning intervals, had frets or didn't, etc. And although most baroque cello and viol players today support the instrument with the inside of their legs (and there are many paintings showing this hold), some paintings show larger instruments resting on a foot, or a small stool or barrel:

Eventually, by the 18th century, there is talk of wooden endpins. There's a very thorough history of endpins as someone's doctoral dissertation, with a survey of these iconographic sources and mentions in treatises.
With double basses, the endpin has much less need to sharp, since the angle is usually much less acute (that is, the instrument is more upright), so there's less chance of it sliding forward.
Comment: @IanGoldby The dissertation makes mention of classical guitarist Paul Galbraith, who holds the guitar cello-like, with an endpin, resting on a wooden box for resonance.
Comment: I like, and have seen, the strap round the leg of a chair idea. It means, as you say, the endpin is anchored on any surface, and I've seen straps with cups on the end, to accommodate the tip, so will work anywhere. No big deal, just simple innovation, with an adjustable strap - often 'hook and loop'.
Comment: -1, As a cellist, I've never met another who does not employ an endpin anchor. I'd like to see an example before I believe there are cellists "aggressively jabbing their endpin into a wood floor".
Comment: A secondary function of the end-pin is to couple the instrument to the floor so that, depending on the type of floor, it can help to transmit the vibrations that make the sound. It is said that before the advent of electronic amplification, swing band double bass players would try to arrive early at the venue so they could locate and lay claim to a location on the platform that produced a good resonance.
Comment: @ToivoSäwén every cellist has an endpin anchor, sure. But if a venue permits ramming the spike directly in wood, that _is_ still a better option. It is the most reliable way to avoid sliding (in particular side-to-side) under flamboyant playing, it allows arbitrarily changing the chair-instrument distance without any fiddling with straps, and it allows getting seated and starting to play without awkward aiming-for-the-anchor.
Comment: @Tim My daughter just started cello and I immediately got the "strap plus cup" one for her. I guess the appeal of the "pucks" can be that: 1) If you're sitting on something non-standard, like a folding piano bench, it might not have a convenient "foot" that the D-ring of the strap can go over; 2) I suppose, if you have to sit on something that isn't your preferred height, the placement of the endpin might need to vary, forcing you to adjust the length of the strap, whereas the "puck" is grab-and-go. But most pucks slip sometimes, especially the cheaper ones.


Using input() to quit

Question: I'm a pretty new programmer and have been working with Python 3 for a few weeks. I tried making a little magic 8 ball program where you get an answer to a question and it asks if you want to play again. however no matter what I enter it never quits and keeps looping. I'm not sure what I'm doing wrong. Any help is greatly appreciated!
#Magic 8 Ball V2
import random
import time

class Magic8ball:

    def __init__(self, color):
        self.color = color

    def getanswer(self):
        responselist = ['The future looks bright!', 'Not too good...', 'Its a fact!',
                        'The future seems cloudy', 'Ask again later', 'Doesnt look too good for you',
                        'How would i know?', 'Maybe another time']
        cho = random.randint(0, 7)
        print ('Getting answer...')
        time.sleep(2)
        print (responselist[cho])

purple = Magic8ball('Purple')
blue = Magic8ball('Blue')
black = Magic8ball('Black')

while True:
    print ('Welcome to the magic 8 ball sim part 2')
    input('Ask your question:')
    black.getanswer()
    print ('Would you like to play again?')
    choice = ' '
    choice = input()
    if choice != 'y' or choice != 'yes':
        break

Comment: Your Boolean logic is wrong...
Comment: If you are never quitting, then something else is going on.  As written, it should always *exit*.
Answer: Three things wrong with your code:
1)
choice = ' '
choice = input()

No need for the first line, you are immediately overriding it.
2)
print ('Would you like to play again?')
choice = input()

Instead of this, use just input("Would you like to play again?")
3)
The logic on the line of if choice != 'y' or choice != 'yes': is wrong.
In my opinion it would be better if you did this:
if choice not in ("y", "yes"):

This would make it really clear what you are trying to do.
Also, you might want to consider using choice.lower() just for the convenience of the users. So that Yes still counts.
Comment: `item in set(...)` is amortized `O(1)`, because it hashes values.  `item in list(...)` is `O(n)`, as it needs to check every element in the list.
Comment: You mentioned `not item in...` vs `item not in...`, that difference is even smaller, especially if you move the set creation outside the loop.
Comment: `if choice not in set(["y", "yes"])` is faster still.
Comment: @RoadieRich How come? `set()` just does some additional operation (checking for dublication and creating a new object) after it creates the list, adding more overhead. I will actually change the list into a tuple since it's a bit faster as far as I remember.
Comment: @RoadieRich come on, the overhead of creating the set is way more than the tiny efficiency (if there even is, since hashing takes time) of a hash table on 2 elements.
Comment: @AmitGold Working now! Awesome and thanks for the help!
Comment: @Tamilist you might also use `choice.lower()` for the convenience of the users.
Answer: Use sys.exit() to quit the shell.
Also, as @jonrsharpe notes, you want and instead of or on this line:
if choice != 'y' or choice != 'yes':
That's because if the user supplies 'y', the program will do two checks: First, it checks if choice != 'y', which is false. Then, because you are using or, it checks if choice != 'yes', which is true. Therefore, the program will break out of the while loop no matter what the user inputs.

Using input() to quit


With bash on Windows 10, why does it execute my $() as separate commands?

Question: I'm learning how to work with Docker and Minikube on a Windows 10 Home computer.  I've installed the needed software OK.  I've installed Docker, minikube, kubectl, and a recent version of MySQL, properly pathed so its CLI can be used.  I'm using either the Bash console provided by GIT, and/or the Bash console provided by Cygwin.  Both seem to provide the same (bad) results.
I start Docker, and install the MySQL service.  The kubectl get all shows everything running OK.
Per the programming book I'm working through, I want to try accessing MySQL through this command:
mysql -h $(minikube service mysql-svc --format "{{.IP}}") -P $(minikube service mysql-svc --format "{{.Port}}") -u root -p

The result should be the MySQL CLI prompt, like mysql>  .  Instead I get this behavior:

A popup window stating "Windows cannot find '192.168.99.101'.  Make sure you typed the name correctly, and then try again."

The console text:
The system cannot find the file 192.168.99.101.
*
X open url failed: 192.168.99.101: exit status 1
*
* minikube is exiting due to an error. If the above message is not useful, open an issue:
- (URL for sending an error message)

A popup window stating "Windows cannot find '31067'.  Make sure you typed the name correctly, and then try again."

The console text:
mysql: [ERROR] Unknown suffix '|' used for variable 'port' (value (gives the border fence that surrounds the output from  minikube service mysql-svc  .)
mysql: [ERROR] (path to mysql.exe): Error while setting value '|-----|--- (etc)' to 'port'

The expected behavior is to insert an IP and Port into the mysql command line, then firing a command like  mysql -h http://192.168.99.101 -P 31067 -u root -p  .
I think that the problem is with the using the Bash console in a Windows environment.  Any explanation is appreciated.
Thanks,
Jerome.
UPDATE ON 8/7/2020:
I'm asked to more thoroughly document my issue.  Here we go.
Here is what Docker knows:
$ docker images
REPOSITORY                                                        TAG
      IMAGE ID            CREATED             SIZE
logicaltiger/cloudnative-statelessness-posts                      latest
      3a3c66daf7f3        5 days ago          139MB
logicaltiger/cloudnative-statelessness-connections                latest
      d060e9857f49        5 days ago          139MB
logicaltiger/cloudnative-statelessness-connectionposts-stateful   latest
      ce33f0966380        5 days ago          123MB
openjdk                                                           8-jdk-alpine
      a3562aa0b991        15 months ago       105MB
mysql                                                             8.0.12
      ee1e8adfcefb        22 months ago       484MB

Here is my reconfiguring of minikube.  Other posters suggested that minikube runs iffy unless given a lot of resources.
$ minikube delete
* Deleting "minikube" in virtualbox ...
* Removed all traces of the "minikube" cluster.

$ minikube start --cpus=4 --memory=4096
* minikube v1.12.1 on Microsoft Windows 10 Home 10.0.18363 Build 18363
* Automatically selected the virtualbox driver
* Starting control plane node minikube in cluster minikube
* Creating virtualbox VM (CPUs=4, Memory=4096MB, Disk=20000MB) ...
* Found network options:
  - NO_PROXY=192.168.99.100
  - no_proxy=192.168.99.100
* Preparing Kubernetes v1.18.3 on Docker 19.03.12 ...
  - env NO_PROXY=192.168.99.100
* Verifying Kubernetes components...
* Enabled addons: default-storageclass, storage-provisioner
* Done! kubectl is now configured to use "minikube"

After starting mysql from its yaml file I have it running:
$ kubectl get all
NAME                         READY   STATUS    RESTARTS   AGE
pod/mysql-7dbfd4dbc4-b2tmm   1/1     Running   0          2m55s

NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          A
GE
service/kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP          6
m43s
service/mysql-svc    NodePort    10.102.7.119   <none>        3306:32235/TCP   2
m55s

NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/mysql   1/1     1            1           2m55s

NAME                               DESIRED   CURRENT   READY   AGE
replicaset.apps/mysql-7dbfd4dbc4   1         1         1       2m55s

Now get the mysql-svc URL:
$ minikube service mysql-svc --url
http://192.168.99.102:32235

Try to run the book example.  Again I get the two popup windows and what is shown below in the terminal.  I omit the popup window text here...
$ mysql -h $(minikube service mysql-svc --format "{{.IP}}") -P $(minikube service mysql-svc --format "{{.Port}}") -u root -p
The system cannot find the file 192.168.99.102.
*
X open url failed: 192.168.99.102: exit status 1
*
* minikube is exiting due to an error. If the above message is not useful, open
an issue:
  - https://github.com/kubernetes/minikube/issues/new/choose
The system cannot find the file 32235.
*
X open url failed: 32235: exit status 1
*
* minikube is exiting due to an error. If the above message is not useful, open
an issue:
  - https://github.com/kubernetes/minikube/issues/new/choose
mysql: [ERROR] Unknown suffix '|' used for variable 'port' (value '|-----------|
-----------|-------------|-------|')
mysql: [ERROR] C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe: Error whil
e setting value '|-----------|-----------|-------------|-------|' to 'port'

I'm asked what happens if I put in the IP directly.  From above, that IP was http://192.168.99.102:32235
$ mysql -h http://192.168.99.102 -P 32235 -u root -p
Enter password: **********
ERROR 2005 (HY000): Unknown MySQL server host 'http://192.168.99.102' (0)

When directly entering the IP and Port, the MySQL server IS reached (see the "Enter password:" prompt) but the request is refused.  I'm thinking that I don't know how to make MySQL use the HTTP request.
But is the MySQL not knowing what to do with the IP, and the way that the indirect method (minikube service mysql -svc ...), related?
Continuing, I edit my cookbook-deployment-posts.yaml file with the MySQL address:
kind: Service
apiVersion: v1
metadata:
  name: posts-svc
spec:
  selector:
    app: posts
  ports:
  - protocol: "TCP"
    port: 80
    targetPort: 8080
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts
  labels:
    app: posts
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
      - name: posts
        image: cdavisafc/cloudnative-statelessness-posts
        env:
          - name: INSTANCE_IP
            valueFrom:
              fieldRef:
                fieldPath: status.podIP
          - name: PORT
            value: "8080"
          - name: SPRING_APPLICATION_JSON
            value: '{"spring":{"datasource":{"url":"jdbc:mysql://192.168.99.102:32235/cookbook"}}}'

Going to kubectl get all, the posts-svc continually starts, errors out and reboots.  Don't know what is wrong...
Jerome.
Comment: Does this `then firing a command like mysql -h http://192.168.99.101 -P 31067 -u root -p` actually work? `I start Docker, and install the MySQL service.` You mean you deployed a mysql pod and service? docker is docker, kubernetes is kubernetes.  Take a look at example [here](https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/). Could you add output from `kubectl get all`?
Answer: I now see a number of things going wrong.
First, I keep thinking that the mysql call is somehow related to the MySQL installed on my PC.  It never is.  Just because I manually create a cookbook database on my PC instance doesn't mean that the textbook example thru Docker / Minikube ever references it.
Second, the textbook is missing the --url from its minikube requests.  Here is what is happening.
> kubectl create -f mysql-deployment.yaml

> minikube service mysql-svc --url
http://192.168.99.102:31030

> minikube service mysql-svc

This opens the web browser to show the service at 192.168.99.102:31030.  The mysql service doesn't render a web page, but that doesn't matter to this example.  The console then shows the details of the service (namespace, name, target port, url) in an ASCII box.
minikube service mysql-svc --format "{{.IP}}"

This wants to open the web browser to show the service at http://192.168.99.102, with an implied port of 80.  But there is nothing there, and Windows complains at a popup box.  The console then complains about not opening that url.
minikube service mysql-svc --format "{{.Port}}"

This wants to open the web browser to show the service at 31030, which isn't a valid URL.  Complaints, complaints.
What I really wanted all along is to add the --url to the minikube bits:
mysql -h $(minikube service mysql-svc --format "{{.IP}}" --url) -P $(minikube service mysql-svc --format "{{.Port}}" --url) -u root -p

This connects to the managed mysql in the console, yielding the mysql> prompt.  Now I can run 'create database cookbook;'.
Solved!


Check if a function is entire or holomorphic

Question:
Let $\;f: \mathbb{C}  \rightarrow \mathbb{C}$ be the function
$$f(z) = \left\{ \begin{array}{cl} 0 & z = 0 \\ e^{-\frac{1}{z^2}} & z
 \neq 0 \end{array} \right.$$
Show that $f$ is not an entire function, but holomorphic for $\mathbb{C}
 \setminus \{0\}$.

I really don't get the definitions of holomorphic and entire functions (yet). Can you please tell me how this can be proved?
Comment: A function $f$ is *holomorphic* at a point $x$ if $f$ is differentiable (as a complex function) on a neighbourhood of $x$, i.e. on some small disc around $x$. $f$ is called entire if it's holomorphic at *every* point in the whole complex plane. Your function is holomorphic everywhere except at $0$, so it's not entire.
Answer: It is pretty easy to show that $f(z)$ is holomorphic on $\mathbb{C}\backslash\{0\}$ (e.g. by noticing that it is a composition of the exponential and a rational function), to show that it is not entire (i.e. holomorphic on the whole $\mathbb{C}$), notice (and by that, I mean prove) that it's derivative at $0$ cannot be defined (take the limit approaching $0$ in various directions).
Comment: The derivatives at $0$ do not exist. If you approach $0$ along the imaginary axis, the function blows up.
Comment: @DanielFischer Ah, you're right of course. Well, that works as a proof, too. I will correct my answer.
Comment: @DanielRobert-Nicoud great, thank you!
Answer: $f$ is not even continuous at $0$: $$f(i/n)=e^{n^2}\to\infty\ne 0 $$
Comment: I thought about your answer and do understand that $f$ is not continous at $0$, but why does this lead to one of the two assumptions for $f$? And what do you mean by $e^{n^2} \rightarrow \infty \neq 0$?
Comment: Every entire function is continuous everywhere..
Comment: @muffel As Herbert said, a function that is not even continuous cannot be entire. To show discontinuity I picked the specific sequence $\frac in$, $n\in\mathbb N$ that converges to $0$, so for continuous $f$ we would have $f(i/n)\to 0$ as $n\to\infty$. however, $f(i/n)=e^{n^2}$, which clearly tends to $\infty$ instaed.


Como validar um formulário de Login no Ionic 3

Question: Como validar um formulário de Login que contem EMAIL e SENHA no Ionic 3?
É necessário a criação de um novo componente para validar estes campos ?
Comment: Use o FormGroup de '@angular/forms';
Comment: Quando você fala validar é o que? Verificar se é email válido e senha tem X caracteres por exemplo ou ver se os dados batem?
Comment: Eduardo, exatamente isto.
Comment: Renan, vou tentar usa-lo
Answer: As validações no Ionic 3 podem ser implementadas no próprio JS com uma funçao validaFormulario() ou com os Froms do angular.
Segue um tutorial de implementação de uma tela de login com FormBuilder que acredito ser a forma mais eficiente e elegante de validação de formulários.
https://robferguson.org/blog/2017/11/19/ionic-3-and-forms/


Best plot in R for count data with a broad range and lots of low frequency data

Question: I have a data set that looks like this, in reality there are about twenty categories with a count of 1:
Things Count
Cars 500
Trucks 250
Jeeps 17
Planes 2
Foot 1
Oranges 1
Plasters 1
Grapes 1
Tablets 1
Pillows 1

I have tried plotting:

Pie charts (too many low frequency entries - with a second zoomed in one on the low counts this looks silly as they all have counts of one).

Bar charts: Not a nice aesthetic with lots of 1 counts in the tail.

Treemaps (using treemapify) - again too many low frequency tiles to many don't have their name within them.

I would like to know how people visualize such data in a presentable way. Online searches don't yield many helpful responses. Maybe I'll  just stick with a table?
This is a toy example, in reality I am trying to visualize patients that have been given a genetic diagnosis for a set disease to the "things" are genes and then their counts. Many people have a rare gene, hence the low counts, but a few genes make up a larger proportion of the diagnoses. I want to tell this story in the most visually appealing way possible. I have been on the R Gallery, but none of the plots really seemed to deal with count data with such a broad range.
Comment: A log scale for counts may work. For appropriate values of "work"... Possibly cut your dataset into two, one for "high" and one for "low" counts, then have two plots that are at least comparable "internally". (Or even more than two.)
Comment: What is the nature of the data?  Is each of these a separate variable, or is this one variable with many possibilities?  Eg, can a patient have gene cars & gene pillows, or is there one gene, and the patient could have the cars version of it or the pillows version of it?
Comment: Also, regarding "I want to tell this story...", can you clarify the substantive / scientific *story* you want to illustrate?  Is it that there are lots of patients with rare variants but that they are all different variants, or is it that these variants, given that they are rare, are probably not that important, or something else?
Comment: @gung-ReinstateMonica each patient just has one gene, so would be one of pillows or cars etc.
Comment: @StephanKolassa That's a good suggestion, I need to try and keep the plots to a minimum as it is part of an academic paper and there are already a fair few figures!
Comment: Do you know the relative frequencies of these variants in the population without this disease?
Comment: Can you provide the full list of 40 categories, or even better, 40 genes? I would combine the singleton categories into meaningful groups first. (Are there natural grouping of those rare genes?) This would simplify the problem greatly. I agree with @GeorgeSavva that a table is probably best but a table that has ~35 rows of 1s may be hard to process. So would be a legend with ~35 category names squashed together.
Comment: Surprisingly or not, I remain more convinced by my own answer, but I naturally agree with @dipetkov that a real or realistic data example is needed to test what works best. I have other tricks too!
Comment: Yes, @NickCox's suggestions are good too.
Answer: Two simple variations on the suggestion of logarithmic scale by @Stephan Kolassa are

square root scale (some history as a first aid transformation for counts)

log(count + 1) scale implemented directly in many environments as a function log1p(). Several examples using this scale can be found in Tukey, J.W. 1977. Exploratory Data Analysis. Reading, MA: Addison-Wesley.

(A third suggestion, logit scale, comes towards the end of this answer.)
Some moderately major and moderately minor points:

Being able to show zero does no harm and may seem a real bonus. At the same time pulling in the highest values and keeping the lowest values discernible are both needed.

Showing axis labels (tick labels) on the original scale is important. Few people want to be obliged to back-transform from either transformed scale.

Dot charts rather than bar charts are meant to undermine a mental habit of taking bar height or length literally, which would be fair enough with the usual convention.

Horizontal alignment is vital to ensure legible categorical labels. The toy example has 10 categories, and the implication is that there are several more in the real data.

When a graph has table flavour, I often put the horizontal axis at the top. This is personal preference, but note that table conventions of using headers for columns clash with graph conventions of horizontal axis and text (titles or labels or tick labels, whatever you call them) at the bottom.

More explanation could and perhaps should be added on the unusual scales.

You might or might not want to show the counts next to each dot.

The "dots" could be any point symbol you prefer.

One or at most a few categories of particular interest or concern could be distinguished by a different symbol or colour. (Different symbols or colours for each category would be a bad idea for this kind of plot, although made necessary by some other designs.)

There is no free lunch. With either scale, you'll need to explain more than usual. Some readers will decide immediately that the idea is so weird that they won't play. You might have trouble getting either idea past reviewers. Just use a table! is to me too an understandable view.
Square root scale

log(count + 1) scale

I ignored "in R" as contrary to the best ecumenical spirit of CV. If R is as good as people say, you should have no problem in emulating or improving on my Stata script (below for the record).
clear
input str8 Things Count
Cars 500
Trucks 250
Jeeps 17
Planes 2
Foot 1
Oranges 1
Plasters 1
Grapes 1
Tablets 1
Pillows 1
end

gen Toshow = sqrt(Count)
mylabels 500 200 100 50 20 10 5 1 0, myscale(sqrt(@)) local(yla)
graph dot (asis) Toshow, over(Things, sort(1) descending) linetype(line) lines(lc(gs8) lw(vthin)) ysc(alt) yla(`yla') name(G1, replace)

replace Toshow = log1p(Count)
mylabels 500 200 100 50 20 10 5 1 0, myscale(log1p(@)) local(yla)
graph dot (asis) Toshow, over(Things, sort(1) descending) linetype(line) lines(lc(gs8) lw(vthin)) ysc(alt) yla(`yla') name(G2, replace)

Yet another variation, logit scale: You know the total number of patients, say 1000. Then frequencies of genes that occur can be shown as logit (count / total). That scale makes it impossible to show genes that don't occur (which doesn't sound an issue) or genes that always occur (I guess not an issue).
As before, the scale shown on axis labels shouldn't be logit but could be count or probability.
Recalling that for probabilities $p$, $\text{logit}\ p = \ln\ [ p / (1 - p)] = \ln\ p - \ln\ (1 - p)$, note that

for very small $p$ near $0$, $\text{logit}\ p \approx \ln\ p$ because $\ln\ (1 - p) \approx \ln\ 1 = 0$

for very large $p$ near $1$,   $\text{logit}\ p \approx -\ln\ (1 - p)$ because $\ln
\ p \approx \ln\ 1 = 0$.

So the scale is logarithmic in different ways in each tail, which is either what you want or not a problem.
All these devices could be called ad hoc, which I translate positively as "fit for purpose".
Answer: After playing with this for a bit I think 'just use a table' might be the best approach, but I tried a few of R's methods for showing this kind of information so I'm including as an answer in case it's useful.
Here's the data in R (data.table package)
library(data.table)
dat <- fread(text="Cars 500
Trucks 250
Jeeps 17
Planes 2
Foot 1
Oranges 1
Plasters 1
Grapes 1
Tablets 1
Pillows 1", header=FALSE) |> setNames(c("Category", "Frequency"))

Edit:  you can add labels directly onto a waffle plot by extracting the locations of the plotted tiles.  So:
# create a waffle plot
library(waffle)
library(data.table)
w1 <- ggplot(dat[sample(nrow(dat)),], aes(fill=Category, values=Frequency)) +
  geom_waffle(n_rows=50, col=NA) +
  theme_void() +
  scale_fill_brewer(palette="Paired") +
  theme(legend.position = "none")

# extract the locations of the plotted tiles
d1 <- ggplot_build(w1)$data |> as.data.table()

# take the average position for each group
# (relies on each group having a different fill colour)
regiondata <- d1[, .(x=mean(x), y=mean(y)), by=fill]

# now draw the plot, and add the labels
w1 + geom_text(aes(
  label = Category,
  x = regiondata$x,
  y = regiondata$y,
  size = Frequency
)) +
  scale_size_binned()

You can play with the size scale or maybe with ggrepel to get better sizing and placement of the labels.
Be careful that the labels are plotted in the right order, this relies on the order in the ggplot data being the same as the order the waffle plot is built in.  So far this seems to be the case but it's worth checking.

First I tried the waffle and treemapify (as you did) R packages:
library(waffle)
ggplot(dat, aes(fill=Category, values=Frequency)) +
  geom_waffle(n_rows=50, col=NA) + theme_void()

ggplot(dat, aes(area = Frequency, fill = Category, label = Category)) +
  geom_treemap(layout="srow") +
  geom_treemap_text(layout="srow")+
  scale_fill_brewer(palette="Paired")

Neither of these works great when the distributions are so skewed, but they do convey the sense of area pretty well.  If you can figure out how to label the waffle plot without using a legend it might work well.
I looked at facet_zoom from ggforce but I don't think it works in this case.  So I tried to re-implement it as a pair of stacked bar charts with varying widths.  Again not sure if it works particularly to convey your message, but it's possible you could adapt it.
This works by duplicating the dataset, with one part only having the low frequencies, then plotting two stacked bars side by side with some annotation to indicate the zooming and variable widths to make the relative areas correct:
dat[, prop:=Frequency/sum(Frequency)]
datlong=rbindlist(list(full=dat,zoomed=dat[Frequency<100]), idcol="part")
datlong[, sum:=sum(Frequency), by=part]
datlong[, grandsum:=sum(Frequency)]

ggplot(datlong) + aes(x=part, y=Frequency, fill=reorder(Category, Frequency)) +
  geom_col(position="fill",width=width,col="black",aes(width=sum/grandsum)) +
  geom_text(aes(label=sprintf("%s (%d)",Category,Frequency)),
            position = position_fill(vjust=0.5),
            data=datlong[(part=="full" & Frequency>100)]) +
  geom_text(aes(label=sprintf("%s (%d)",Category,Frequency)),
            position = position_fill(vjust=0.5),hjust=-0.1,
            data=datlong[(part=="zoomed")]) +
  theme_minimal()+
  theme(legend.position = "none",
        axis.text = element_blank()) +
  annotate(x=1.5,xend=1.99,
           y=1-sum(datlong[part=="zoomed", prop]),
           yend=0, geom="segment", lty="dashed")+
  annotate(x=1.5,xend=2.0,
           y=1,yend=1, geom="segment", lty="dashed")+
  labs(x=NULL, y=NULL)

But I don't honestly think it's better than a table or a description in text would be.
Comment: (+1) I think the last plot works much better than the others. In general, a legend is at best a necessary evil if only because it obliges mental back and forth between legend and plot. In this case and often, it's important to wonder how any design will fare with several more categories. Getting about 30 colours that remain easily distinguishable is hard work for most people.
Comment: @NickCox I completely agree.  This is an interesting question so if I get time I might think about how to make the waffle plot with direct labelling.


How to hide set up database step in a installation profile?

Question: In a installation profile, how do I fill values for Set up database step programmatically and hide it so user doesn't need to fill the form?
How to do the above action for the Select language step?
Answer: You wanted an example -- which is basically showing you how to do it. From the docs I supplied and the help others that gave you cookie crumbs provided should have lead you towards a solution, Other than saying "show me" all the code.
A working profile example is in this GIST, you make a shortprofile directory in your /profiles directory and select "Short Profile" from the Installation screen. This is the "long way" to do this, there is a shorter way in-theory ... see my code comments.
Be sure to change the $databases['default']['default'] in line 47 of .profile to the existing database credentials that will work in your environment. Look for my comments in the code to change the db credentials and db password (line 125 of .profile).
Comment: for the Locale stuff I would do a custom `system_form_install_select_locale_form_alter()` in your .profile file and provide the default value you want.
Answer: Fair warning I haven' done this before (but I have made install profiles and used them via Drush Make). So I was interested in how you might try to do this ...
I found this documentation page, How To Write a Drupal 7 Installation Profile
I assume you are using the 'Miminal' or 'Standard' defaults in your profile to save you some headache, or else you'd know the answer to your own question in building a complete profile from scratch ... I think you need to do 2 things:
(1)
If you're using the minimal or standard defaults you can use hook_install_tasks_alter() to change the visibility of the database Step to hidden. If your defining your own install tasks via hook_install_tasks() in yourprofile.profile
(2)
You need to provide the database parameters. You can do that probably most straight-forwardly via hook_form_alter() as described in the documentation page linked above.  You may also be able to muck with the values in $install_state for hook_install_tasks as described in install_state_defaults()
I suggest you read up on all these hook functions and the documentation page above. good luck.
Comment: Thanks, I know about hooks you mentioned. I need more details on how to set database parameters.
Answer: For me the accepted answer didn't work. It would just fill the form with default values but the user would still need to click to "save configuration" button to go forward. This is not what I would call a "skip step" if the user still has to press a button.
But basing on the solution I could find something that worked for me. First alter the step in question in your_profile_install_tasks_alter
your_profile_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_settings_form']['display'] = FALSE;
  $tasks['install_settings_form']['function'] = 'your_profile_install_settings_defaults';
  $tasks['install_settings_form']['type'] = 'normal';
}

Setting the type to form gave me problems as I was trying to call drupal_form_submit (would complain function is undefined) and overcomplicating my life
Now just copy paste the code from the submit function from core:
function your_profile_install_settings_defaults(&$install_state) {

  $database = array(
    'database' => 'yourparams',
    'username' => 'yourparams',
    'password' => 'yourparams',
    'prefix' => '',
    'host' => 'localhost',
    'port' => '',
    'driver' => 'mysql'
  );

  // Update global settings array and save.
  $settings['databases'] = array(
    'value' => array('default' => array('default' => $database)),
    'required' => TRUE,
  );
  $settings['drupal_hash_salt'] = array(
    'value' => drupal_hash_base64(drupal_random_bytes(55)),
    'required' => TRUE,
  );
  drupal_rewrite_settings($settings);
  // Indicate that the settings file has been verified, and check the database
  // for the last completed task, now that we have a valid connection. This
  // last step is important since we want to trigger an error if the new
  // database already has Drupal installed.
  $install_state['settings_verified'] = TRUE;
  $install_state['completed_task'] = install_verify_completed_task();
  return NULL;
}

That worked for me.
Answer: Database credentials are set in settings.php. So you'd provide a settings.php with your distribution, or you'd write out the db array to the settings.php at some point during installation.
You could do this in an installation profile, with hook_install_tasks_alter(), by changing install_settings_form.
Same caveats as tenken... I haven't done this.
Comment: I have done this, and it works; Drupal will skip the database configuration page on install if the database settings are already configured in settings.php. I have not tried this on D7 (I mostly use `drush site-install` nowadays), but it should still work. One problem on D6 which may or may not be fixed on D7: if you navigate to http://mysite.org when it is NOT installed, then you will see many errors; you must go to http://mysite.org/install.php directly.
Comment: "You could do this in an installation profile, with hook_install_tasks_alter(), by changing install_settings_form." This is my question! how to do this with `hook_install_tasks_alter()`? Can you provide an example?
Comment: as @greg_1_anderson says using settings.php causes errors until user enters example.com/install.php
Comment: Right. That's how you install Drupal. :-)


Autofac load dependencies from referenced and non referenced assemblies

Question: I have seen many question that ask how to load all referenced assemblies even if not directly used, but I would like to take that a step further.  I am building a service and interface that can be extended, the intention is that I could extend the Sender/Receiver with additional types, for example: the interface is responsible for sending SMS messages and can have different adapters, say I have two different applications that want to use SMS, each would have its own implementation of an ISmsAdapter and ISmsReplyAdapter, the assemblies may not necessarily be referenced by the Service (the application comprises of a Windows Service and a WebAPI service to receive replies).
What I would like to be able to do is not just register my autofac modules that are in referenced assemblies, but also register modules in assemblies that are in say a specific folder such as /bin/plugins or something similar
I have not been able to find anything that relates to this other than Caliburn.Micro which has a DirectoryCatalog which does something similar to what I want
Does anyone know how I might be able to achieve this with Autofac please?
Answer: This isn't really an Autofac question so much as a reflection question. Autofac doesn't care how you load assemblies.
Load your assemblies through reflection using something like Assembly.LoadFrom and then use the assembly scanning in Autofac or continue using reflection to manually locate certain types in the assemblies (eg types that inherit from module, types with a certain naming convention, types that implement a certain interface, etc.) and register the types individually in a for-loop.


Should the hostname of my VPS point to the dedi IP of my Domain or to to a shared one used for new account creation?

Question: I leased a VPS which I want to use to sell shared hosting. 3 IPs - I call them A, B and C here for simplicity.
Actual setup is:
A=NS1.mydomain.com; host.mydomain.com and is used to set-up new accounts in shared environment
B=NS2.mydomain.com
C=dedicated IP for mydomain.com (SSL secured)
The more I read about DNS, the more I get confused; thus my question:
Is this configuration "Good Practice", especially the hostname pointing to A rather than to C?
And what would be a better alternative?
Answer: I asked a support specialist and got the following answer, which I would like to share:

The hostname should be always pointed to the main server IP
  address.
The main server IP address in the
  server is "A". You can verify it via
  WHM >> Main >> Server Configuration >>
  Basic cPanel & WHM Setup.
The domain "mydomain.com" has SSL
  installed in it. For installing the
  SSL certificate you need to have a
  dedicated IP Address. Hence it is
  pointed to the IP address "C".
It is not necessary that the
  main domain is pointed to the main
  server IP address.

Thus my above mentioned setup is logic and complies with 'Good Practice'


(Polynomial approximation) Why does the nth derivative of both the function and the polynomial has to be equal at center?

Question: I've watched many videos about Taylor/Maclaurin polynomial but no tutor ever explained why it has to be f(n)(c) = p(n)(c) at center x = c.
I've seen the behavior of the graph of p(x) and f(x) when they are approximating and how each higher degree polynomial approximate the function more accurate around the center. My confusion is at the part "around the center", since the higher derivatives of both functions only match at the center:
1/ How does that make the vicinity of both functions match, since the derivatives of the f(x)'s and the p(x)'s around the center doesn't equal (only the derivative of the center is equal)?
2/ How does the approximation get better and better once the "n" of f(n)(c) = p(n)(c) start increasing? Like, how does f(2)(c) = p(2)(c) provide better approximation than f(1)(c) = p(1)(c), and how does f(3)(c) = p(3)(c) does an even better job? And it keeps going... The Youtube tutors I've watched only tell: "Higher derivatives of both functions match will give better approximation" but never explain how that is the case.
Thank you all. Any help is greatly appreciated!
Answer: The rough idea is that if two functions have the same $n$ first derivatives at $a$, then their difference is of the order $(x-a)^{n+1}$. Do you see why, for $x$ close to $a$, a $(x-a)^2$ is much smaller than a $(x-a)$ ?
The rigorous foundation for that is Taylor's theorem.
But you can see already that for polynomials. If two polynomials $f$ and $g$ have the same $n$ first derivatives at $a$, it means that $a$ is a root of order $n+1$ of the difference polynomial $f-g$. Hence $f-g = (x-a)^{n+1}$ times something.
Try it with $-x^3 + 6 x^2 - 8 x + 3$ and $x^3 - 2 x + 1$, for $a=1$. First show that they have the same derivatives up to the second, and then show that their difference can be factored out by $(x-1)^3$.
So essentially what Taylor's theorem tells you is that nice functions (which are $n$ times differentiable) obey the same principles as polynomials.
I agree that it's initially wierd to see the equality condition being only at the center $a$. But the derivative itself is something that sums up what happens in smalls neighborhoods of $a$ if the first derivative agrees at $a$, it means that the function has to nearly agree near $a$.
Comment: $(x-a)^2$ being much smaller than $(x-a)$ when $x$ is close to $a$ is simply because the square of something really small is "twice as small". As in $0.001^2 = 0.000001$.
Comment: The concept that the derivative $f'(a)$ tells you about the local behavior of the function near $a$ *is exactly Taylor's theorem*. But already from the definition of the derivative, you can see that *to define $f'(a)$ you need to look at $f$ on neighborhoods of $a$*.
Comment: Thank you so much for your help! Sorry for my late respond. I understand that f and p has error to be polynomial of the order (x−a)^(n+1). But can you please explain the part "Do you see why, for x close to a, a(x−a)^2 is much smaller than a(x−a)"?
Comment: Also, at this part - "But the derivative itself is something that sums up what happens in smalls neighborhoods of a if the first derivative agrees at a, it means that the function has to nearly agree near a." - Can you please give me the name of the concept that explains this part? Thank you!
Comment: Thank you! Really appreciate your help.


Isolated singular point- complex function

Question: I know that if a function $f$ fails to be analytic at $z_0$ but is analytic at some point in every neighborhood of $z_0$, then $z_0$ is a singular point.
But what is an isolated singular point?
Here is the definition from my book: A singular point $z_0$ is said to be isolated if, in addition [to being singular], there is a deleted neighborhood $0<|z-z_0|<\epsilon$ of $z_0$ throughout which $f$ is analytic.
I don't fully understand what a deleted neighborhood means.
Any clarification is appreciated.
Thanks.
Comment: right  ,because    it omits itself
Comment: @dato Thank you, that was very helpful!
Comment: http://mathworld.wolfram.com/IsolatedSingularity.html
Comment: http://www.mathwords.com/d/deleted_nbhd.htm
Comment: please see second link,there is given  definition of  deleted neighorhood
Comment: @dato Oh okay, so it's basically a neighborhood of $z_0$ without $z_0$, right?
Comment: so i am happy @Alti  if i helped you.good lucks.you are welcome to this great  mathematical website
Answer: Deleted Neighborhood
The proper name for a set such as ${x: 0 < |x – a| < δ}$. Deleted neighborhoods are encountered in the study of limits. It is the set of all numbers less than δ units away from a, omitting the number a itself.
Using interval notation the set ${x: 0 < |x – a| < δ} $ would be $(a – δ, a) ∪ (a, a + δ).$ In general, a deleted neighborhood of $a$ is any set $(c, a) ∪ (a, d)$ where $c < a < d.$
For example, one deleted neighborhood of $2$ is the set ${x: 0 < |x – 2| < 0.1}$, which is the same as $(1.9, 2) ∪ (2, 2.1).$


How to protect a website with HTTPS using a digitalocean certificate?

Question: I have deployed a website on a Digital Ocean droplet that listens on port 80, i.e. vanilla HTTP. I would like to protect the website using HTTPS, and it seemed like this would be a simple process using DO's Let's Encrypt integration under the Security -> Certificates section. It was as simple as...

Click on "Add Certificate"
Select the domain name of my website... testingtestingmiccheck123.com
Click on "Generate Certificate"

However, after doing this simple process, my website is still being served over simple HTTP. Am I doing something wrong here? Is this not actually what this feature of DO was intended to be used for?
Comment: I believe just adding new certificate in general won't make your web app/site listen and respond over HTTPS - additional DNS configuration may be required (to make HTTPS default) as well as configuration of your web server to respond over HTTPS - I think you need more details on whether you did anything on this side. Also I assume you aware that feature you described works only when your DNS name managed by DO.
Answer: These are functions for higher level DO services (e.g. load balancers), not meant to add a cert to a single droplet.
Since a droplet is just a Linux VM (or whatever OS you chose), you add a cert in the usual way, e.g. by installing certbot in the VM and running it.


Using define_method and meta-programming to define instance methods dynamically in Ruby?

Question: I have some code something like :
class Country
  attr_reader :name

  def initialize
    @name     = "MyName".freeze
  end

  def government
    @government ||= Government.new(self)
  end

  def symbols
    @symbols ||= Symbols.new(self)
  end

  def economy
    @economy ||= Economy.new(self)
  end

  def education
    @education ||= Education.new(self)
  end

  def healthcare
    @healthcare ||= Healthcare.new(self)
  end

  def holidays
    @holidays ||= Holidays.new(self)
  end

  def religion
    @religion ||= Religion.new(self)
  end

end

How can I create the methods dynamically? I tried :
class Country
  attr_reader :name

  COMPONENETS = %w(government symbols economy education healthcare holidays religion)

  COMPONENETS.each do |m|
    define_method(m) do |argument|
      instance_variable_set("@#{m}",Object.const_get(m.capitalize).new(self))
    end
  end

  def initialize
    @name     = "MyName".freeze
  end

end

If I try:
puts Country.new.education.inspect
I get the following error:
country.rb:16:in `block (2 levels) in <class:Country>': wrong number of arguments (0 for 1) (ArgumentError)
    from country.rb:27:in `'

What am I missing here?
Comment: Why would you think that you are missing something? Is there an error message? If yes, what is it? Is the output not what you are expecting? If yes, what is the output, and what is the output you are expecting? Is the behavior not what you are expecting? If yes, what is the behavior, and what is the behavior you are expecting? Is nothing happening? Is something happening that shouldn't happen? Is something not happening that should happen? Please provide a minimal, self-contained test-case, the inputs and expected outputs and behaviors of said test-case, and any and all errors and warnings.
Comment: I think I'm missing something cuz I'm not getting the expected behaviour. Aw I just updated the error I'm getting. Any clue?
Comment: seems the `self` here related to `Country` class and not the instance of Country. How should I fix this?
Answer: In your original code, you defined all the methods to take no arguments:
def education
#            ^^^
  @education ||= Education.new(self)
end

In the metaprogrammed code, you define all the methods to take a single argument called argument:
define_method(m) do |argument|
#                   ^^^^^^^^^^
  instance_variable_set("@#{m}", Object.const_get(m.capitalize).new(self))
end

However, you call it with zero arguments:
puts Country.new.education.inspect
#                        ^^^

Obviously, your methods are meant to be lazy getters, so they should take no arguments:
define_method(m) do
  instance_variable_set("@#{m}", Object.const_get(m.capitalize).new(self))
end

Note that there are other problems with your code. In your original code, you use a conditional assignment to only perform the assignment if the instance variable is undefined, nil or false, whereas in the metaprogrammed code, you are always unconditionally setting it. It should be something more like this:
define_method(m) do
  if instance_variable_defined?(:"@#{m}")
    instance_variable_get(:"@#{m}")
  else
    instance_variable_set(:"@#{m}", const_get(m.capitalize).new(self))
  end
end

Note: I also removed the Object. from the call to const_get to look up the constant using the normal constant lookup rules (i.e. first lexically outwards then upwards in the inheritance hierarchy), since this corresponds to how you look up the constants in the original code snippet.
This is not fully equivalent to your code, since it sets the instance variable only when it is undefined and not also when it is false or nil, but I guess that is closer to your intentions anyway.
I would encapsulate this code to make its intentions clearer:
class Module
  def lazy_attr_reader(name, default=(no_default = true), &block)
    define_method(name) do
      if instance_variable_defined?(:"@#{name}")
        instance_variable_get(:"@#{name}")
      else
        instance_variable_set(:"@#{name}",
          if no_default then block.(name) else default end)
      end
    end
  end
end

class Country
  attr_reader :name

  COMPONENTS = %w(government symbols economy education healthcare holidays religion)

  COMPONENTS.each do |m|
    lazy_attr_reader(m) do |name|
      const_get(name.capitalize).new(self))
    end
  end

  def initialize
    @name = 'MyName'.freeze
  end
end

That way, someone reading your Country class won't go "Huh, so there is this loop which defines methods which sometimes get and sometimes set instance variables", but instead think "Ah, this is a loop which creates lazy getters!"
Answer: You can simply use eval :
class Country
  attr_reader :name

  COMPONENETS = %w(government symbols economy education healthcare holidays religion)

  COMPONENETS.each do |m|
   eval <<-DEFINE_METHOD
   def #{m}
     @#{m} ||= #{m.capitalize}.new(self)
   end
DEFINE_METHOD
  end

  def initialize
    @name = "MyName".freeze
  end
end

Comment: Wow, Awesome. Thanks @Jean Bob
Answer: I guess you don't need the argument:
class Country
  attr_reader :name

  COMPONENETS = %w(government symbols economy education healthcare holidays religion)

  COMPONENETS.each do |m|
    define_method(m) do
      instance_variable_set("@#{m}",Object.const_get(m.capitalize).new(self))
    end
  end

  def initialize
    @name     = "MyName".freeze
  end

end


What is the geometrical representation of |z-a|-|z+a|=2c?

Question: I stumbled across the following question-
What is the geometrical representation of $|z-a|-|z+a|=2c $ where $c$ is a Real number for the following cases - $(I)$ $c>|a|$ and $(II)$ $c=a$.
I tried to put $z=x+iy$ and try to square and expand ,but it didn't work out. Can anyone elegantly find out the geometrical representation for the above 2 cases ?
Comment: You can read it out of the equation. $|z-a|$ and $|z+a|$ are the distances from $z$ to the fixed points $a,-a$. The points $z$ satisfying the equation are those for which the difference between their distances to two fixed points is a constant $2c$. That's a [hyperbola](https://en.wikipedia.org/wiki/Hyperbola#As_locus_of_points) with foci at $a,-a$.
Comment: @NDB more precisely, it's one branch of hyperbola since left hand side changes signs depending on whether we are closer to $a$ or $-a$.
Comment: These comments should be an answer.
Comment: Raghav, if you write in your post more context, your efforts and attempts, I will help you.
Answer: Hint:
Put Just not only $$z=x+ iy$$ and also $$a=a_1 +ia_2$$
Answer: HINT: For two fixed point $F$ and $F'$, the locus of point $P$ described by the equation $PF-PF'=constant$ is a hyperbola. In complex plane, $|z_1-z_2|$ represents the distance between points $z_1$ and $z_2$ so $|z-1|$ and $|z-(-1)|$ are essentially $PF$and $PF'$.The use of inequalities like $<$ and $>$ describe the regions containing or excluding the origin .