Using Derivatives to Approximate Changes in a Function

Question: We know that $\Delta{f(x)}\approx f^\prime(x)\Delta{x}$. I'm looking to formalise this argument (it may have been formalised already, but here's my approach). Firstly, say we want to find $f(b)-f(a)$. Using the approximation stated earlier, $f(b)-f(a)\approx f^\prime(\frac{a+b}{2})(b-a)$. Note that I'm evaluating the derivative at the arithmetic mean of $a$ and $b$. I find that this works well for a few simple functions. Perhaps, evaluating it at the geometric or harmonic mean may be better in some situations. Anyway, to formalise this argument I thought of proving that $\lim_{b \to\ a} \frac{f^\prime(\frac{a+b}{2})(b-a)}{f(b)-f(a)}=1$. My reasoning is that as $b$ tends to $a$, $\frac{\Delta{f(x)}}{\Delta{x}}$ tends to $\frac{df(x)}{dx}$, and the approximation tends to the actual value of the change in the function. Is there any flaw in my reasoning? Can this formalisation somehow be improved? Also, how to prove the limit stated above? Any help will be appreciated.
Comment: Your reasoning cannot be mathematically rigorous if you use the symbol " $\approx$ ". Also you say you want to formalise your approximation but you are using it to proove it... It's logically wrong. If you are looking for a proper theorem, what you are looking for is called the Taylor's theorem (first order).
Comment: The whole point of introducing limits was to remove that symbol. Also, I'm looking to prove that the limit evaluates to 1 only if my reasoning is true, which it may or may not be. Thanks for the reference to Taylor's Theorem, though.
Answer: Well, the definition (or an equivalent way of writing the definition) of differentiability of $f$ at $x$ is that $\Delta f(x;h):=f(x+h)-f(x)=f'(x)h+ R(x;h)$, where $R(x;h)=f(x+h)-f(x)-f'(x)h$ is the remainder term, and is small in the sense that $\lim\limits_{h\to 0}\frac{R(x;h)}{h}=0$. This is the formal way of saying things. In words, we're saying that the actual change in the function $f$ at the point $x$, when displaced by an amount $h$, is equal to a linear term $f'(x)h$, plus some excess remainder, whereby the remainder is 'small' in the sense described above. People often call this a "first order Taylor expansion", but really it's just the definition of the derivative.
Your approach of using the arithmetic mean and dividing requires some extra assumptions, which are stronger than merely assuming differentiability at a single point $x$. For the purposes, you may find this convenient (I don't), but you should think more closely about the definition I wrote above. Differential calculus is essentially the subject of linear approximations, so internalizing the above idea will take you very far.

Edit:
In response to the comment, your limit is true but under stronger hypotheses:

If $f:\Bbb{R}\to\Bbb{R}$ is continuously differentiable and $a\in\Bbb{R}$ is a point such that $f'(a)\neq 0$, then for all $b$ in a punctured nighborhood of $a$, we have $f(b)-f(a)\neq 0$, and $\lim\limits_{b\to a}\frac{f'\left(\frac{a+b}{2}\right)(b-a)}{f(b)-f(a)}=1$.

Note the stronger assumptions. We are assuming here that $f$ is not only differentiable in an interval around $a$, but also that the derivative is continuous there. To prove this, note that first of all $f'(a)\neq 0$, and continuity of $f'$ at $a$ implies that $f'$ maintains a constant sign near $a$ (i.e $f'$ is positive near $a$, or $f'$ is negative near $a$). So, $f$ is strictly monotone near $a$, and thus $f(b)-f(a)\neq 0$.
This paragraph above doesn't get to the heart of the theorem, but it is an important first step to ensure that the fraction we're talking about in the limit actually makes sense (we must avoid division by $0$ at all costs). Now, here's what we can write: if $b$ is in a small punctured neighborhood of $a$, then
\begin{align}
\frac{f'\left(\frac{a+b}{2}\right)(b-a)}{f(b)-f(a)}&=
\frac{f'\left(\frac{a+b}{2}\right)}{\frac{f(b)-f(a)}{b-a}}
\end{align}
Now in the numerator, we have $\frac{a+b}{2}\to a$ as $b\to a$, and so by continuity of $f'$, we have $f'\left(\frac{a+b}{2}\right)\to f'(a)$. The denominator approaches $f'(a)$, as $b\to a$, by definition of the derivative. Thus, the quotient approaches $\frac{f'(a)}{f'(a)}=1$ (I'm using the theorem that limit of quotients equals quotient of limits, provided all the limits exist and the limit of denominator is non-zero).
Comment: Thanks for the answer. I am only interested in the $f^\prime(x)h$ part, and not the remainder part, as I feel that investigating functions using their approximations could be interesting. Do you know if the assertion about the limit I made is true? If so, how do I go about proving it?
Comment: @Heisenberg I've provided a precise statement and proof.
Comment: That's simply perfect. It's just what I wanted. Now that I know how to evaluate the limit I'm annoyed that I didn't figure it out myself. Anyway, thanks for the answer.
Answer: This $$\lim_{b \to\ a} \frac{f^\prime(\frac{a+b}{2})(b-a)}{f(b)-f(a)}=1$$ could be false without the hypothesis of $f'$ being continuous.
If you add that hypothesis, then proving it is almost trivial (may be you could try it).
Comment: @Heisenberg You're assuming **more** than just continuity when you speak about $f'$. You're implicitly assuming differentiability (which is stronger than continuity), otherwise it makes no sense to talk about $f'$. But in my answer I talk about the even stronger hypothesis: the continuity **of the derivative**
Comment: I am assuming that $f$ is continuous, and that $\frac{a+b}{2},a,$and $b$ are all in the function's domain. I did try proving it, but I didn't get too far. In fact, I asked a friend of mine if he could help me with it, and he couldn't figure it out either. This is what led me to believe that there's some sort of flaw in my reasoning.
Comment: Oh yeah, I didn't see the $\prime$. Thanks for your input.


Given Y Bin ~ (10,0.4) and Z Geo ~ (0.3) find P(Y+Z=2)

Question: Given Y Bin ~ (10,0.4) and Z Geo ~ (0.3) find P(Y+Z=2)
Why is the solution to this P(Y=0)P(Z=2)+P(Y=1)P(Z=1)?
Why doesn't P(Y=2)P(Z=0) need to be included in this solution?
Comment: You missed saying $Y$ and $Z$ are independently distributed.
Answer: This depends on how one parametrizes the geometric distribution.  There is, for example, the parametrization
$$\Pr[Z = z] = p(1-p)^z, \quad z = 0, 1, 2, \ldots,$$
which counts the number of failures before the first success, and
$$\Pr[Z = z] = p(1-p)^{z-1}, \quad z = 1, 2, 3, \ldots,$$
which counts the number of trials to observe the first success.  Depending on which parametrization is intended, the answer to the question varies.
Comment: We are using Pr[Z=z]=p(1−p)z−1,z=1,2,3,…,
Answer: For both the Bin dist and the Geo dist, we have that the values of $x$ must be $\geq 0$.
This is why you must consider all the cases.
If we have $P(Y+Z=2)$, then you must consider the following cases:
$(Y,Z)=(0,2),(1,1),(2,0)$
However, the Geo dist is concerned with the number of failures before the first success. Consider a coin being tossed 5 times with success being the event of a head. It does not make sense to find the probability of the number of tails being $0$. This is why we tend to ignore the case where $Y=0$.
In any case, if you can justify, you should get the points. It really comes down to how you interpret the distribution.


Solution for a double differential pde

Question: Question: $\frac{\partial^2z}{\partial x^2}=a^2z\,$ given that when $x=0, \frac{\partial z}{\partial x}=asinx\;\text{and}\;\frac{\partial z}{\partial y}=a$
To solve this I assumed $z=Ae^{ax}+Be^{-ax}$ where A and B are constants or functions of y.
Assuming this, I get $$\frac{\partial z}{\partial x}=aAe^{ax}-aBe^{-ax}\qquad(1)$$ $$\frac{\partial z}{\partial y}=A'e^{ax}+B'e^{-ax}\qquad(2)$$
Inserting $x=0\,$ here gives $$\text{From eq (1)}\rightarrow A=B$$ $$\text{From eq (2)}\rightarrow A'+B'=a$$
Solving for A and B gives, $A=B=\frac{ay}{2}+c$, thus $$z=\left(\frac{ay}{2}+c\right)(e^{ax}+e^{-ax})$$
The procedure I used seems correct to me but since the question gave $\frac{\partial z}{\partial x}=asinx$, am I supposed to find the solution in terms of trigonometric functions only. Moreover, is directly assuming z to be a particular type of function a valid step.
Also, please tell the formula of sine or cosine in terms of e. Say can Euler's formula be used only for complex powers or is it applicable for real powers as well
Answer: $$\frac{\partial^2z}{\partial x^2}=a^2z\,$$
You don't "assume" that the solution is $z=Ae^{ax}+Be^{-ax}$ insofar you first prove that $e^{ax}$ and $e^{-ax}$ are particular solutions. The general solution is the linear combination of two independent solutions. So, this is not an assumption this is a factual result.
Your calculus is correct, leading to
$$z=\left(\frac{ay}{2}+c\right)(e^{ax}+e^{-ax}) ,$$
which satisfies both boundary conditions specified as : When $x=0, \frac{\partial z}{\partial x}=a\sin(x)\;\text{and}\;\frac{\partial z}{\partial y}=a$
Note that the first condition (at $x=0$ ) is :
$$\frac{\partial z}{\partial x}=0\quad\text{because}\quad\sin(x)=0$$
There is no sinusoidal function in the condition. So, you are not supposed to find the solution in terms of trigonometric functions only.
Nevertheless this manner to specify the condition appears strange. Are you sure that there is no typo in the wording ?
Comment: That boundary condition was bugging me when solving the peoblem. The thing is this question is not from a book but rather an exercise problem I took from some Handwritten notes, so it could be that it was intentionally done as an exam practice of some sort
Comment: I bet that the condition at $x=0$ is not $\frac{\partial z}{\partial x}=a\sin(x)$ but is $$\frac{\partial z}{\partial x}=a\sin(y).$$ If so, the result is : $$z(x,y)=\frac12\sin(y)\left(e^{ax}-e^{-ax}\right)+c\,\left(e^{ax}+e^{-ax}\right)$$

Solution for a double differential pde


Estimating expected lifetime from hazard ratio and estimated base hazard function

Question: Apologies if this is a basic question, I am not very familiar with survival analysis ...
I have trained a gradient boosted Cox proportional hazards model in R, and have been able to obtain reasonable hazard function estimates from through the gbm package's basehaz.gbm function.
My goal though is to obtain expected lifetimes.  How does one go about obtaining these estimates given an estimated base hazard function and hazard ratios?  Would it be best to find a parametric fit to the hazard function (or survival function)?  Is this usually handled by a discrete approximation using the estimated survival function (and how would one account for the part of the curve unable to be estimated past a certain time due to sparsity of data)?
I've tried both approaches but have not gotten good results, and the standard parametric survival functions don't seem to fit my estimated curve particularly well.
Answer: The estimation of life-expectancy in the presence of censored data necessarily requires assumptions on the unobserved part of the survival function.
A parametric distribution can be used for extrapolation of observed and expected survival, but it is not easy to capture the shape of the unobserved survival function. A possible approach is to use relative survival (see for instance: Andersson et al. 2012)
If you wish to avoid data extrapolation, this can be done by evaluating survival percentiles. With a sufficient number of cases you can estimate the median survival, while with a proportion of cases below 50% lower percentiles can be estimated.
Survival percentiles can be calculated from the Kaplan-Meier estimator, which summarizes the observed survival. If you are interested in adjusted survival percentiles you may take a look at Laplace regression (see for instance Orsini et al. 2012).
Answer: As you surmised, if you have censored data, it's impossible to calculate the expected lifetime without imposing additional assumptions on the unobserved failure times. One popular option is to assume an exponential drop-off after the last non-censored data point -- but again, that's just an assumption. It doesn't come from the model, or the data.
For survival models, it's usually better to think in terms of median lifetime, because there's actually a meaningful answer to that contained in the estimated survival function.
A great technical resource for these kinds of questions is Klein & Moeschberger's "Survival Analysis": http://www.amazon.com/Survival-Analysis-Techniques-Truncated-Statistics/dp/038795399X
Answer: You may want to check out the work of Haybittle/Pollard who give a good formula for estimating using the Gompertz function:
Life Expectancy at age x = 1/k * ln((1+k/h(x)) - 1/2 (1+ h(x)/k)^-2)
k = 0.09 for most modern populations and h(x) is the hazard function in the general population.  If you want to see the expectancy in a different group (e.g. smokers), multiply the  h(x) by your hazard ratio for that group (e.g., hazard ratio for smokers).
Haybittle JL. The use of the Gompertz function to relate changes in life expectancy to the standardized mortality ratio. Int J Epidemiol. 1998 Oct;27(5):885-9. doi: 10.1093/ije/27.5.885. PMID: 9839748.
Pollard JH. Fun with Gompertz. Genus. 1991 Jan-Jun;47(1-2):1-20. PMID: 12284816.


Ler JSON e mostrar no html usando o angularJS

Question: Estou tentando ler os dados de um arquivo Json no html usando AngularJS, porém não estou conseguindo.
Segue parte do código da index.html:

                            <button id="btf1" ng-repeat="menus in mock(0,4)" class="btf" style="width:416px; height: 79px; background-color:#2E5491">{{response.id}}</button>

                            <button id="btf5" ng-repeat="menus in mock(4,8)" class="btf" style="width:416px; height: 79px; background-color:#2E5491">{{response.id}}</button>

Segue código do JSON:
{
    "alexa": {
        "#text": "",
        "item": {
            "@attributes": {
                "name": "MenuPrincipal",
                "label": "Menu Principal"
            },
            "#text": "",
            "children": {
                "#text": "",
                "child": [{
                        "@attributes": {
                            "id": "mnu1"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu2"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu3"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu4"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu5"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu6"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu7"
                        }
                    },
                    {
                        "@attributes": {
                            "id": "mnu8"
                        }
                    }
                ]
            }
        }
    }
}

Por fim segue o código da minha controller.JS:
var app = angular.module('app', []);
app.controller('HomeCtrl', function($scope, $http) {

    $http.get('mock.json').then(function(response) {
        $scope.data = response.data;
    });
});

Já li algumas perguntas porém ainda não consegui encontrar uma solução para o caso, e na documentação não consegui uma solução satisfatória nenhum exemplo para um iniciante como eu resolver.
Answer: Usa assim no Angular:
$http.get('mock.json').then(function(response) {
  $scope.data = response.data.alexa.item.children.child;
});

e depois no template:

                        <button id="btf1" ng-repeat="menu in data.slice(0,4)" class="btf" style="width:416px; height: 79px; background-color:#2E5491">{{menu['@attributes'].id}}</button>

                        <button id="btf5" ng-repeat="menu in data.slice(4,8)" class="btf" style="width:416px; height: 79px; background-color:#2E5491">{{menu['@attributes'].id}}</button>

Exemplo: http://jsfiddle.net/Sergio_fiddle/x2nbcmu2/
Comment: Valeu sergio, funcionou perfeitamente, muito obrigado.
Comment: @WesleyBrito ótimo! Eu não uso muito Angular mas a sintaxe é parecida com outras bibliotecas e deu para ajudar :)
Answer: Pelo que eu entendi deve ser isto:
var info = null;
$http.get('algumacoisa.json').success(function(data) {
    info = data;
});

Comment: Olá Pedro, podes explicar melhor a tua resposta e de que maneira isso resolve o problema na pergunta?
Comment: isso não resolveu, acabei de testar...


Symfony Audio Stream with Gaufrette

Question: I am using KnpGaufretteBundle to store audio files. I am able to download a given file to the client like this:
<code>    $filename = "Somefilename.mp3";

    $fs = $this->filesystemMap->get('media_fs');
    $file = $fs->read($filename);

    if($file){
        //Create And Return Response
        $response = new Response();

        $disp = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            $variant->getFileName()
        );

        $response->headers->set('Content-Length', $fs->size($filename));
        $response->headers->set('Accept-Ranges', 'bytes');
        $response->headers->set('Content-Transfer-Encoding', 'binary');
        $response->headers->set('Content-Type', 'application/octet-stream');
        $response->headers->set('Content-Disposition', $disp);
        $response->setContent($file);

        return $response;
    }
</code>
But now I also want to stream the file to the client, instead of using the attachment content disposition. Basically I want to access it clientside as if I was pointing at an actual mp3 sitting on my server. Does anyone know how this can be done?
Answer: I solved this by using the streamwrapper... it was this easy.
<code>$filepath = 'gaufrette://myFileSystemName/'.$filename;

$response = new \Symfony\Component\HttpFoundation\BinaryFileResponse($filepath);
</code>

Symfony Audio Stream with Gaufrette


Derivative of matrix exponential $\exp(A+xB)$ at $x=0$

Question: Consider two (Hermitian) matrices $A$ and $B$. Is there a nice expression for  the following?
$$ \boxed{ \frac{\mathrm d}{\mathrm d x}  \exp\left( A + x B \right)\big|_{x=0} = \; ? }$$
Of course, if $A$ and $B$ commute, this is simply $B \exp{(A)}$.
One thing I tried was the Suzuki-Trotter formula:
\begin{align}
\boxed{\frac{\mathrm d}{\mathrm d x}  \exp\left( A + x B \right)\big|_{x=0}}
&= \frac{\mathrm d}{\mathrm d x} \left. \left( \lim_{N \to \infty} \left[ \exp\left( \frac{A}{N} \right) \exp \left( x \frac{B}{N} \right) \right]^N \right) \right|_{x=0} \\
&= \lim_{N\to \infty}  \sum_{n=1}^N \exp\left( \frac{n}{N} A \right) \frac{B}{N}  \exp\left( \frac{N-n}{N} A \right) \\
&= \left( \lim_{N \to \infty} \frac{1}{N} \sum_{n=1}^N e^{\frac{n}{N}A }B\; e^{-\frac{n}{N}A } \right)  e^A \\\
&= \boxed{ \int_0^1 e^{t A} B \;e^{(1-t)A} \; \mathrm d t } \; .
\end{align}
Is this as close as it gets to a closed form?
One thing we can do is go to the eigenbasis of $A$, such that we can explicitly perform the integration over $t$. If we index the eigenvectors of $A$ by $i$, with corresponding eigenvalues $\lambda_i$, then we can express the answer in this basis:
\begin{equation}
\boxed{ \left( \frac{\mathrm d}{\mathrm d x}  \exp\left( A + x B \right)\big|_{x=0} \right)_{ij} = \frac{e^{\lambda_i}-e^{\lambda_j}}{\lambda_i-\lambda_j} B_{ij}} \;,
\end{equation}
where $(\cdot)_{ij}$ are the entries of a matrix in the eigenbasis of $A$. (Note that if $\lambda_i = \lambda_j$, we replace $\frac{e^{\lambda_i}-e^{\lambda_j}}{\lambda_i-\lambda_j} \to e^{\lambda_i}$, which is also consistent with l'Hopital's rule.)
Comment: While I don't currently have anything to show for it, I've been playing around with using the fact that $\frac{d}{dx}(A+xB)^n=\sum_{i+j=n-1}A^iBA^j$.  I feel like there is something useful lurking there, if only one can free it.
Comment: In general, $\frac{d}{dt}\big|_{t=0}f(A+tB)=\tilde f(L_A,R_A)B$, where $\tilde f(\lambda,\mu)=\frac{f(\lambda)-f(\mu)}{\lambda-\mu}$ for $\lambda\neq \mu$ and $\tilde f(\lambda,\lambda)=f'(\lambda)$. So the question of an "explicit representation" boils down to finding representations of $\tilde f$ in the form $\tilde f(\lambda,\mu)=\sum_k \phi_k(\lambda)\psi_k(\mu)$, where the sum may be infinite (or even an integral).
Comment: In this special case, I don't think you will get anything substantieller nicer than $\frac{e^{\lambda}-e^{\mu}}{\lambda-\mu}=\int_0^1 e^{t\lambda}e^{(1-t)\mu}\,dt$, which yields the formula from the OP.
Comment: One more remark: The matrix $\tilde f(L_A,R_A)B$ is exactly the Hadamard product (entrywise product) of $B$ and the matrix with entries $\tilde f(\lambda_i,\lambda_j)$, where $\lambda_i$ are the eigenvalues of $A$, counted with multiplicity.
Comment: The last expression that you derived is basically the [Daleckii-Krein](http://eprints.maths.manchester.ac.uk/2466/1/gendk.pdf) theorem.
Answer: Given the $\lambda$-parameterized matrix definitions
$$\eqalign{
C &= C(\lambda) &= A+\lambda B \\
E &= E(\lambda) &= \exp(C) \\
E'&= E'(\lambda)&= \frac{dE}{d\lambda} \\
}$$
an effective method to calculate the value of $\,E'(0)$ is the block-triangular method:
$$\eqalign{
&F = \exp\Bigg(\begin{bmatrix}A&B\\0&A\end{bmatrix}\Bigg)
   =  \begin{bmatrix}C(0)&E'(0) \\0&C(0)\end{bmatrix} \\
&E'(0) = \big[\matrix{I&0}\big]\,F \left[\matrix{0\\I}\right] \\
}$$
This method is quite general and works for any function, not just the exponential.
Answer: Not an answer, but here is an alternative, algebraic, elementary approach to the final formula you have.  It rests on the observation that if $T:V\to W$ is a linear transformation, $(v_{\alpha})$ a basis for $V$, $(w_{\beta})$ a basis for $W$, and $(w^*_{\gamma})$ the corresponding dual basis, then if $[T]$ is the matrix of $T$ with respect to our bases, $[T]_{ij}=w_i^*Tv_j$.
By using the product rule for matrices that $\frac{d}{dx}(M(x)N(x))=M'(x)N(x)+M(x)N'(x)$ and induction, we get the formula
$$\frac{d}{dx}(M(x)^n)=\sum_{\substack{0\leq i,j \\i+j=n-1}}M(x)^iM'(x)M(x)^j.$$
Therefore
$$\left.\frac{d}{dx}(A+Bx)^n\right\rvert_{x=0}=\sum_{i+j=n-1}A^iBA^j,$$
and so
$$C:=\left.\frac{d}{dx}e^{A+Bx}\right\rvert_{x=0}=\sum_n\sum_{i+j=n-1}\frac{A^iBA^j}{n!}.$$
Let $u,v$ be left and right eigenvectors of $A$ so that $uA=\mu u$, $Av=\lambda v$. (Sidedness isn't necessary when working with symmetric matrices over $\mathbb R$, but I want to leave open the possibility of working with not-necessarily symmetric matrices).  Then
$$uCv=(uBv)\sum_n\sum_{i+j=n-1}\frac{\mu^i\lambda^j}{n!}.$$
By the identity $a^n-b^n=(a-b)\displaystyle \sum_{i+j=n-1}a^ib^j$, we have
$$(\mu-\lambda)uCv=(uBv)\sum_n\frac{\mu^n-\lambda^n}{n!}=(uBv)(e^{\mu}-e^{\lambda}).$$

Actually, here is an extension of this idea which sort of gives a formula.  Given $A\in \operatorname{GL}(V)$, define $L_A,R_A:\operatorname{End}(\operatorname{GL}(V))$ by $L_A(B)=AB, R_A(B)=BA$.  Then $L_A$ and $R_A$ commute.  We can then write
$$C=\sum_n\sum_{i+j=n-1}\frac{A^iBA^j}{n!}=\left(\sum_n\sum_{i+j=n-1}\frac{L_A^iR_A^j}{n!}\right)B.$$
If we multiply this on the left by $ad_A=(L_A-R_A)$, identical algebra as above yields
$$[A,C]=e^{L_A}(B)-e^{R_A}(B)=e^AB-Be^A=[e^A,B].$$
This formula only determines $C$ up to a map commuting with $A$, but there be another way to to make use of this to find a formula for $C$ itself.


find probabilities in question of distribution of 4 distinguishable balls between 3 people

Question: I got stuck verifying the probabilities I got in the 2-Dimensional probability table. would appreciate your help! I can't figure out how to find the probabilities in the X=1 and X=2 columns.
The question:"In basketball training there are 3 players and 1 trainer. one of the players is called Anthony. The trainer throw at the players all the 4 balls, such that for every ball he chooses randomly the player that will have it (Independently with other balls) let's mark: X - number of balls Anthony received. Y - number of players such that each one of them get 2 balls exactly.
Calculate the probabilities table".
Here is what I did:

furthermore, I found out that $X$~$Bin(4,\frac{1}{3})$, no clue if Y also has a special distribution.
Answer: Ok, because looks like most of the readers are sleepy, I'm going to publish also the answer for that.

firstly, let's notice that $P(Y=0)=\frac{\binom{3}{1}+\binom{3}{2}\binom{3}{1}\binom{4}{1}}{3^4}$. the numerator counts: there're $\binom{3}{1}$ ways to distribute the balls such that one player get all the 4 balls, and there're $\binom{3}{2}\binom{3}{1}\binom{4}{1}$ ways to distribute the balls such that two of the three players get the balls such that one of them gets one ball and the second one gets the rest.
secondly, $P(X=1,Y=1)=\frac{\binom{4}{1}\binom{3}{2}\binom{2}{1}}{3^4}$ because we firstly choose the single ball for Anthony, then we choose 2 of the remaining balls for one of the other players.
lastly, $P(X=2,Y=2)=\frac{\binom{4}{2}\binom{2}{1}}{3^4}$ because we firstly choose 2 balls for Anthony and for the remaining 2 balls we choose in $\binom{2}{1}$ ways the player that will get them.

Finally, the balded values are calculated by a probabilities-table-completing-values method.
I hope it helped anybody, Cheers.


How to optimize queries with user-defined parameters in the "where" clause?

Question: I'm learning how to do proper query optimization using indexes. Let's say I have a huge table of products with all kinds of details for each product, e.g. price, category, number of purchases, review average, and more. When having multiple "where" conditions, I learned that it's best to put a multi-column index on whatever your "where" conditions are, in the order that they appear.
However, I'm having difficulty figuring out how to scale it if there are so many queries for different purposes, and if users get to pick how to filter the products table. For example, a user can browse products WHERE rating > 4 AND purchases > 100, or it could be WHERE category = 'x' AND price < 100 AND price > 20. How would a proper multi-column index work if the columns chosen to be filtered are random?
Answer:
I learned that it's best to put a multi-column index on whatever your "where" conditions are, in the order that they appear.

You learned... not quite correctly.
The order of appearance in the WHERE clause is not meaningful, since the optimizer is free to evaluate the conditions in any logically valid way, subject of course to parentheses and logical operators (AND, OR, etc.) in the expression.
The order of columns in a multi-column index is important because, from left to right, as soon as a column is encountered in an index that not mentioned in the where clause, nothing more toward the right side of that index can be used.
If 3 columns, (a,b,c) are indexed, and the query is WHERE a = 1 AND c = 6 then the optimizer will only be able to use the left-most "a" column values in that index, not "c".
In that case, it would likely still choose to use the index to find rows where a = 1, and then scan all of those identified rows for only those with c = 6.
You can visualize a multi-column index as a multidimensional array.  Without a known value or range you need to match for the first column (a), the values for the second column (b) are a meaningless, unordered jumble of data, because they're sorted in "groups of 'a'"... you'd have to iterate through every "a" to find the matching "b" values, and iterate through every "a,b" to find the matching "c" values.  Since, in the example above, the "b" value is "anything" since it isn't specified, the ordering of the "c" values is meaningless and inaccessible for optimizing the query (although when every column within the SELECT list is available within a single index, the optimizer may scan the index instead of scanning the whole table, treating it as a "covering index," which is generally better than a full table scan but still suboptimal).
If your WHERE clause includes two columns both of which are indexed individually, the optimizer will check the index statistics and try to use the one that is most likely to produce the fewest matches... if "a" and "c" each have an individual index, and the index stats indicate that there are many values for "c" (high cardinality) but only a few values for "a" (low cardinality) the optimizer will typically use the index on "c" to find matching rows, then scan all of those rows for the requested values of "a".
Or, it may try to use the union of the two indexes, to precisely identify which rows satisfy both conditions.
Neither of these strategies is optimal, either, but still far better than a full table scan, so itdoes suggest that you should -- at a minimum -- have every independently-searchable column as the leftmost column in an index... that is, any column that can be queried on its own, with no other columns in the WHERE clause, and return a reasonably-sized result-set.  If the result-set will not be reasonable in size, you may wish to restrict the user to searching on additional attributes, in the application.
In the case of WHERE category = 'x' AND price < 100 AND price > 20 the better index would be (category,price) and not (price,category) but this is not because of the ordering of expressions in the WHERE clause.  It is because category is an equality test, but price is a range.   WHERE price < 100 AND price > 20 AND category ='x' is equivalent, and (category,price) is still the appropriate index -- because indexes are sorted by the first column, then within each value for the first column, they are sorted by the values of the second column, then within each (first,second) pair they are sorted by the values in the third column, ad infinitum... so with (category,price) the server goes directly to all of the rows for category = 'x' and within that grouping in the index, the referenced rows are already sorted by price, so it only has to select the range of price within the category 'x' of the index.  Optimal.  The (price,category) index requires checking all the prices in the range, and then checing the category value for all of those.  The index could still be used, but depending on the criteria, the optimizer could still opt to scan the whole table.
If you add a third criteria to the WHERE clause that isn't indexed, the same path will be followed, but the server will scan the identified rows for matches with the required value of the non-indexed column.  Again, suboptimal, but often acceptable, depending on your business needs -- which play a role in determining the correct answer to this question.
Every index requires space, and resources, because every insert, update, and delete, requires that the server make the necessary changes -- right then -- to every index that is affected by the changes to the table.
Note also that if you have an index on (a,b) or (a,b,c), etc., then a separate index on (a) generally is considered a waste of space, since the index on (a,...anything-else...) will also serve as an index on (a).
Experimenting with  EXPLAIN SELECT (which also supports INSERT/UPDATE/DELETE as of MySQL 5.6) and genuinely understanding its output is an indispensable tool for understanding how indexes work.  MySQL 5.6 also supports optimizer tracing, which gives you detailed output of how the optimizer understood your query, the various plans it considered, the cost it estimated of each plan, and how it arrived at the decision of how to execute a particular query.
Comment: Thank you very much for the explanation. Though I understand some of it, I must admit, some of it is still over my head. I'll have to read the EXPLAIN output page when I have the time, and look at an optimization chapter in a MySQL book. Thanks again.
Comment: Thank you.  Please consider accepting the answer or let me know if there are points I can clarify.


Include warning on php

Question: I have uploaded my web site on a server and then all the includes stop working.
 when i open the site this warning pops up:

Warning: include_once() [function.include-once]: open_basedir restriction in effect.
  File(/usr/local/apache/htdocs/showcaze/User/User.php) is not within
  the allowed path(s): (/home/:/usr/lib/php:/tmp) in
  /home/a8739766/public_html/showcaze/login.php on line 3

line 3 is :
<code>include_once $_SERVER['DOCUMENT_ROOT'].'/showcaze/User/User.php';
</code>
how can i fix it?
Comment: Did you do a search on SO on "open_basedir restriction in effect" ? what did you try to fix it?
Answer: The open_base_dir setting is primarily used to prevent php scripts for a particular user from accessing files in another user's account. So usually, any files in your own account should be readable by your own scripts.
If you are on shared hosting, you are out of luck. If you have your own server or are on VPS then modify the open_basedir settings on your httpd configuration file.
Or .. you are using a wrong include and you are have no intententions to access a file outside   the basedir. You should, off course, adjust your include.

Include warning on php


Trigonometric Identities - $\sin(x-2\pi)\cos((3\pi/2)-x)+\tan(\pi-x)\tan((3\pi/2)+x)$

Question:
Simplify: $$\sin(x-2\pi)\cos\left(\frac{3\pi}{2}-x\right)+\tan(\pi-x)\tan\left(\frac{3\pi}{2}+x\right)$$

What I did was convert each term to its simplest form.
$$\sin(x-2\pi)\cos\left(\frac{3\pi}{2}-x\right) = \sin(x)\sin(x) = \sin^2(x)$$
$$\tan(\pi-x)\tan\left(\frac{3\pi}{2}+x\right) = (-\tan(x))(-\cot(x))=1 $$
So than I added those two together and got:
$$\sin^2(x)+1$$
However this is wrong somehow. Any ideas?
Comment: $\cos((3\pi/2)-x) = \cos(3\pi/2)\cos(x) + \sin(3\pi/2)\sin(x) = 0\cos(x) + (-1)\sin(x) = -\sin x$. I think you also have the wrong sign for $\tan((3\pi/2) + x)$...
Comment: Arturo, we still haven't "learned" the sum and difference identities, so how would i solve otherwise.
Comment: $\cos(x)$ is even; so $\cos((3\pi/2)-x)$ is the same as $\cos(x-(3\pi/2))$. Now, the graph of $f(x-a)$ is the graph of $f$ translated right by $a$. The graph of $\cos(x)$, translated to the right by $3\pi/2$   Is the graph of $-\sin(x)$, not of $\sin(x)$. Similarly, the graph of $\cos(x+(3\pi/2))$ is the graph of $\cos(x)$ translated *left* by $3\pi/2$, which is the graph of $\sin(x)$, and the graph of $\sin((3\pi/2)+x)$ is the graph of $\sin(x)$ translated left by $3\pi/2$, which is the graph of $-\cos(x)$. (Cont)
Comment: Alright :) Thank you
Comment: So $\tan((3\pi/2)+x) = \sin((3\pi/2)+x)/\cos((3\pi/2)+x) = -\cos(x)/sin(x) = -\cot(x)$ (maybe that sign was right). The graph of $\tan(\pi-x)$ is the same as the graph of $\tan(-x)$ by periodicity, and $\tan(-x)=-\tan(x)$.
Answer: Hint:
$$\begin{split}
&\sin(x-2\pi)\cos(3\pi/2-x)+\tan(\pi-x)\tan(3\pi/2+x)\\ = &-\sin(x)\cos(\pi/2-x) + \left(-\tan(x)\right)\left(-\tan(x-\pi/2)\right)\\ =& -\sin^2(x) + \tan(x)\tan(x-\pi/2)
\end{split}$$


Python list withing list distinct elements

Question: I have a list that looks like this:
a = [[99 , 2],[2,99]]

My objective is to get a list that has one of the elements because they are similar combinations:
so I need another list b that is either:
b = [[99,2]]

or
b= [[2,99]]

How do I go about it in the most efficient manner without any libraries, answers with libraries are also appreciated since I would wanna know what are the stuffs already out there to ease my pain with learning how to code.
Thank you
Comment: I would like to remove all the other combinations. Just need one of the elements.
Comment: if your sublist don't contain duplicates, you can transform them into frozenset, then pass that into a set and you get the one that are different, but if you only need to pick one because they are just permutation of a set of elements, just arbitrarily pick one
Comment: Needs a description of how your list looks in general. For example whether the sublists always have two Elena's, whether they always differ, whether always both (all?) orders occur. And if not all orders occur, whether the order on the output matters.
Answer: There might be many different ways to do it, but one option is to use frozenset in set:
a = [[99,2],[1,2,3],[2,99],[2,3,1]]
b = set(frozenset(x) for x in a) # alternatively, set(map(frozenset, a))
print(b) # {frozenset({1, 2, 3}), frozenset({2, 99})}
b = [list(x) for x in b]
print(b) # [[1, 2, 3], [2, 99]]

Another option is to use (sorted) tuples to represent the "uniquified" elements:
b = set(tuple(sorted(x)) for x in a)

However, frozenset seems faster: Hashing frozenset versus tuple of sorted
Comment: I mean better use map instead of your generator expression.
Comment: If you want fast, then don't reimplement `map`.
Comment: @KellyBundy Can you give me more details? I am afraid I am not experienced to understand it. Please teach me, thanks.
Comment: @KellyBundy Aha now I understand, thanks!
Answer: I can give you an answer using libraries. random is part of the python standard library (you already have it installed if you have python), so depending on why you don't want to use libraries, this might work.
import random

a = [[99 , 2],[2,99]]
b = random.choice(a)

b will be a list that has exactly one of the elements of list a.
If you need b to be a list of lists, modify it like so:
import random

a = [[99 , 2],[2,99]]
b = [random.choice(a)]

Comment: What even is this answer? He is not asking to peek random. He is asking how to distinct them
Comment: @sudden_appearance what even is this comment


Jquery is not working in Rails 3.2.8

Question: my name is Pamela and i'm new to this version of rails, i'm trying to put some validations and datepickers in a form, but for some reason the jquery is not working, i've searched a lot and tried several things but they didn't work.
Here's my application.js file:
//= require jquery
//= require jquery_ujs
//= require jquery-ui-1.8.24.custom.min
//= require jquery.ui.datepicker-es
//= require jquery.validate
//= require messages_es

This is my application.html.erb:
<%= javascript_include_tag "application" %>

I ran: rails generate jquery:install and this is the result:
deprecated  You are using Rails 3.1 with the asset pipeline enabled, so this generator is not needed.
              The necessary files are already in your asset pipeline.
              Just add //= require jquery and //= require jquery_ujs to your app/assets/javascripts/application.js
              If you upgraded your app from Rails 3.0 and still have jquery.js, rails.js, or jquery_ujs.js in your javascripts, be sure to remove them.
              If you do not want the asset pipeline enabled, you may turn it off in application.rb and re-run this generator.
Can anyone help?
Thank you.
Updated:
This is my form:
<%= form_for(@contrato) do |f| %>
  <% if @contrato.errors.any? %>

<%= pluralize(@contrato.errors.count, "error") %> no han permitido que el contrato sea guardado:

      <% @contrato.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label 'Obra' %>

    <%= f.text_field :contrato_nombre_obra %>

   <%= f.label 'Nombre Contratista/Empresa' %>

   <%= f.select :contratista_id, Contratista.find(:all, :order => "empresa").collect{|c| [c.empresa, c.id] } %>

    <%= f.label 'Municipio' %>

    <%#= f.number_field :tipo_norma_legal_id %>
    <%= f.select :municipio_id, Municipio.find(:all, :order => "nombre").collect{|c| [c.nombre, c.id] } %>

    <%= f.label 'Localidad' %>

    <%#= f.number_field :tipo_norma_legal_id %>
    <%= f.select :localidad_id, Localidad.find(:all, :order => "nombre").collect{|c| [c.nombre, c.id] } %>

    <%= f.label 'Tipo de Norma Legal' %>

    <%#= f.number_field :tipo_norma_legal_id %>
    <%= f.select :tipo_norma_legal_id, TipoNormaLegal.find(:all, :order => "tipo_norma_legal_descripcion").collect{|c| [c.tipo_norma_legal_descripcion, c.id] } %>

    <%= f.label 'Nº Norma Legal '%>

    <%= f.text_field :contrato_nro_norma_legal %>

    <%= f.label 'Año Norma Legal' %>

    <%= f.text_field :contrato_anio_norma_legal %>

    <%= f.label 'Nº de Expediente (solo numeros)' %>

    <%= f.text_field :contrato_expte %>

    <%= f.label 'Fecha del Contrato' %>

    <%= f.text_field :contrato_fecha %>

    <%= f.label 'Monto de Contrato ($)' %>

    <%= f.text_field :contrato_monto %>

    <%= f.label 'Plazo de Obra (dias)' %>

    <%= f.text_field :contrato_plazo_obra %>

    <%= f.label 'Contrato Finalizado' %>
    <%= f.check_box :finalizado %>

    <%= f.submit 'Guardar', :class=>'button' %>

<% end %>

<%= render(:partial => "javascripts") %>

This is the partial:

Comment: Can you show what the error is and the snippet of your code?
Comment: Are there are any javascript errors on the page?
Comment: NO, that's the strange thing, couldn't find any javascripts errors
Answer: You should already have access to jQuery and Unobtrusive jQuery if you have generated the application and haven't changed the gemfile. Check if it includes jquery-rails. If it does, then you already have jquery ready to use. You don't need to run rails generate jquery:install.
Comment: yes, i also thought the same thing, i really don't why is not validating the form or showing the datepickers. Is such a mistery, and i really need the javascript
Answer: Well, first of all, thank you very much for helping me... i've tried another one last thing... i started from fresh, i've realized that maybe i deleted something in my effort to make javascript work, so i decided to created a the project again (not the ideal thing to do, right?), so i just copied my views in the new project, made the migrations, etc... And now at least the validations are working, i didn't try datepickers or other stuff yet (hopefully they'll work too). If ever know what happened, i'll let you know it may help someone else.

Jquery is not working in Rails 3.2.8


Hibernate: Selecting same record using load() and get() in the same Session

Question: Some of the web articles are saying that 'load() method will create a proxy that engages with the unit of work related flow until the real persistent object is created with flow and later reference variable stops referring proxy and starts referring to real obj representing record'
(means session will be associated with two instances to perform a load).
As for my understanding "load() method may return a proxy, a placeholder, without
hitting the database. A consequence of this is that you may get an ObjectNotFoundException later, as soon as you try to access the returned placeholder and force
its initialization". (Reference-Book: Java Persistence With Hibernate).
It means session will be associated with only one instance that is a proxy to perform a load.
Here is an Example that shows what i have understood..
    Session mysql_session1 = session_factory.openSession();

    logger.info("calling load()");
    POCEntity1 p = (POCEntity1) mysql_session1.load(POCEntity1.class, 12);
    /*
     * Will create a proxy which doesn't have the real data means will not
     * completely initialized until we invoke methods on it to get data.
     */
    logger.info("calling get()");

    POCEntity1 p1 = (POCEntity1) mysql_session1.get(POCEntity1.class, 12);
    /*
     * Now,the get method will directly hits the database with a select
     * query even though an object(proxy) with same identifier value already
     * associating with the session.Because the session will mark the
     * proxy's status as uninitialized ,so after calling get session will
     * re-writes the state/completes the initialization of the proxy. so p1 also
     * refers the same object.
     */

    logger.info("calling load() again ");
    POCEntity1 p2 = (POCEntity1) mysql_session1.load(POCEntity1.class, 12);

    logger.info("p==p1" + (p == p1)); //p==p1true
    logger.info("p==p2" + (p == p2)); //p==p2true
    logger.info("p1==p2" + (p1 == p2));//p1==p2true

    logger.info("p.getTitle" + p.getTitle());
    /*
     * will not making hibernate to generate another select query.
     * only one select query will be generated.
     */

So,Please let me know whether i am understanding the concepts(about load(), a get() after load()) correctly or not...
My example is saying that
"get() method will uses the proxy created by the preceding load() method and completes its initialization instead of returning a new instance and referencing it. (p==p1true)".
Thanks in Advance!!.
Note: I have used assigned generator.
Answer: You have picked it right, semantics of these methods sometimes cause confusion. Here is practical use of two methods:

You can use load in cases where you have to set a foreign key relationship, you can set a object without actually loading it. Load only ensures that object with that id exists and thats why you find it throwing ObjectNotFoundException
Car c = new Car();
Engine e = (Stock)session.load(Engine.class, new Integer(1));
c.setEngine(e);
session.save(c);

Note you only need to set engine in car you don't need actually any of the properties of engine.

Use get when you actually need that object.
Engine e = (Stock)session.get(Engine.class, new Integer(1));
System.out.println(e.getYear();

Hope this clarifies.
Also refer Whats the advantage of load() vs get() in Hibernate?
Hibernate: Difference between session.get and session.load
Cheers !!


why is mat-autocomplete not showing my loading spinner?

Question: i'm trying to utilize angular material in my angular 11 project, one of my pages contain a mat-autocomplete component. i would like this component to show a loading spinner when i request something.
this is my code :

component.ts
this.searchServiceProviderCtrl.valueChanges
    .pipe(
        debounceTime(500),
        tap(() => {
            this.loading = true;
        }),
        switchMap( (value) => this.serviceProviderAutocompleteService.searchByQuery(value)
        )
    )
    .subscribe( (response) => {
        this.serviceProviders = response;
        if (isNullOrUndefined(this.serviceProviders) || this.serviceProviders.length === 0) {
            this.emptyServiceProviders = true;
            this.loading = false;
        }
    });

component.html
<mat-form-field>
        <input matInput placeholder="Search" aria-label="State" [matAutocomplete]="auto" [formControl]="searchServiceProviderCtrl">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngIf="loading" class="is-loading">
            <mat-progress-bar mode="indeterminate"></mat-progress-bar>
          </mat-option>
          <mat-option *ngIf="emptyServiceProviders">Aucun résultat</mat-option>
          <ng-container *ngIf="!loading">
            <mat-option *ngFor="let serviceProvider of serviceProviders" [value]="serviceProvider">
              {{serviceProvider.lastName + ' ' + serviceProvider.firstName}}
            </mat-option>
          </ng-container>
        </mat-autocomplete>
    </mat-form-field>

first time i wasn't able to see the loader, and i figured out that my service was synchronous, so i added a piece of dead code in it to fake a sleep(5000ms) :
    searchByQuery(query: string): Observable<any[]> {
    const date = Date.now();
    let currentDate = null;
    do {
        currentDate = Date.now();
    } while (currentDate - date < 5000);
    return of(this.values.filter((v) => v.firstName.toLowerCase().indexOf(query.toLowerCase()) > -1 || v.lastName.toLowerCase().indexOf(query.toLowerCase()) > -1));
}

but even with that workaround, i'm never able to see the loading spinner. i added a {{loading}} in the html to debug, and it never toggles to true, even if i pass in tap() => this.loading = true;
does anyone have a clue on why the loading boolean never updated in the html ?
Comment: Can you post your code (or minimal reproducible code) to Stackblitz?
Answer: Your searchByQuery is still synchronous since you're doing a busy wait. Since Javascript is single threaded, you lock the browser tab for 5 seconds and your spinner doesn't show.
To make searchByQuery async with Rxjs, you can use this:
import { delay} from 'rxjs/operators';

searchByQuery(query: string): Observable<any[]> {
    return of(this.values.filter((v) => v.firstName.toLowerCase().indexOf(query.toLowerCase()) > -1 || v.lastName.toLowerCase().indexOf(query.toLowerCase()) > -1))
        .pipe(delay(5000));
}

Comment: THANK YOU very much, it helped a lot.


Como imprimir o resultado de uma função php de outra pagina?

Question: Você podem me dizer como terminar esse projeto, com esse codigo abaixo eu conseguido definir a mensagem que vai aparecer a partir do numero inserido pelo usuário dado pelo administrador
        <form action="submit.php" method="post" >

insira o código especifico ou deixe em branco para resposta padrão

         <input type="text" name="CODNOME">

          <button type="submit" >Enviar</button>

        </form>

o código que estou usando no submit.php
 <?php

//função para gerar respostas

echo $CODNOME;

if($_POST['CODNOME'] == "001"){
  $msg = "mensagem1";
}

else if($_POST['CODNOME'] == "002"){
  $msg = "mensagem2";
}

else {
  $msg = "opção fixa";
}

echo $msg;
?>

o código acima redireciona para outra pagina.
Mas gostaria que se o usuário digitar um código invalido ou não digitar nada ele imprime a "msg fixa" imprimindo ela sem mudar de pagina clicando no código abaixo.
<input type="submit" value="Imprimir" class="btn no-print" onClick="window.print()">

msg fixa

isso seria como se o resultado da submit.php fosse impressão do usuário, na mesma pagina, tem alguma forma de fazer isso ?
Comment: Você pode usar a `action` para a mesma página que está o formulário. Pode escrever o nome da página ou usar `$_SERVER["PHP_SELF"]`. Depois basta verificar se a varíável post não está vazia, `if (!empty($_POST))` e coloca as condições que pretende verificar.
Comment: @lazyFox deu certo colocando na mesma pagina ele gera o  que eu queira porem agora ele não aplica a função não reconhece o valor inserido no input nem 001 nem 002 da apenas como 'else'

como aplico o 'if (!empty($_POST))'
na
'  '
Answer: Coloque a pagina html junto com o arquivo php e faça isso:
<?php

//função para gerar respostas

echo $CODNOME;

if($_POST['CODNOME'] == "001"){
  $msg = "mensagem1";
}

else if($_POST['CODNOME'] == "002"){
  $msg = "mensagem2";
}

else {
  $msg = "opção fixa";
}

echo "<input type='submit' value='Imprimir' class='btn no-print' onClick='window.print()''>

$msg

";
?>

Ou você pode fazer assim também:
<?php

//função para gerar respostas

echo $CODNOME;

if($_POST['CODNOME'] == "001"){
  $_POST['msg'] = "mensagem1";
}

else if($_POST['CODNOME'] == "002"){
  $_POST['msg'] = "mensagem2";
}

else {
  $_POST['msg'] = "opção fixa";
}

?>

//Title, body etc
<input type='submit' value='Imprimir' class='btn no-print' onClick='window.print()''>

<?php echo $_POST['msg']; ?>

Comment: Colando o código na mesma pagina ele não muda a resposta sempre  mostra "opção fixa" como se a função nao estivesse sendo aplicada  somente mostrando o que tem

**else {
  $_POST['msg'] = "opção fixa";
}**
Comment: @LuccasCerqueira essa parte eu copiei do seu código, sempre vai pra elsse porque você deve não está recebendo o $_POST['CODNOME'], como ela não existe, sempre é else


Problemas para instalar o Composer no Windows

Question: Estou tentando instalar o Composer por esse tutorial no Windows, mas estou com problemas na hora de baixar tanto pelo PHP como pelo cURL.
Comment: primeiro voce tem que instalar o curl [atraves do site oficial](http://curl.haxx.se/download.html).
Comment: Cara, por que você não baixa o instalador normal?
Comment: Voce pode instalar pelo php na sua segunda opção, porem voce deve ver se o php e versão 5.3 ou posterior usando php --version, quando voce executou o comando de instalação pelo php ocorreu um erro de syntax, copia todo o comando e cole la e execute: php -r "readfile('https://getcomposer.org/installer');" | php
Answer: Tente instalar pelo próprio instalador oferecido pela Composer, Composer-Setup.exe. Boa sorte!


How to test for normal distribution with one peak in data?

Question: I would like to test following. Suppose I have a normal distribution with mean 1.5 and sigma 0.5 on interval [0, 3]. Python code:
import numpy as np
import matplotlib.pyplot as plt

mu = 1.5  # mean
sigma = 0.5  # standard deviation
n = 1000  # number of samples

# generate normally distributed random numbers with mean mu and standard deviation sigma
samples = np.random.normal(mu, sigma, n)

# shift and scale the samples to the range 0 to 3
samples = np.clip(samples, 0, 3)

Histogram looks like this:

But now I add one peak around x = 1.96 and my histogram looks like this now:

Python code for generating this peak is:

n = 70  # number of samples

# generate uniformly distributed random numbers between 0 and 1
added_samples = np.random.rand(n)

# scale the samples to the range 1.96 to 1.99
added_samples = 1.96 + added_samples * (1.99 - 1.96)

all_together = np.append(samples, added_samples)

My question is, if there is a statistical test or algorithm that can check for normally distributed data with "one peak"? Some modification of shapiro-wilk test or something.. Thanks a lot.
EDIT:
What we know beforehand:

Peaks can be only in three points, lets say x = 1.5, x = 1.96 or x = 2.5. We would like to test if there is really a peak in any of these x.
We know the mean and standard deviation of the new sample = that is after the peak is present.
The additional data are uniformaly distributed around the interval [x, x + 0.03] (that is [1.5,1.53],  [1.96,1.99] or [2.5, 2.53])
Comment: Strictly speaking, the normal distribution has unbounded support, so your clipping operation results in a *truncated* normal distribution. Are the points of truncation *known* beforehand, or do they need to be estimated from the data?
Comment: @StephanKolassa We know only the truncation points of the original data, because it cannot change just because of adding additional peaks. Unfortunately, we dont know the mean and standard deviation of the original data, so we need to estimate these.
Comment: Can I check, what is the goal of testing for normality in this context? I am reluctant to recommend anything based on Shapiro-Wilk or indeed null hypothesis significance testing in general. What is the point of of seeing whether a fallible test successfully rejects the null hypothesis when we already know for a fact that the null hypothesis is false (a normal distribution that is then clipped and has another peak inserted is by definition no longer a normal distribution)? If the p-value is low, it tells us nothing we didn't already know, and if it's high, then it's a type II error.
Comment: What is your goal with this? Your data is clearly not normal, so this seems like `but other than that piece which doesn't fit with my hypothesis, how does the rest look?`.
Comment: [My answer](https://stats.stackexchange.com/a/610422/1352) to [Normality test after rounding](https://stats.stackexchange.com/q/610417/1352) could easily be adapted to your case, at least if the truncation is known: either do the "inter-ocular trauma test", or a parametric bootstrap of the Shapiro-Wilk test (or any other goodness of fit test) under the null distribution of a truncated normal.
Comment: @vojtam, maybe D'Agostino's $K^{2}$ Test will help you. It's described [here](https://en.wikipedia.org/wiki/D%27Agostino%27s_K-squared_test) and can be found as [scipy.stats.normaltest](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.normaltest.html).
Comment: @StephanKolassa Thank you for your comments. Yes, suppose I would like to test if there is a peak in x = 1.96 , so I know them beforehand. I am little bit confused with the `truncated normal distribution` as you write. Why does my case lead to truncated normal distribution?
Comment: Ah, so you even know where the peak will be? That changes matters a bit, then it might be possible to create a more powerful test. Can you be as explicit as possible as to what information are known beforehand and which need to be estimated from the data? I'm thinking of the mean, the standard deviation, the upper and lower truncation point, and any knowledge you have of the additional data (in your example, you know that they are uniform in [1.96,1.99])? It does sound like what you want to test is whether your data come from a mixture of a truncated normal and a uniform distribution.
Comment: To your question about the truncation: the normal distribution is spread out over the entire real axis. Your `np.clip` command truncates it, so what you end up with is not normal any more. (Actually, since `np.clip` does not *remove* data outside the interval, but maps these data points to the interval boundary, what you end up with is not a [truncated normal](https://en.wikipedia.org/wiki/Truncated_normal_distribution), but a mixture of a truncated normal with two point masses.) Whether you can disregard this effect or not will depend on how much you cut off.
Comment: @StephanKolassa Thanks for you answer. See my edit please.
Comment: Great, thanks, we are making progress. Do you know the mean, standard deviation and truncation points of the original data before the "additional data" comes in, or do we need to estimate these from the data?
Answer: First, it seems like you should be able to identify the particular alternative hypothesis, i.e., which of the three potential intervals the "additional" data would come from, simply by looking which of the three intervals contains the most excess data over what we would expect under the null hypothesis of a normal distribution.
Next, the probably best way to continue would be a likelihood ratio test between two competing models for the data.

A mixture between (a) a mixture of a truncated normal distribution and two point masses at 0 and 3 and (b) a uniform distribution on a prespecified interval.
The mixture between the truncated normal and the two point masses, part (a) without (b) above.

Unfortunately, the likelihood functions involved are a bit icky... maybe someone with more time could set these up. It might be best to bootstrap the test itself once we have the likelihoods.

A much simpler alternative would be to use a two-sample Kolomogorov-Smirnov test: compare your data against a simulated data sample under the null hypothesis of that mixture between a truncated normal and two point masses with no "additional data".
Here is an example. I will use R, simply because I am more fluent in that.
# a function to simulate data
simulate_obs <- function(n_orig,m_orig,sd_orig,n_add,a_add,b_add) {
    obs <- c(rnorm(n_orig,m_orig,sd_orig),runif(n_add,a_add,b_add))
    pmin(pmax(obs,0),3)
}

# simulation parameters
n_orig <- 1000
m_orig <- 1.5
sd_orig <- 0.5
n_add <- 70
a_add <- 1.96
b_add <- 1.99

# simulate your "real" data
set.seed(1)
obs_orig <- simulate_obs (n_orig,m_orig,sd_orig,n_add,a_add,b_add)

# simulate under the null hypothesis
null_sample <- simulate_obs(length(obs_orig),mean(obs_orig),sd(obs_orig),0,0,3)
# compare your "real" data to the simulated data:
ks.test(obs_orig,null_sample)

In the present case, this gives $p=0.23$, because the "real" data is quite consistent with coming from a "real" uncontaminated distribution.
Comment: @Number: to be honest, it's the first one that comes to mind. I agree that the Anderson-Darling test in particular would be an alternative.
Comment: The KS test between your data and *simulated data under the null hypothesis* does care about the peak, because the "reference data" explicitly does not contain the second peak. See how I define `null_sample`.
Comment: @StephanKolassa I completely agree with your answer, just out of curiosity, why use the KS test when other tests have advantages? -- see my new question at https://stats.stackexchange.com/questions/610924/why-is-the-kolmogorov-smirnov-test-so-popular-when-other-tests-have-advantages
Comment: @Number the KS test is less powerful if your hypothesis about the type of distribution is correct.
Comment: Thanks for your answer. The idea with the likelihood ration test is interesting, I will think about it. KS test is not really what I need, because it just checks if two samples follow the same distribution. In other words, it does not care about my peaks in data. But again, thanks a lot :)
Comment: Ah, sorry, I see, thanks!
Answer:
Compute the probability for the set $S=[1.5,1.53] \cup [1.96,1.99] \cup [2.5, 2.53]$ for a truncated normal with the given parameters, say $p_0$.

Run a binomial test for the $H_0:\ p=p_0$ against the alternative $p>p_0$ on data that is 1 for observations in $S$ and 0 for observations not in $S$.

One can probably improve this a bit if you know that there will be only one peak; what I propose here works also (and is maybe in some sense optimal) if you have peaks at two or all three of these locations.
Comment: @vojtam OK, sorry, my answer was then based on not fully understanding what information is known and what isn't. In principle it should be possible to estimate the parameters of a normal distribution from the data excluding "critical" intervals using the information what is excluded, but this is unfortunately a nonstandard problem and I don't have a solution for it right now.
Comment: Thanks, but how do you compute the step 1? We dont know the parameters (mean and standard deviation) of the original truncated normal distribution, right? We only know how the new distribution with a peak looks like.
Comment: @vojtam The question says "Suppose I have a normal distribution with mean 1.5 and sigma 0.5 on interval [0, 3]", so I thought you know them?
Comment: unfortunately not, please look at the last paragraph *What we know beforehand:*


Change linux multicast interface

Question: Why my multicast traffic always goes through wlan0 interface?
I try
ip route add 220.127.116.11/4 dev lo
ip link set dev lo multicast on
ip route flush cache

But VLC casting to 22.214.171.124:1111 always goes through wlan0 interface.
ip route:
default via 192.168.0.1 dev wlan0  proto static  metric 600
192.168.0.0/24 dev wlan0  proto kernel  scope link  src 192.168.0.102  metric 600
22.214.171.124/4 dev lo  scope link

Answer: Ok the problem you are running into is VLC is defaulting to the interface of your default route, but you need the device of the default route to be a different network card.
You can't have two default routes but you can do a little hackary to get around this.
1) Set the default route to be the network card you want to receive multicast packets on. For example eth4
ip route del default
ip route add default dev eth4

Your computer will no longer be able to route traffic to your gateway so your internet will break.
2) To fix it route all traffic to your gateway.
ip route add 0.0.0.0/1 via (ip of gateway) dev wan1
ip route add 22.214.171.124/1 via (ip of gateway) dev wan1

Answer: this work for me
ip route add 22.214.171.124/4 dev lo table local

verify with
ip route get 184.108.40.206

Change linux multicast interface


Injecting an input to a step provided in a stepList?

Question: I have a pipeline template that takes a stepList:
parameters:
- name: applicationDeploySteps
  type: stepList
  default: []

And injects the stepList into the template:
- deployment: Deploy_App
  displayName: Deploy Application
  pool: ${{ variables.AgentPool }}
  environment: ${{ parameters.Stage }}
  variables:
  - name: ServiceConnection
    value: SomeServiceConnection
  strategy:
    runOnce:
      deploy:
        steps:
          - ${{ each step in parameters.applicationDeploySteps }}:
            - ${{ each pair in step }}:
                ${{ pair.key }}: ${{ pair.value }}

However, I'd like to provide an AzureCLI@2 step, with the azureSubscription parameter being sourced from a variable inaccessible to the AzureCLI@2 step at the time of template compilation:
extends:
  template: main.yml
  parameters:
    applicationDeploySteps:
      - task: AzureCLI@2
        inputs:
          azureSubscription: $(ServiceConnection)
          addSpnToEnvironment: true
          scriptType: 'bash'
          scriptLocation: 'inlineScript'
          inlineScript: |
            echo "do azurey things here"

The problem is in azureSubscription: $(ServiceConnection). Obviously, that variable can't resolve. So the solution I'm shooting for is to inject the azureSubscription value in the template. However, I can't find a way to effectively iterate over the values provided in the input block.
- ${{ each pair in step }}:
    ${{ pair.key }}: ${{ pair.value }}

will let me interrogate the type of the step. Trying to take it further just gives me a null reference exception when trying to queue the pipeline:
- ${{ each pair in step }}:
    ${{ if eq(pair.key, 'inputs') }}:
      - ${{ each input in pair.value }}:
          ${{ if eq(input.key, 'azureSubscription') }}:
            ${{ input.key }}: ${{ variables.ServiceConnection }}
          ${{ else }}:
            ${{ input.key }}: ${{ input.value }}
    ${{ else }}:
      ${{ pair.key }}: ${{ pair.value }}

That attempt gives me: Object reference not set to an instance of an object. with no corresponding line number. I'm guessing it's failing to iterate over pair.value, but I have no idea how to troubleshoot it further or get an idea of what I can and cannot iterate over. The documentation does not include more comprehensive examples, just checking if, say, it's a script task and blocking execution.
Note that this is similar, but not the scenario that I'm implementing.
Answer: I figured it out.
- ${{ each step in parameters.applicationDeploySteps }}:
  - ${{ each pair in step }}:
      ${{ if eq(pair.key, 'inputs') }}:
        inputs:
          ${{ each input in pair.value }}:
            ${{ if eq(input.key, 'azureSubscription') }}:
              ${{ input.key }}: ${{ variables.ServiceConnection }}
            ${{ else }}:
              ${{ input.key }}: ${{ input.value }}
      ${{ else }}:
        ${{ pair.key }}: ${{ pair.value }}

This document was useful for pointing me in the right direction, but honestly it was mostly trial-and-error.


Como testar se uma cadeia de caracteres é um número na linguagem C?

Question: Sou iniciante na programação.
Estou realizando um exercício no qual eu devo determinar se uma cadeia de caracteres é um número, considerando que o usuário pode escrever qualquer coisa como entrada. Então criei a função abaixo. Eu só posso usar a biblioteca padrão. Estou tentando usar o mínimo de variáveis possível.
Alguém poderia avaliar?
int isNumber(char input[], int input_size){

int i;

//Elimina cadeia com caracteres não numéricos
for(i = 1; i < input_size; i++)
{
    if(input[i-1] != '0' && input[i-1] != '1' &&
       input[i-1] != '2' && input[i-1] != '3' &&
       input[i-1] != '4' && input[i-1] != '5' &&
       input[i-1] != '6' && input[i-1] != '7' &&
       input[i-1] != '8' && input[i-1] != '9' &&
       input[i-1] != '.' && input[i-1] != ',' &&
       input[i-1] != ' ' && input[i-1] != '-' &&
       input[i-1] != '\0'){
        return 0;
    }
}

//Elimina cadeia que só possui espaços e caracteres nulos
for(i = 1; i < input_size; i++){
    if(input[i-1] != ' ' && input[i-1] != '\0'){
        break;
    }
}
if(i >= input_size){
    return 0;
}

//Elimina cadeia com mais de um ponto ou vírgula
for(i = 1; i < input_size; i++){
    if(input[i-1] == '.' || input[i-1] == ','){
        for(i++; i < input_size; i++){
            if(input[i-1] == '.' || input[i-1] == ','){
                return 0;
            }
        }
        break;
    }
}

//Elimina cadeia com mais de um sinal de menos
for(i = 1; i < input_size; i++){
    if(input[i-1] == '-'){
        for(i++; i < input_size; i++){
            if(input[i-1] == '-'){
                return 0;
            }
        }
        break;
    }
}

//Elimina cadeia com dois números separados por espaço
for(i = 2; i < input_size; i++){
    if(input[i-2] != ' ' &&
       input[i-2] != '\0' &&
       input[i-1] == ' ' &&
       input[i] != ' ' &&
       input[i] != '\0'){
        return 0;
    }
}

//Elimina cadeia com dois números separados por sinal de menos
for(i = 2; i < input_size; i++){
    if(input[i-2] != ' ' &&
       input[i-2] != '\0' &&
       input[i-1] == '-' &&
       input[i] != ' ' &&
       input[i] != '\0'){
        return 0;
    }
}

//Elimina cadeia terminada em sinal de menos
for(i = input_size; i > 0; i--){
    if(input[i-0] != '\0' && input[i-0] != ' ' && input[i-0] == '-'){
        return 0;
    }
}

//Elimina cadeia que somente tem ponto, vírgula ou sinal de menos
if((input[0] == '.' || input[0] == ',' || input[0] == '-') && (input[1] == ' ' || input[1] == '\0')){
    return 0;
}
for(i = 2; i < input_size; i++){
    if((input[i-2] == ' ' || input[i-2] == '\0') &&
       (input[i-1] == '.' || input[i-1] == ',' || input[i-1] == '-') &&
       (input[i] == ' ' || input[i] == '\0')){
        return 0;
    }
}

return 1;
}

Answer: Ve se é isso q vc queria.
#include <stdio.h>

int IsNumber( char input[] )
{
    register int i;
    int flagVirgula = 0;

    for(i = 0; input[i]; i++)
    {
        if( !i && !(input[i] - '-') )//Numero negativo
            continue;

        if( (!(input[i] - ',') || !(input[i] - '.')) && !flagVirgula )//só pode posuir uma virgula ou ponto
        {
            flagVirgula = 1;
            continue;
        }

        if( (!(input[i] - ',') || !(input[i] - '.')) )//segunda virgula
            return 0;

        if( (input[i] - '0') < 0 || (input[i] - '0') > 9 )
            return 0;
    }

    return 1;
}

int main()
{
    char nome[50];

    while(1)
    {
        gets(nome);

        printf("%s\n", IsNumber(nome) ? "E um numero." : "Nao e um numero.");
    }

    return (0);
}

Comment: Não está dando a saída exata que eu queria. Mas me fez perceber que, ao me forçar a usar o mínimo de variáveis possíveis, estou complicando demais a lógica do meu código e dificultando a legibilidade. Obrigado.
Comment: e o essencial da resposta,q eu está certo aqui, é qeu em C se pode comparar caracteres diretamente pelo código - então a expressão `( (input[i] - '0') < 0 || (input[i] - '0') > 9 )` é  a que faz realmente toda a diferennça em vez de se comparar o caractere com cada dígito de forma hard-coded.
Comment: @CL27 Não se preocupe com o número de variáveis do seu código: O compilador simplificará muitas coisas para melhorar o desempenho do seu programa, de qualquer maneira. Tente usar o número de variáveis que você achar necessário, e seja descritivo quando criar uma variável.
Comment: mas se preocupar em simplificar sim - esse código está bem melhor que o apresentado na questão - em particular pro só percorrer a sequencia uma vez, e não com um  loop para cada caso.  Em sistemas mais complexos, se for necessário um loop para cada caso, faça cada loop ter uma função própria - senão fica bem difícil manter controle.
Answer: Em vez de percorrer a sequência de caracteres várias vezes procurando por propriedades específicas, é melhor examinar uma vez só, considerando as propriedades de um número bem formado:
#include <stdio.h>
#define FLAG_DIGITO_ENCONTRADO 1

int
eh_numero(const char * entrada) {
    unsigned int flags = 0;
    // um número pode ter uma quantidade arbitrária de espaços antes dele
    while (*entrada == ' ') entrada ++;
    // seguido, opcionalmente, de um único sinal de menos
    if (*entrada == '-') entrada ++;
    // seguido de zero ou mais dígitos
    while (*entrada >= '0' && *entrada <= '9') {
        flags |= FLAG_DIGITO_ENCONTRADO;
        entrada ++;
    }
    // se encontrou pelo menos um dígito, o número pode terminar aqui
    if ((flags & FLAG_DIGITO_ENCONTRADO) && *entrada == '\0')
        return 1;
    // senão, vai ter que encontrar um separador decimal
    if (*entrada == '.' || *entrada == ',') entrada ++;
    // Se não houver dígitos antes da vírgula/ponto, precisa de
    // pelo menos um depois do ponto
    if (!(flags & FLAG_DIGITO_ENCONTRADO) && (*entrada < '0' || *entrada > '9'))
        return 0;
    // se houver, pode haver mais zero ou mais dígitos depois do ponto
    while (*entrada >= '0' && *entrada <= '9') entrada ++;

    // finalmente, temos que ter chegado ao fim da sequência, ou
    // ela não é um número
    return (*entrada == '\0');
}

// main para efetuar alguns testes
#define VERIFIQUE(N) printf("A sequência " N " %sé um numero válido\n",\
    eh_numero(N) ? "" : "não ")
int
main(int argc, char ** argv) {
    VERIFIQUE("0");
    VERIFIQUE("         -2.5");
    VERIFIQUE("1.");
    VERIFIQUE(",25");
    VERIFIQUE("3..");
    VERIFIQUE("+1");
    VERIFIQUE("--8");
    VERIFIQUE(",");
    VERIFIQUE("3A");

    return 0;
}

Note que eu usei um unsigned int para guardar flags binárias. No caso, só precisei de uma (para guardar contra o caso de não haver dígitos nem antes, nem depois da vírgula), mas poderia haver mais caso quiséssemos converter o número em float, por exemplo. Neste caso, a segunda flag seria 2, a terceira 4, a quarta 8, e por assim em diante. Usa-se disjunção bit-a-bit (|) para ligar a flag, e conjunção bit-a-bit (&) para testar se está ligada. Podia substituir por uma variável simples neste caso, mas acho que vale a pena só para lembrar as pessoas desta possibilidade.
O resultado dos testes:
$ cc -o so201793 so201793.c -Wall

$ ./so201793
A sequência 0 é um numero válido
A sequência          -2.5 é um numero válido
A sequência 1. é um numero válido
A sequência ,25 é um numero válido
A sequência 3.. não é um numero válido
A sequência +1 não é um numero válido
A sequência --8 não é um numero válido
A sequência , não é um numero válido
A sequência 3A não é um numero válido

$

Comment: Resposta impecável. Infelizmente, tem alguns comandos/conceitos que ainda não vi nas aulas de programação em C. Então fiz um código diferente, mas com essa mesma abordagem de percorrer a cadeia uma única vez. Obrigado de qualquer forma.


Forecast accuracy measures for different forecast horizon h in R

Question: I have a yearly time series data, from 1980 to 2005. The data is splitted into an training sample and a out of sample; the out-of sample consists of the 6 most recent observations and the rest is considered for training sample. I need to fit a ETS model and compare different accuracy measures for different forecast step aheads h=1,2,3,4,5 and 6.
Something like this:
    h=1  h=2  h=3  h=4  h=5   h=6

MSE   ..   ..   ..   ..  ..    ....   ..   ..   ..  ..    ....   ..   ..   ..  ..    ..
MASE  ..   ..   ..   ..  ..    ......   ..   ..   ..  ..    ....   ..   ..   ..  ..      ..
The following code gives me the accuracy measures for h=6:
trainx<- window(x,end=1999.99)
testx<- window(x,start=2000)
fit<- ets(trainx)
accuracy(forecast(fit,h=6),testx)

The questions are:

How can I calculate the accuracy measures for h=1,2,3,4,5 ? For instance, when h=2, I fit a model to training data and I produce the forecast that correspond to 2000 and 2001.
Now, how should I produce the forecast for 2002 and 2003, etc?
Should I suppose that the observations for the year 2000 an 2001 are known and then fit a new model (this time I need to add the observations of 2000 and 2001 to the training set), then, to produce the forecast for 2002 and 2003?
Answer: It sounds like you need a rolling forecast origin (aka time series cross-validation). Here is an example.
library(forecast)
x <- ts(cumsum(rnorm(26)), start=1980)

k <- 10 # minimum data length for fitting a model
n <- length(x)
mae <- matrix(NA,n-k-1,6)
st <- tsp(x)[1] + k - 1

for(i in 1:(n-k-1))
{
  trainx <- window(x, end=st+i-1)
  testx <- window(x, start=st+i, end=st+i+5)
  fit <- ets(trainx)
  fcast <- forecast(fit, h=6)
  mae[i,1:length(testx)] <- abs(fcast[['mean']]-testx)
}
mase <- mae / mean(abs(diff(x)))
tab <- rbind(colMeans(mae,na.rm=TRUE),colMeans(mase,na.rm=TRUE))
rownames(tab) <- c("MAE","MASE")
colnames(tab) <- paste("h=",1:6,sep="")
tab


Is there only one way to divide an equilateral triangle into congruent fourths?

Question: Suppose we wish to divide an equilateral triangle into fourths, such that each piece is congruent. (Let's also require connectedness.) One way to do this is to connect the medians, forming one inverted triangle in the center and three at the corners. Is this the only way? Are there any other ways to divide an equilateral triangle into congruent fourths?
Comment: @JohnDouma Those won't be congruent.
Comment: Take three line segments from one vertex to the opposite edge.
Comment: You can deform the common sides between two triangles in such a way to keep them congruent.
Comment: @Intelligentipauca The issue is, if you're starting from the connect-the-medians solution, you can't get two disjoint pairs of adjacent triangles.
Comment: @AkivaWeinberger You're right, that won't work.
Comment: I think you mean 'the midpoints of the sides", not "the medians". A median is usually a line connecting a vertex to the midpoint of the opposite side.
Answer: Depending on how strict you are with your notion of connectedness, here are four congruent sets whose closures are connected and whose interiors are disjoint:
Comment: Well, the point is called a cut point (https://en.wikipedia.org/wiki/Cut_point). I don't know if there's any name in particular for a space with a cut point.
Comment: Of course, this still leaves open the question of a strongly connected decomposition. (Call a piece _weakly_ connected if the closure of its interior is connected, and _strongly_ connected if its interior is connected; I think that captures the idea well enough.) I strongly suspect this is impossible, which will require an impossibility proof
Comment: Nice! But: if these shapes are all taken to contain the point at which the three pieces meet (which is not possible since that point is the same point for red + green, and for yellow + orange) then they are contractible; otherwise, they are disconnected. Either way, where is the nontrivial $\pi_1$?
Comment: Good point - sloppy wording on my part, I'll edit. Do you know of nice terminology for the notion of not-quite-connectedness that applies here?
Comment: Cool! That's a pretty unexpected configuration. How did you find it?
Comment: I was inspired by [this](https://i.stack.imgur.com/6j9W7.png) decomposition of an equilateral triangle into 5 pieces, and realized that the problem of writing a union of finitely many congruent cells as a collection of subsets related to each other by one of a finite set of isometries could be expressed as a not-too-large SAT instance; I wrote some code to generate such instances, and then plugged it into an off-the-shelf solver in Python. One of the solutions had remarkably few edge-connected components in each piece (compared to e.g. [this](https://i.imgur.com/bn5yW7X.png)).


Can a site be put in maintenance mode without a database?

Question: I'm trying to handle a planned database outage and want Drupal to show the maintenance page during that time.

$conf['maintenance_theme'] = 'exampletheme' and a suitable $conf['_message'] are set in my sites/sitename.com/settings.php
I have a maintenace-page--offline.tpl.php and maintenance-page.tpl.php in sites/all/themes/exampletheme/templates/
I set $conf['maintenance_mode'] = TRUE in sites/sitename.com/settings.php

I hope that Drupal that does not have a database can still bootstrap and display the contents of maintenance-page--offline-tpl.php in this configuration, but in my testing it seems that's not the case. Should this work? Anything I should look into?
Comment: Have you seen this: https://drupal.stackexchange.com/questions/165699/how-to-restore-complete-database-keeping-the-site-in-maintenance-mode-in-drupal ?
Comment: @brotherperes I've read through that now and followed the instructions and it seems it's not working. So, I guess this question is asking for help to understand why this feature is not working for me.
Comment: Well there is one way to find out, Are you thinking what I'm thinking?
Comment: yes. Clone the website to a different location first. I've got the process to do that if you need.
Comment: I'd say no you'd need a database working as the variable that defines if the site is/isn't in maintenance mode is itself stored in the database.

A dirty but quick workaround would be to temporary hack the index.php and do a print 'Site in maintenance mode'; die; or something similar
Answer: What you're describing should work: the maintenance-page--offline.tpl.php template should be called when the database is unavailable.
Drupal does not bootstrap completely when there is no database, but does so partially. When the bootstrap process fails to contact the database, it calls _drupal_log_error() in include/errors.inc, which (indirectly) calls _drupal_maintenance_theme() in includes/theme.maintenance.inc. This is enough to allow hook invocations to work, and to load the theme specified in your $conf['maintenance_theme'] setting.
First, I would verify that _drupal_maintenance_theme() is being called and that it's finding your theme. If you're using a debugger, set a breakpoint there. If not, add this line at the end of the function:
  echo "
Custom theme: $custom_theme
";

If all is ok up to this point, try starting off with the simplest possible maintenance page in maintenance-page--offline.tpl.php, e.g.

Hello world

If that works, and your maintenance page does not, perhaps your maintenance page contains something that attempts to access the database, or invokes a hook that attempts to access the database? Can you post your template and any errors you are seeing?
If the simple maintenance page doesn't work, more debugging would be needed.


Google API - Autocomplete não traz CEP

Question: Estou tentando utilizar os serviços do Google para obter endereçamento.  A ideia é informar o endereço ou cep e carregar os dados logradouro, bairro, cep, cidade e estado.
Já consegui obter a maioria dos dados, porém o cep não está sendo retornado no resultado.  Segue a chamada do serviço e o resultado (sendo que alterei a chave para removi, não vai funcionar.  Porém a URI está ok):
https://maps.googleapis.com/maps/api/place/autocomplete/json?key=removi&components=country:br&input=rua+embaixador+abelardo+bueno
<code>    {
   "predictions" : [
      {
         "description" : "Avenida Embaixador Abelardo Bueno - Barra da Tijuca, Rio de Janeiro - RJ, Brasil",
         "id" : "31fc7076c2289ecf1b100f0a769553d5341ac002",
         "matched_substrings" : [
            {
               "length" : 33,
               "offset" : 0
            }
         ],
         "place_id" : "ElBBdmVuaWRhIEVtYmFpeGFkb3IgQWJlbGFyZG8gQnVlbm8gLSBCYXJyYSBkYSBUaWp1Y2EsIFJpbyBkZSBKYW5laXJvIC0gUkosIEJyYXNpbA",
         "reference" : "CmRUAAAAkQ98koLpBb_VEBonelaZ8iCxYEHtJp0sDeH4gtBzgEnkOs4hpwI7Jaxd0Nq7ZAo1pfsWy9YRLWFkIz0D4EyAZC6ncoK-rQ-dTr9lMWVeFqhZTK50x-zweb3LFcb_zAJDEhD7GsVJdIBYX0_ldipY-272GhSqcdx6p9Ml9BgchUoHct1wglHwqQ",
         "structured_formatting" : {
            "main_text" : "Avenida Embaixador Abelardo Bueno",
            "main_text_matched_substrings" : [
               {
                  "length" : 33,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Barra da Tijuca, Rio de Janeiro - RJ, Brasil"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Avenida Embaixador Abelardo Bueno"
            },
            {
               "offset" : 36,
               "value" : "Barra da Tijuca"
            },
            {
               "offset" : 53,
               "value" : "Rio de Janeiro"
            },
            {
               "offset" : 70,
               "value" : "RJ"
            },
            {
               "offset" : 74,
               "value" : "Brasil"
            }
         ],
         "types" : [ "route", "geocode" ]
      }
   ],
   "status" : "OK"
</code>
Será que o CEP não é retornado mesmo?  Existe algum parâmetro que determine que o CEP precisa ser incluído?
Comment: Até onde eu pesquisei, se você não informar o número da rua, ele não retornará CEP, porque uma mesma rua pode ter diversos CEPs
Comment: Felipe, faz todo sentido.  Mas testando o endereço "Rua Irutim, 86 - Penha Circular, Rio de Janeiro - RJ, Brasil" no link https://jsfiddle.net/api/post/library/pure/ que é fornecido pelo Google, não retorna o CEP.  Obrigado pelo retorno.
Comment: Como posso informar o numero do endereço na URI?
Answer: O problema dessa abordagem é que os dados de localidades da Google nem sempre possuem o CEP, como você deve ter percebido.
Portanto, para trabalhar com CEPs, sugestiono o uso de Web Services como o ViaCep que possui uma base de dados gigantesca com os CEPs do Brasil todo.
Infelizmente, você terá que obter as informações, atualizar os campos e fazer validações manualmente, porém o funcionamento do Web Service é bem simples...
Basta acessar o URL com o endereço e você terá o CEP como retorno.

https://viacep.com.br/ws/RS/Porto%20Alegre/Domingos+Jose+Poli/json/

<code>[
  {
    "cep": "91790-072",
    "logradouro": "Rua Domingos José Poli",
    "complemento": "",
    "bairro": "Restinga",
    "localidade": "Porto Alegre",
    "uf": "RS",
    "unidade": "",
    "ibge": "4314902",
    "gia": ""
  }
]
</code>
Também funciona de forma inversa: você informa o CEP e o serviço retorna detalhes do endereço.

https://viacep.com.br/ws/01001000/json/

<code>{
  "cep": "01001-000",
  "logradouro": "Praça da Sé",
  "complemento": "lado ímpar",
  "bairro": "Sé",
  "localidade": "São Paulo",
  "uf": "SP",
  "unidade": "",
  "ibge": "3550308",
  "gia": "1004"
}
</code>
Para os casos onde uma rua pode ter mais de um CEP, o ViaCep irá retornar um array com todos os CEPs disponíveis daquela rua:

https://viacep.com.br/ws/SP/Sao%20Paulo/Avenida%20Paulista/json/

<code>[
  {
    "cep": "01311-909",
    "logradouro": "Avenida Paulista",
    "complemento": "491",
    "bairro": "Bela Vista",
    "localidade": "São Paulo",
    "uf": "SP",
    "unidade": "",
    "ibge": "3550308",
    "gia": "1004"
  },
  {
    "cep": "01311-905",
    "logradouro": "Avenida Paulista",
    "complemento": "347",
    "bairro": "Bela Vista",
    "localidade": "São Paulo",
    "uf": "SP",
    "unidade": "",
    "ibge": "3550308",
    "gia": "1004"
  },
  {
    "cep": "01310-000",
    "logradouro": "Avenida Paulista",
    "complemento": "até 610 - lado par",
    "bairro": "Bela Vista",
    "localidade": "São Paulo",
    "uf": "SP",
    "unidade": "",
    "ibge": "3550308",
    "gia": "1004"
  },
  {
    "cep": "01310-933",
    "logradouro": "Avenida Paulista",
    "complemento": "2444",
    "bairro": "Bela Vista",
    "localidade": "São Paulo",
    "uf": "SP",
    "unidade": "",
    "ibge": "3550308",
    "gia": "1004"
  }
...
</code>
Comment: Amelco perfeito.  Me parece que a Google não possui os ceps atualizados.  Pensando na colocação do Felipe, podemos ter mais de um cep para a mesma rua, avenida...  Como poderia passar o numero do endereço para o Viacep?  Estou procurando no site e no Google, mas não tive sucesso.  Muito obrigado pela sua solução.
Comment: Acredito que o ViaCep não aceite números na consulta, portanto não será tão preciso quando esperado. Mas consultando pelo nome da rua, cidade e estado, o ViaCep retorna um Vetor com os resultados possíveis.

Ou seja, se a rua tem 2 CEPs, ele deve listar os dois. Cabe a você tratar isso para o usuário.
Comment: Adicionei à resposta essa possibilidade de múltiplos CEPs.

Google API - Autocomplete não traz CEP


When trying to compile a .dll, I'm getting an error with the interface keyword

Question: I have set up a project in Visual Studio to create a .dll. I have included an external library in the project which uses the keyword "interface". This is giving me the following error:

error C2146: syntax error : missing ';' before identifier 'INuiAudioBeam'

These are the lines of code where the error occurs:
#ifndef __INuiAudioBeam_FWD_DEFINED__
#define __INuiAudioBeam_FWD_DEFINED__
typedef interface INuiAudioBeam INuiAudioBeam; //Error on this line
#endif

The above code is part of a header file in the external library I have included. The project builds successfully without any errors when compiling without including the headers for the library (Note: Linking the library does not cause any problems).
What is the solution to this? Is it because I have an external library I'm using to create my dll? Should I create a .lib instead of a dll?
Comment: Are you including `NuiApi.h`? @busy_wait There is no `interface` keyword in managed C++. Managed C++ uses the `__interface` keyword. C++/CLI offer the compound keywords `interface class` and `interface struct`. The `interface` you see here is a COM artifact. Additionally, the Kinect system is implemented in native code and exposes its services through COM to be easily consumable by native and managed code alike.
Comment: Thanks for the help fellas, __interface seemed to work.
Comment: This is not C++ syntax, but Google says MS added the interface keyword to managed C++. You probably need to tell VS the Kinect library is written in managed C++ somehow.
Comment: This is standard spew in any .h file generated by MIDL for a COM interface.  I'd have to guess that you disabled the Microsoft specific language extensions in your project, /Za option.
Answer: If anyone else searches this, the problem is most likely
#define WIN32_LEAN_AND_MEAN

Before
#include <windows.h>

Remove the define, make sure your including windows.h, and that should define interface keyword for you
Comment: For who is trying to build a DLL with VisualStudio, the `#define WIN32_LEAN_AND_MEAN` line is in the stdafx.h file. Just comment it and everything will work.
Answer: You can get C2146 with indictment of the interface keyword. It may be confusing as to how a keyword may be undefined, especially that in other compilation units or projects that use the same header file - the inclusion of which brought about the problem - all goes smooth. However, the apparent keyword "interface" is still a compiler #define directive. It just happens to be buried inside a header file that a few developers have reasons to inspect: the <objbase.h>. There it is defined in two steps:
#define __STRUCT__ struct
#define interface __STRUCT__

Since the <objbase.h> is included by multiple other header files - such as ole2.h, oleauto.h, and a slew of ATL headers - you may be surprised with this error when none of those headers were included in the current compilation unit.


Created folder is not visible in the sdcard folder

Question: I want to create the pictures folder and in that i want to add flower.png image  in the sdcard.
I have 2 buttons in my layout file one is  save and load when I click on save button its must save in the sd card.With the below code,Its displaying a toast message "data written successfully". But I can't see the created folder and file on the sdcard in file explorer. only sd card folder is visible to me.when I click on load button it must gather the saved image from sdcard and set in the image view.But here also im getting only toast message "data written successfully in the image view.But the imageview with loaded images is not displaying can any body help me ?
This is may layout file:
    main.xml

This is my activity file:
public class AndroidExternalStorageActivity extends Activity implements OnClickListener {
    Button btnSave,btnLoad;
    Bitmap bmp;
    String s;
    InputStream inputstream;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnSave = (Button)findViewById(R.id.save);
        btnLoad = (Button)findViewById(R.id.load);
        btnSave.setOnClickListener(this);
        btnLoad.setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        if(v.getId()==R.id.save)
        {

                 s=Environment.getExternalStorageState();
                if(s.equals(Environment.MEDIA_MOUNTED))
                {
                    File root = Environment.getExternalStorageDirectory();
                    File f = new File(root+ "/pictures/", "logos.png");
                    f.mkdir();

                    try {
                        //fis = new FileInputStream(R.drawable.logos);
                        InputStream inputStream = getAssets().open("logo.jpg");
                    } catch (FileNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                        try
                 {
                   FileOutputStream fos=new FileOutputStream(f);

                   int read = 0;
                    byte[] bytes = new byte[1024];
                    while ((read = inputstream.read(bytes)) != -1) {
                        fos.write(bytes, 0, read);
                    }
                   fos.flush();
                   fos.close();

                   } catch (Exception e) {
                   Log.e("saveToExternalStorage()", e.getMessage());

                   }
                   //DataOutputStream dos=new DataOutputStream(fos);
                   //dos.writeBytes("Hello friends how are you,welcome to android session");
                   Toast.makeText(this,"Data Written successfully.." ,Toast.LENGTH_LONG).show();

    }
        }

    else if(v.getId()==R.id.load)
    {
                        String s1=Environment.getExternalStorageState();
                        if(s1.equals(Environment.MEDIA_MOUNTED))
                        {
                            try
                            {
                             File root1 = Environment.getExternalStorageDirectory();
                             File f1 = new File(root1 + "/pictures/", "logos.png");
                             ImageView iv=(ImageView)findViewById(R.id.imageView1);
                                Bitmap bm=BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ "/pictures/logos.png");
                                iv.setEnabled(true);
                                iv.setImageBitmap(bm);

                             Toast.makeText(this, "image is uploaded successfully in imageview" ,Toast.LENGTH_LONG).show();
                             //dis.close();
                            }
                            catch(Exception e)
                            {
                                System.out.println(e);

                        }
                    }

        }
    }
            }

 I also added the following permissions in my manifest file:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">

    </uses-permission>

     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">

     </uses-permission>

Answer: You need to create directory and file separately.
File directory = new File(root, "pictures");
directory.mkDirs();
File f = new File(directory, "logos.png");
f.createNewFile();

You can also get directory like this
File directory = Environment.getExternalStorageDirectory("pictures");
directory.mkDirs();

Answer: Make sure you have added the Previleges in AndroidManiFest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This will provide you complete access to write onto your sdCard on Android.
Answer: Update your save button onClick option as follows:

First create Folder Directory then create File
There has a typo, at first you are creating InputStream object named inputstream but you are creating another InputStream object named inputStream where S is capital. You should not create it second time.

Compare and update your code with the following updated code snippet, I think you will get your problem solved.
if (v.getId() == R.id.save) {

    s = Environment.getExternalStorageState();
    if (s.equals(Environment.MEDIA_MOUNTED)) {

        File root = Environment.getExternalStorageDirectory();
        File fileDir = new File(root.getAbsoluteFile() + "/pictures/");
        fileDir.mkdir();
        File f = new File(fileDir, "logos.png");

        try {
            inputstream = getAssets().open("logo.jpg");
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream fos = new FileOutputStream(f);

            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = inputstream.read(bytes)) != -1) {
                    fos.write(bytes, 0, read);
            }
            fos.flush();
            fos.close();

        } catch (Exception e) {
            Log.e("saveToExternalStorage()", e.getMessage());
        }

        Toast.makeText(this, "Data Written successfully..", Toast.LENGTH_LONG).show();
    }
}

Comment: sorry @Hamid i didnt get you. Ill surely accept your answer but im not getting the procedure can you explain me clearly?
Comment: I have already explained those facts which should be resolved.


UICollectionViewCell - Edit mode

Question: I am working on an app in which i've implemented edit mode in UICollectionView.I am trying to implement something like this :

when i click on edit button,camera button and eye button should get hidden and delete and rename button should appear like this :

And after editing,when i click on "Done" button,delete button and rename button should get hidden and camera button and eye button should get appeared again. I've tried it but it is giving me some weird output. Everything is working fine except this "edit" button functioning. Can anyone suggest me any way to resolve this. Suggestions will be appreciated. Please provide some suggestions. Thanks in advance.
Comment: what do you mean by "edit" button functioning?
Comment: can any one help me regarding this????
Answer: As per your explanation about your task,you have filled this collection
view by an NSMutableArray. So you can achieve your task by filling all
button on their respective UICollectionViewCell using array of delete
images ,array of rename images,array of camera images and array of eye
images . Just set flag for each particular condition.And when you click on
'edit' button,  on the basis of that flag ,you can fill your collection
view. Just try this. It might help you.
Comment: That is really amazing !! I just needed to reload my collectionview on edit button click after implementing this logic. Your idea solved my problem..

UICollectionViewCell - Edit mode