Can mean plus one standard deviation exceed maximum value?

Question: I have mean 74.10 and standard deviation 33.44 for a sample that has minimum 0 and maximum 94.33.
My professor asks me how can mean plus one standard deviation exceed the maximum.
I showed her many examples about this, but she doesn't understand. I need some reference to show her. It could be any chapter or paragraph from a statistics book that talks particularly about this.
Comment: An interesting example is the sample (0.01,0.02,0.98,0.99). Both the mean plus the standard deviation and the mean minus the standard deviation lie outside [0,1].
Comment: Why do you want to add (or subtract) one standard deviation from the mean? The SD is a measure of the spread of the data. Did you want the standard error of the mean instead perhaps?
Comment: I don't want to add or subtract, the one that wants this is my professor. That is the way she understands the standart deviation
Comment: Maybe she's just thinking of a Normal distribution?
Answer: Certainly the mean plus one sd can exceed the largest observation.
Consider the sample 1, 5, 5, 5  -
it has mean 4 and standard deviation 2, so the mean + sd is 6, one more than the sample maximum. Here's the calculation in R:
> x=c(1,5,5,5)
> mean(x)+sd(x)
[1] 6

It's a common occurrence. It tends to happen when there's a bunch of high values and a tail off to the left (i.e. when there's strong left skewness and a peak near the maximum).
--
The same possibility applies to probability distributions, not just samples - the population mean plus the population sd can easily exceed the maximum possible value.
Here's an example of a $\text{beta}(10,\frac{1}{2})$ density, which has a maximum possible value of 1:

In this case, we can look at the Wikipedia page for the beta distribution, which states that the mean is:
$\operatorname{E}[X] = \frac{\alpha}{\alpha+\beta}\!$
and the variance is:
$\operatorname{var}[X] = \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\!$
(Though we needn't rely on Wikipedia, since they're pretty easy to derive.)
So for $\alpha=10$ and $\beta=\frac{1}{2}$ we have mean$\approx 0.9523$ and sd$\approx 0.0628$, so mean+sd$\approx 1.0152$, more than the possible maximum of 1.
That is, it's easily possible to have a value of mean+sd large enough  that it cannot be observed as a data value.
--
For any situation where the mode was at the maximum, the Pearson mode skewness need only be  $<\,-1$ for mean+sd to exceed the maximum, an easily satisfied condition.
--
A closely related issue is often seen with confidence intervals for a binomial proportion, where a commonly used interval, the normal approximation interval can produce limits outside $[0,1]$.
For example, consider a 95.4% normal approximation interval for the population proportion of successes in Bernoulli trials (outcomes are 1 or 0 representing success and failure events respectively), where 3 of 4 observations are "$1$" and one observation is "$0$".
Then the upper limit for the interval is $\hat p  + 2 \times \sqrt{\frac{1}{4}\hat p \left(1 - \hat p \right)} = \hat p  + \sqrt{\hat p (1 - \hat p )} = 0.75 + 0.433=1.183$
This is just the sample mean + the usual estimate of the sd for the binomial ... and produces an impossible value.
The usual sample sd for 0,1,1,1 is 0.5 rather than 0.433 (they differ because the  binomial ML estimate of the standard deviation $\hat p(1-\hat p)$ corresponds to dividing the variance by $n$ rather than $n-1$). But it makes no difference - in either case, mean + sd exceeds the largest possible proportion.
This fact - that a normal approximation interval for the binomial can produce "impossible values" is often noted in books and papers. However, you're not dealing with binomial data. Nevertheless the problem - that mean + some number of standard deviations is not a possible value - is analogous.
--
In your case, the unusual "0" value in your sample is making the sd large more than it pulls the mean down, which is why the mean+sd is high.

--
(The question would instead be - by what reasoning would it be impossible? -- because without knowing why anyone would think there's a problem at all, what do we address?)
Logically of course, one demonstrates it's possible by giving an example where it happens. You've done that already. In the absence of a stated reason why it should be otherwise, what are you to do?
If an example isn't sufficient, what proof would be acceptable?
There's really no point simply pointing to a statement in a book, since any book may make a statement in error  - I see them all the time. One must rely on direct demonstration that it's possible, either a proof in algebra (one could be constructed from the beta example above for example*) or by numerical example (which you have already given), which anyone can examine the truth of for themselves.
* whuber gives the precise conditions for the beta case in comments.
Comment: +1 The Beta example is a nice idea. In fact, provided $0\lt\beta\lt 1$ and $\alpha \gt \beta(1+\beta)/(1-\beta)$, *any* Beta$(\alpha,\beta)$ distribution will have mean+sd exceeding $1$.
Comment: @tomka I have attempted to help many students in a similar position. I eventually learned the (possibly unsurprising) rule of thumb that it's effectively impossible to teach a supervisor anything through the medium of their student.
Comment: She's right that a percentage > 100% makes no sense in your situation. The problem is actually the unstated premise that adding one sd to the mean should make sense in this context, when it *doesn't*. That's where I believe your difficulty originates. If we understood where the premise came from, it might lead to a better resolution. It's possible that the simple fact is stated in a book somewhere (it's a trivial observation, though, so it's possible it isn't, either), but I doubt it will ever be put in a way that will satisfy her, because her false premise is the source of the problem.
Comment: Indeed - my minor point is that this curiosity is a result of what standard deviations represent for strongly non-symmetric distributions rather than a result of taking a sample. But in general, I think your answer is excellent
Comment: Let me explain further. I am looking for accuracy percentage of particular appliance used for correction of teeth.  And this appliance performed accuracy percentage for 7 tooth as follow: %76,19, %77,41, %94,33, %91,06, %0, %87,77, %91,96. My professor adds one standart deviation to mean and states that the result can not exceed maximum value even %100 because %100 is the maximum accuracy percentage that appliancek can perform.
Comment: What's an "accuracy percentage"? I don't know what that term means. Why is your professor adding a standard deviation to the mean? Why should that mean anything at all? Her mistake is in thinking that adding a standard deviation to the mean should necessarily yield a value that is possible for a percentage. Why would it?
Comment: Note that your numerical example fits my description - you have a bunch of high values, and a tail off to the left (suggested by the low value of 0). That's exactly when this can happen. There's really no good reason to expect adding any number of standard deviations (even a fraction of one) to the mean should respect the 100% boundary.
Comment: Firstly let me explain "accuracy percentage". For example you want to achieve 1 mm movement of tooth. By using an appliance you achieve only 0,40 mm movement. The accuracy percentage for this example is %40
Comment: Boyun -- Thanks for that. Why is the professor adding a standard deviation to the mean?
Comment: And why does she wants to add one standart deviation to mean I don't understand...
Comment: That is the way she thinks about standart deviation unfortunately and I can not change her mind
Comment: How would you compute the accuracy percentage if the achieved movement was 1,20 mm ?
Comment: In my study planned movement never exceeds achieved movement
Comment: All I want is to show her a reference. I don't want to spell the words that she deserve but without making her understand this I can not move further...
Comment: Thank you again for your contribution. Everything is clear for me. Now a new trial begins for me - to make her understand. I will show her your comments. Thanks a lot
Comment: I'd be happy to discuss in chat to clear anything up.
Comment: Pedantically, you and R are using the $n-1$ sample standard deviation calculation.  If the population is $1,5,5,5$ then its standard deviation is $\sqrt{3} \gt 1$ so your example is still valid.
Comment: @Henry I was deliberately using the usual sample standard deviation there; the OP's problem involves sample mean and standard deviation. But yes, the $n$-divisor version also has the same issue.
Comment: @Glen_b I think she wants to add and substract one SD to mean because of her vague sense of Chebychev's inequality. From what I read I don't think she knows about it in particular actually. Instead she thinks about the special case of a normal distribution for which the OP's observation would not be possible. Having said that she also does not know enough about statistics to supervise this student's project.
Answer: Per Chebyshev's inequality, less than k -2 points can be more than k standard deviations away. So, for k=1 that means less than 100% of your samples can be more than one standard deviation away.
It's more interesting to look at the low bound. Your professor should be more surprised there are points which are about 2.5 standard deviations below mean. But we now know that only about 1/6th of your samples can be 0.
Answer: In general for the Bernoulli random variable $X$, that takes the value $1$ with probability $0<p<1$ and the value $0$ with probability $1-p$, we have
$$E(X) = p,\;\; SE(X) = \sqrt {p(1-p)}$$
And we want
$$E(X)+ SE(X) > 1 \Rightarrow p +\sqrt {p(1-p)} >1$$
$$\Rightarrow \sqrt {p(1-p)} > (1-p)$$
Square both sides to obtain
$$p(1-p) > (1-p)^2 \Rightarrow p > 1-p \Rightarrow p > \frac 12$$
In words, for any Bernoulli random variable with $p>1/2$ the theoretical expression $E(X)+ SE(X) > \max X$ holds.
So for example, for any i.i.d. sample drawn from a Bernoulli with, say, $p=0.7$,  in most cases the sample mean plus the sample standard deviation will exceed the value $1$, which will be the maximum value observed (bar the case of an all-zeros sample!).
For other distributions we always have the opposite direction in the inequality, e.g. for a Uniform $U(a,b)$, it is always the case that $E(U)+ SE(U) < \max U=b$.
 Therefore, no general rule exists.
Answer: The essence of the problem may be that your distribution is not a normal distribution which a standard deviation assumes.  Your distribution is likely left skewed, so you need to transform your set into a normal distribution first by picking a suitable transform function, this process is called transformation to normality.  One such function candidate in your case might be a mirrored log transform.  Once your set satisfies a normality test you may then take the standard deviation.  Then to use your 1$\sigma$ or 2$\sigma$ values you must transform them back into your original data space using the inverse of your transform function.  I'm thinking this is what your professor was hinting at.
Comment: This is a nice contribution. I'm not sure that the SD really "assumes" a normal distribution, though.
Comment: "Distribution fitting" and finding a transformation to normality are distinct procedures with different aims.
Comment: The standard deviation is perfectly natural as a summary for many non-normal distributions, such as the Poisson or binomial, if only because the variance is.
Answer: It is quite common that people (including your professor) make this mistake.
People often do calculations assuming that one has a large sample of an ideal normal distribution. At a certain moment they start thinking that alle and everything in life shows a normal distribution. That is not true!
Especially when a distribution is not symmetric one then gets unexpected results.
People also tend to forget that in small populations (/small colletions of numbers) never have a normal distribution. It only starts to come close to a normal distribution if both the number of samples is high, and if indeed the underlaying phenomena cause the distribution to be pure and normal.
Answer: I would like to emphasise with this answer why I think people think of the normal distribution when the subject of standard deviation comes up, like other people have already mentioned in other answers for this question. For a lot of people, indeed the first thing that comes to mind when they think of standard deviation is the figure below (or one variant of it):

The two sections in dark below are, as you can see in the x-axis legend, one standard deviation to the right or to the left of the mean, which is zero here. When someone else mentions that one standard deviation from the mean can be outside the range of of values of this distribution mean(X)+sd(X) > max(X) (in R code), naturally they freeze. How come!?
Maybe your professor went to R and did something like:
set.seed(2021)
N <- 10000
X <- rnorm(n=N, mean=74.10, sd=33.44)
mean(X)+sd(X) > max(X)

This returns false, but if you check, the max/min values do not match yours. What I did was to generate a normal distribution, as one can see in the plot below.
library(ggplot2)
ggplot() +
  aes(X) +
  geom_histogram(binwidth=1)

Many people are introduced to the concepts of normal distributions, or standard deviations, with a figure like the first one.
You can easily generate some distributions that will have the mean+sd outside the range of values in a distribution, as many other colleagues have answered in this post, to at least prove it is possible.
As you've probably already heard, looking at a scatter plot or histogram of your data usually helps a lot. If your professor had had a look at the histogram of your data, I think s/he would be at least a bit more inclined to accept the idea :-)
Comment: Could you explain how this answers the question?  Your only germane remark appears at the end, but adds nothing to existing answers in this thread.
Comment: I hate to see good work deleted and would instead suggest stating explicitly--perhaps at the beginning of your post--what it is intended to accomplish and how it is related to the question.
Comment: There's still a bit of a disconnect.  The reference to normal distributions comes out of the blue: I don't see any reference to it in the question.  Three *answers* do address this issue, so perhaps you might want to acknowledge them and state what you are adding to what they have already said.
Comment: My intention was to emphasise why many people think of the normal distribution when standard deviation is mentioned, and how the author of the question could explain to the professor with some R code and image. I don't honestly think it adds a lot, but I still think there is some complement to what has been said. If you think it's better to delete the answer, please let me know.
Comment: Done, @whuber. What do you think?
Comment: I added a reference, mentioning previous answers :-)


Index notation for unitary matrices

Question: I was wondering if someone could confirm this for me. I'm attempting to convert a paper into matrix notation but I keep getting confused.
I first have a unitary matrix that makes a transformation on some set of vectors (the unitary matrix is made of only real values) such that
$$b_{n} = \sum_mU_{nm}a_{m}.$$
If I then take the transpose on either side such that
$$U^{-1}b = (U^{-1}U)a = Ia,$$
I have in index notation that \begin{align*}
\sum_{n} U^{\dagger}_{kn}b_{n} &= \sum_{m} \sum_{n} U^{\dagger}_{kn}U_{nm}a_{m} \\
\sum_{n} U^{\dagger}_{kn}b_{n} &= \sum_{m}(U^{\dagger}U)_{km}a_{m}
\end{align*}
where
$$
(U^{\dagger}U)_{km} = δ_{km}
$$
therefore we end up with;
$$
\sum_{n} U^{\dagger}_{kn}b_{n} = a_{k}
$$
I know I can re-label any of the indices as long as I am consistent on both sides, however, what I need to know here is since $U$ is real then the Hermitian conjugate just simplifies to the transpose and transposing a matrix with index notation means just flipping the indices (or changing the sum), since when you do the transpose explicitly you're really just summing over the other index (i.e., when you have a vector it's the difference between it being a row or a column vector). Thus, the following should be equivalent:
$$
\sum_{n} U^{\dagger}_{kn}b_{n} = \sum_{n} U_{nk}b_{k}
$$
Does this seem reasonable? It looks to me from my beginning point it is as the original U is summing over the second index, m. Where as the final expression is summing over the first index, n.
thanks for taking a look guys, if you want any information on the paper and such that's not a problem
Answer: As you note, $U$ is unitary so $U^\dagger$ = $U^{T}$, and so \begin{align*}
a_k &= \sum_n \left[U^\dagger\right]_{kn} b_n \\
&= \sum_n \left[U^T\right]_{kn} b_n \\
&= \sum_n U_{nk} b_n.
\end{align*}
That is to say, $b_k$ on the right-hand side of your expression should be $b_n$.

Index notation for unitary matrices


Como chamar uma function em JavaScript dentro de um Razor?

Question: Estou programando em ASP.NET MVC e tenho um formulário de cadastro. Preciso verificar se a data de nascimento é válida, ou seja, se é menor que a data de hoje. Eu tenho o script mas não sei chamá-lo dentro da form abaixo, alguém poderia me ajudar?

   Data de Nascimento
   @Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control" } })
   @Html.ValidationMessageFor(model => model.DataNascimento, "", new { @class = "text-danger" })

Peguei esse script de uma outra resposta para implementar:
function verificaData()
{
    var dt = new Date();
    var dia = dt.getDay();
    var mes = dt.getMonth();
    var ano = dt.getFullYear();

    if(dia > 0 && dia < 10) dia = "0" + dia;
    if(mes > 0 && mes < 10) mes = "0" + mes;

    var dataAtual = dia + "/" + mes + "/" + ano;
    var vDia = document.model.DataNascimento.value.substr(0,2);
    var vMes = document.model.DataNascimento.value.substr(3, 2);
    var vAno = document.model.DataNascimento.value.substr(6, 5);

    if(vDia > dia ||
       vMes > mes ||
       vAno > ano)
    {
        alert("Data Inválida");
        document.model.DataNascimento.value = dataAtual;
        document.model.DataNascimento.focus();
    }
}

Comment: Isso é simples...basta mudar o botão de submit para um link (elemento a) e com uma função que pegue o clique, captura a data informada, chama a tua função é depois da um submit manual...amanhã vou estar bem enrolado...não sei se consigo lhe manda um exemplo mas depois de amanhã me cobre que mando
Answer: O seu form será enviado ao Controller quando o usuário der submit.
Lá, você pode chamar sua função para validar a data e, caso esteja errado, retornar ao form com mensagem de erro.
Answer: Adicione ao atributo onchange do seu elemento a função verificaData()
@Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control", @onchange = "verificaData()" } })

Answer: O melhor evento para verificar a data é a saída do campo, feita pelo evento onblur:
@Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control", @onblur = "verificaData()" } })


Question about the supremum of a set

Question: Let
$$X=\sup\left\{\left|\frac{a\sqrt{2}}{2}+b\right|^2+\left|\frac{a\sqrt{2}}{2}-b\right|^2+|b|^2;\;\;(a,b)\in \mathbb{C}^2,\;|a|^2+|b|^2=1\right\}.$$

How can I show that $$X\neq 1\;?$$
Answer: With $a=0$ and $b=1$ $\Rightarrow$ $X\geq3$ ?

Question about the supremum of a set


C programming: casting a void pointer to an int?

Question: Say I have a void* named ptr. How exactly should I go about using ptr to store an int?  Is it enough to write
ptr = (void *)5;

If I want to save the number 5? Or do I have to malloc something to save it?
Comment: Why, for the goodness sake, do you want to do this?
Comment: Do you want a pointer to memory location 5 or to the number 5? There is a big difference between the two.
Comment: What do you want to do? We need to see the bigger picture to help you. Now I can only guess that the code you posted is probably not doing what you would expect it to do.
Comment: Yes, what you have there will work just fine. Whether it's a good idea or not depends on what exactly you're trying to do, but there's no problem with that code as it is.
Comment: The `cast` is sufficient..................
Comment: We do this for passing undefined data to callback functions
Answer: You're casting 5 to be a void pointer and assigning it to ptr.
Now ptr points at the memory address 0x5
If that actually is what you're trying to do .. well, yeah, that works. You ... probably don't want to do that.
When you say "store an int" I'm going to guess you mean you want to actually store the integer value 5 in the memory pointed to by the void*. As long as there was enough memory allocated ( sizeof(int) ) you could do so with casting ...
void *ptr = malloc(sizeof(int));
*((int*)ptr) = 5;

printf("%d\n",*((int*)ptr));

Comment: I do this all the time, when working with a framework that stores "User Data" as a `void*`, but all I need is an int.
Comment: As long as someone after you doesn't accidentally dereference it later, I agree that works. It just makes me cringe a bit for that reason.
Comment: And I knew there was something else that was bugging me - it's not portable. http://developer.gnome.org/glib/2.28/glib-Type-Conversion-Macros.html
Comment: @MooingDuck Ah! That's exactly what I was running into. So it's a proper use case. Thanks.
Comment: If the OP had to ask whether to use a malloc or not, it means that he needs to use a malloc.  One does not simply walk into storing ints in pointer spaces.
Answer: That will work on all platforms/environments where sizeof(void*) >= sizeof(int), which is probably most of them, but I think not all of them. You're not supposed to rely on it.
If you can you should use a union instead:
union {
    void *ptr;
    int i;
};

Then you can be sure there's space to fit either type of data and you don't need a cast. (Just don't try to dereference the pointer while its got non-pointer data in it.)
Alternatively, if the reason you're doing this is that you were using an int to store an address, you should instead use size_t intptr_t so that that's big enough to hold any pointer value on any platform.
Comment: No, don't use `size_t`. It isn't guaranteed to be able to hold all possible addresses of pointers. `intptr_t` and `uintptr_t` are there for that since C99. In C90 you're out of luck. I can even give you a platform where `size_t` is 16 bits wide and pointers are 32 bits wide: x86 in real mode using memory model `HUGE`, `FAR` and `COMPACT`. `size_t` can be seen as the type used for addressing arrays, nothing more.
Answer: A pointer always points to a memory address. So if you want to save a variable with pointer, what you wanna save in that pointer is the memory address of your variable.


Surface of graph of a function.

Question:
Let $G:=\{(x,y,z)\in\mathbb{R}^3:|x|<|z|^2,|y|<|z|,0<z<1\}$ and $f:G\to\mathbb{R},f(x,y,z)=2x+2y+z^3$. Calculate the surface of the graph of f.

We recently got introduced to Stokes' theorem and the Divergence theorem, but I'm still struggling immensely with applying it. I think this a problem I have to apply the Divergence theorem to, but I'm completely lost and need help.
After thinking about it more I found the following:
We have the function $f:G\to\mathbb{R}$. So we can define our Manifold $M$ as the image of $\phi:G\to\mathbb{R}^4,x\mapsto (x,f(x))$, which therefore is of dimension 3. We see that $D\phi^TD\phi=1+Df^TDf$. Thus we have that the area of the graph of $f$ is the surface of $M$, given by $\int_M dS_3=\int_G\sqrt{det(1+Df^TDf)}\,d\lambda_k(x)=\int_G3\sqrt{z^4+1}\,d\lambda_k(x)$. Then, we see that $G=\{(x,y,z)\in\mathbb{R}^3:-z^2<x<z^2,-z<y<z,0<z<1\}$. Solving the integral gives us the answer $2$.
Comment: I'm sorry, do you mean calculate the surface integral of $f$ in the graph of $f$?
Comment: This is the exact wording of the problem. The surface of $f$ is 3-dimensional. My thoughts were that I have to define $F(x,y,z)=(x,y,z,f(x,y,z))$ and then use one of the theorems.
Comment: No, it isn't. It's 2-dimensional, that's why you could (depending on what you want to compute) use the divergence or Stokes's theorem. Actually you have a whole family of surfaces, given by $2x+2y+z^3 =c$ for all $c \in \mathbb{R}$. I'm still lost at what the question wants.
Comment: Why is it 2-dimensional? If you plot a 2-dimensional function $f(x,y)$, you get a 3-dimensional graph $(x,y,f(x,y))$. Thus its surface is 2-dimensional.
Comment: Okay, perhaps this additional comment will enlighten us. The graph of $f$ lives in $\mathbb{R}^4$, which the surface defined implicitly by $f$ lives in $\mathbb{R}^3$, and what more, it is 2 dimensional. For comparison, think of $f(x,y,z) = x^2+y^2+z^2$ which is the family of spheres centered at the origin.
Comment: I think I understand what you mean now. You're using in the first sense I mentioned in the previous comment. Can't use Stokes's or Divergence theorems since they apply in $\mathbb{R}^3$.
Comment: Actually, the Divergence theorem applies in $\mathbb{R^n}$.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12714/discussion-between-fantini-and-blst)
Answer: For each point $(x,y,z)$ in $D$ we get a number $\mathrm{f}(x,y,z)$ given by
$$\mathrm{f}(x,y,z)=2x+2y+z^3$$
The graph of the function $\mathrm{f} : D \to \mathbb{R}$ is, for ${\bf x} = (x,y,z)$, defined to be as follows:
$$\{({\bf x},v) \in D \times \mathbb{R} : v=\mathrm{f}({\bf x})\}$$
This is the usual definition that we are used. For example, in the plane, the graph of $x^2$ is given by
$$\{(x,y) \in \mathbb{R}^2 : y = x^2 \}$$
You need to describe the graph of your $\mathrm{f}$ given the unusual nature of $D$.
I would start by looking looking at the boundary cases, e.g. $|x| = |z|^2$, $|y|=|z|$ and $z=0$ or $z=1$.
Comment: @blst As you can tell by the time I posted my reply: I was busy typing your reply while your comments conversation was underway. I would recommend that you start by looking at the boundary cases: $|x|=|z|^2$, $|y|=|z|$ and $z=0$ or $z=1$.
Comment: @blst Let $z=t$ where $0 < t < 1$ then ask yourself what $|y|<|z|$ and $|x|<|z|^2$ give you for each $t$. Then, what does that translate to in $(x,y,z,2x+2y+z^3)$? Other than actually answering the question, I don't see what else I can say.
Comment: @blst How much time and thought have you given to this problem? I have given you a solution. Try *thinking* about it. What exactly do you expect? For me to solve your problem for you? (I will not do your homework for you. Sorry.) For me to write one line and then you suddenly understand? I would be a millionaire if I could make people understand university mathematics without them having to think.
Comment: @blst You haven't been asked to integrate. You have been asked to find a surface. That will mean the boundary of a region. Stokes' Theorem relates an integral over a region to another integral over a boundary:

$$\int_{R} \mathrm{d}\omega = \int_{\partial R} \omega$$

Before you can even try to use this, you need to find the boundary of the region, i.e. find the $\partial R$. As far as I can tell, the graph of $\mathrm{f}$ is the region $R$ and you need to find the boundary $\partial R$.
Comment: As we figured out above, we have that the graph of $f$ is $(x,y,z,2x+2y+z^3)$ where $(x,y,z)\in D$ which lives in $\mathbb{R}^4$ and thus it's surface is 3-dimensional. After this, I'm still lost.
Comment: For the boundary cases we have $z=0$, then $x=0,y=0$. You pointed out $z=1$. If we have $x=\pm 1$, we have $z=1$. Same with $y$. Where do I go from here?
Comment: Well, I'm still completely lost. I think it would help to see an actual answer to this.
Comment: The thing is I don't even know _what_ im supposed to integrate here.
Comment: The surface should be ${(x,y,z)\in\mathbb{R}^3:z=1,|x|<|z|^2,|y|<|z|\}\union\{(x,y,z)\in\mathbb{R}^3:0<z<1,|x|=|z|^2,|y|=|z|}. I think it's a half-ellipsoid.
Answer: Sorry, not an answer, but just to clarify the problem  after reading the comments above, let's read http://en.wikipedia.org/wiki/Surface: "In mathematics ... a surface is a two-dimensional ... manifold. The most familiar examples are those that arise as the boundaries of solid objects in ordinary three-dimensional Euclidean space R3 — for example, the surface of a ball".
The graph of $f$ defined above is a 3-dimensional region (living in $\mathbb{R}^4$) and bounded by the surfaces we are asked to "calculate".

Surface of graph of a function.


How to find the centerpoint of a circle that intersects two points where the centerpoint is on the X axis

Question: So say I have two points
(0, 5) and (-10, 0)
I want to find the centerpoint of a circle that intersects these two points...
With the additional requirement that the Y component is 0 and the X component is negative.
Answer: Let $h$ be the x-coordinate of the center of the circle. If you draw a picture, then you will see that the radius of the circle is then $h-(-10) = h+10$. On the other hand the radius of the cicle is also the distance from the center to the point $(0,5)$, which is $\sqrt{(h-0)^2 + (0-5)^2}$.
You can set these equal to each other and solve for $h$.


How to control checkbox Situation in List View asp.net C#

Question: I'm control check box checked or not in GridView like in the below
foreach (GridViewRow row in GridView2.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("CheckBox1");

                if (cb.Checked == true)
                {
                    if (cb != null && cb.Checked)
                    {
                           //Some Stuf..

                    }
                }
              }

But i can't find the way how to control check box in list view Because Listview doesn't have extension "Row" like in the grid view could you help me about it?
My listview code written in the below
<asp:ListView ID="ListView2" runat="server">

             <LayoutTemplate>

                <asp:PlaceHolder ID="itemPlaceholder" runat="server" />

        </LayoutTemplate>
        <ItemTemplate>

                         <asp:CheckBox ID="CheckBox1" runat="server" />
                        City: <%# Eval("eeee") %>

                        Postal Code: <%# Eval("dddd") %>

                        Country: <%# Eval("cccc")%>

                        Phone: <%# Eval("bbbb")%>

                        Fax: <%# Eval("aaaa")%>

        </ItemTemplate>

            <LayoutTemplate>

                    <asp:DataPager ID="DataPager1" runat="server">
                        <Fields>
                            <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" />
                            <asp:NumericPagerField />
                            <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" />
                        </Fields>
                    </asp:DataPager>

            </LayoutTemplate>

        <EmptyDataTemplate>
            Sonuç Bulunamadı
        </EmptyDataTemplate>

        </asp:ListView>

Thank you
Answer: foreach (ListViewItem row in ListView2.Items)
    {
        CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
            if( cb != null)
            {
                if (cb.Checked == true)
                {
                       //Some Stuf..
                }
            }
    }

Comment: Thank you that's what i'm looking for =) . It's very very helpfull to me


How do I post a PDF?

Question: I followed these steps to post a PDF file to Drupal.

Enable JSON API to create at  admin/config/services/jsonapi

Enable the media POST resource
Media /media/{media}/edit: GET, PATCH, DELETE
      /entity/media: POST

Methods: POST, formats: json: authentication: cookie

Create an Angular application and embed it in the Drupal page as a block

The Angular application captures the page using jspdf and embeds the image in the PDF. Instead of using an interceptor, I'm getting a token with each request.
this.certificateService.getCsrf().subscribe(token => {
  this.certificateService.uploadMedia(pdf.output('blob'), fileName, token).subscribe({
    complete: () => {
      console.log('posted media');
    }
  })
});

getCsrf() grabs the token as text.
getCsrf(): Observable<string> {
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

  return this.httpClient.get(this.host + '/session/token',{ headers: headers, responseType: 'text'}).pipe(catchError(this.handleError<any>('token')))
}

uploadMedia() tries to post the PDF file to media to Drupal.
uploadMedia(pdf: Blob, name: string, token: string): Observable<any> {
  const formData: FormData = new FormData();
  formData.append('certificate', pdf, name);
  const headers = new HttpHeaders();
  headers.set('Accept', 'application/vnd.api+json');
  headers.set('X-CSRF-Token',token);
  // headers.set('Content-Type','application/octet-stream');
  headers.set('Content-Type','application/hal+json');
  headers.set('Content-Disposition',`file; filename=${name}`);

  return this.httpClient.post(this.host + '/entity/media', formData, {headers: headers})
    .pipe(
      catchError(this.handleError<any>('uploadMedia'))
    );
}

The error I get is 415 Unsupported media type.

I am using Angular 13 and Drupal 9.
I looked at the Drupal error log; it reports the following exception.

Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException: No route found that matches "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryYAzO5lNTfgLQwQq9" in Drupal\Core\Routing\ContentTypeHeaderMatcher->filter()

Just setting the Content-Type header does not always alter the content type header that is posted. e.g. With both axios and angular http if you post a FormData array you will get a multi-part form even though you the header at the call level is application/octet-stream
Using axios within angular as follows result in 'application/octet-stream':
import Axios from 'axios-observable';
Axios.defaults.headers.post['X-CSRF-Token'] = token;
return Axios.post(this.host + '/entity/media', pdf, {
  headers: {
    Accept: `application/json, text/plain, */*',
    Authorization: `Basic ${basic}`,
    Cookie: ${cookie}; XDEBUG_SESSION=13681',
    'Content-Type': 'application/octet-stream',
  }
});

Passing raw PDF data results in 'application/pdf'
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/octet-stream');
return this.httpClient.post(this.host + '/entity/media', pdf, {headers: headers})
  .pipe(
    catchError(this.handleError<any>('uploadMedia'))
);

Reviewing the rest services page admin/config/services/rest, the allowed content format is 'json'
Debugging confirms that symfony is checking this value

Trying a REST interface i.e. '/jsonapi/media/document/field_media_document/'
Yes there is a 'bin' content type requirement in web/core/modules/file/src/Plugin/rest/resource/FileUploadResource.php which
// Add the content type format access check. This will enforce that all
// incoming requests can only use the 'application/octet-stream'
// Content-Type header.

The /entity/media JSON API request url does need a JSON request as per web/core/lib/Drupal/Core/Routing/ContentTypeHeaderMatcher.php
Answer: I use Angular, not React, but I'm pretty sure this part is wrong:
  // headers.set('Content-Type','application/octet-stream');
  headers.set('Content-Type','application/hal+json');

Files need to be posted as application/octet-stream.  It's not a JSON object; it's a file.
Also, you may need to massage the PDF data into something that JSON:API understands.  For example, here's the docs on doing this with axios/Node.js.
In my case, for image files, I had to read the file in as a blob (React code, but may provide an example):
// https://stackoverflow.com/a/46568146
function readFileBlob(fileBlob: Blob) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onabort = () => Promise.reject(Error('file reading was aborted'));
    reader.onerror = () => Promise.reject(Error('file reading has failed'));
    reader.readAsArrayBuffer(fileBlob);
  });
}

// fileToPost is a string that contains a blob:
// blob:http://localhost:8100/00507d3e-7f6f-4f48-be80-b55c8bc20dd3
const postAuthFileBlob = async (
  fetchUrl: string,
  fileToPost: string,
  // Fetch might return anything.
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
  const fileBlob = await fetch(fileToPost).then((res) => res.blob());
  const arrayStr = (await readFileBlob(fileBlob)) as ArrayBuffer;
  return postAuthFileBlobPart2(fetchUrl, arrayStr);
};

Comment: I think you are close. The back-end is complaining that the content-type is multipart/form-data instead of application/octet-stream
Comment: Just posting the pdf gives application/pdf  return this.httpClient.post(this.host + '/entity/media', pdf, {headers: headers}). Still drupal cannot find a match for application/pdf.
No route found that        matches "Content-Type: application/pdf" in Drupal\Core\Routing\ContentTypeHeaderMatcher->filter()
                                                    (line 49 of
Comment: @Interlated As I already stated, you need to post as `application/octet-stream`.  For some reason you commented that out in your code, but you have to post as `application/octet-stream` if you want to upload any binary files.

How do I post a PDF?


How do I create a custom action?

Question: I want to create simple actions that will change the field_support_status field value to 1 or 0. I enabled the "Actions" module and created a custom module with my actions, but after the module is installed the actions do not appear.
In my module, I created files with the following structure:
/src/Plugins/Action/SupportStatusYes.php
<?php
namespace Drupal\support_action\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
/**
 * Change support status on yes.
 *
 * @Action(
 *   id = "support_status_yes",
 *   label = @Translation("Change support status on yes"),
 *   type = "node"
 * )
 */
class SupportStatusYes extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    /** @var \Drupal\node\NodeInterface $node */
    if ($entity->hasField('field_support_status')) {
      $entity->field_support_status->value = 1;
      $entity->save();
    }

  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->field_support_status->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

/src/Plugins/Action/SupportStatusNo.php
<?php
namespace Drupal\support_action\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
/**
 * Change support status on no.
 *
 * @Action(
 *   id = "support_status_no",
 *   label = @Translation("Change support status on no"),
 *   type = "node"
 * )
 */
class SupportStatusNo extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    /** @var \Drupal\node\NodeInterface $node */
    if ($entity->hasField('field_support_status')) {
      $entity->field_support_status->value = 0;
      $entity->save();
    }

  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->field_support_status->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

/config/install/system.action.support_status_no.yml
langcode: en
status: true
dependencies:
  module:
    - node
id: support_status_no
label: 'Change support status on no'
type: node
plugin: support_status_no
configuration: {  }

/config/install/system.action.support_status_yes.yml
langcode: en
status: true
dependencies:
  module:
    - node
id: support_status_yes
label: 'Change support status on yes'
type: node
plugin: support_status_yes
configuration: {  }

/config/schema/support_action.schema.yml
action.configuration.support_status_yes:
  type: action_configuration_default
  label: 'Change support status on yes'

action.configuration.support_status_no:
  type: action_configuration_default
  label: 'Change support status on no'

Tell me please what am I doing wrong?
Answer: The correct directory structure is src/Plugin, not src/Plugins.
The files in config/schema/ and config/install/ look correct to me. I struggled with those mightily. And I'll emphasize that actions only seem to be registered when the module is installed.

How do I create a custom action?


Deploy Laravel application

Question: I have uploaded my Laravel application to server (I'm using shared hosting).
Directory structure is like this:
--public_html
  --laravelApp
    -- app
    -- bootstrap
    -- public
    -- vendor
    -- other Laravel files

My document root is pointing to laravelApp/public.
When I try to access my website using laravelapp.com, I got 500. I got same error if I try to access laravelapp.com/public or laravelapp.com/public/index.php. I don't have .htacess in root of laravelApp, just in public folder.
I guess it's something with .htaccess, but I'm not sure where to look. Here's how it looks like:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

I see some answers, that I should put everything (except public on same level as public_html), but I don't get it, why is that required.
Can someone put more light on this, why and how this should be done properly? Are there some security issues, etc?
Comment: Do you have access to your virtual host config file? Or are you using plesk or cpanel?
Comment: You definitely don't need to change the directory structure. Have you tried `laravelapp.com/index.php` ?
Comment: @lukasgeiter, yes, that was my thought as well, I'm not sure why these people change structure. Yes, I tried that, and it's 500 as well.
Comment: DocumentRoot /var/www/public_html/laravelApp/public/

AllowOverride all
  sorry, will be bad to read, but do you have these entries/settings? Espacially the part within the  part might be interesting
Comment: @baao, hm, but I don't think I can access virtual host config file in CPanel. Or am I wrong?
Comment: I'm not entirely sure about that, I don't use cpanel. But I'm quite sure that you can set those directory directives anywhere. I did only 2 laravel deployments so far, but I had the same 500 error and after adding the directory directive written above everything worked fine...
Comment: yes, similar thing I'm doing when locally create virtual host. I tried to place it in .htacess, but without success, 500 again.
Comment: Have you tried looking at the "Network" tab in your browser's Developer Tools? Sometimes you can get more detail (perhaps a hint) there.
Answer: Ok, the solution was to set Directory to my public folder, and to add RewriteBase rule to .htaccess. Also check whethere your php version is >= 5.4.
Comment: I was in similar situation and just rename 'public' folder in 'public_html', and it work. Try it for next project, it easier than editing .htaccess

Deploy Laravel application


Is it actually possible to insert the shortcut "C-M-\" in a German keyboard?

Question: Goal: I want to use the function indent-region with the default shortcut C-M-\.
Problem: I use a German keyboard layout. To insert "\" I have to type either C-M-ß or AltGr-ß, because the "ß" is overloaded with "?" and "\" (see: QWERTZ layout in the upper right corner).
Question: Is it possible to to input the shortcut C-M-\ without tweaking emacs or the OS on a German keyboard?
If it is not I would just change the shortcut to something easily accessible. The main reason I want this to work is that it works out of the box on a default emacs installation.
Comment: That depends on the operating system.
Answer: I've experienced this problem and found the following info helpful from the "Alt Gr Key" page on emacswiki.org:-

Emacs keys may seem to be "hidden" (perhaps only) on MS Windows because AltGr + LeftControl + key is just AltGr + key.
Solution 1: Using the Right Control
But you can type those keys even on MS Windows! The trick is that you must type AltGr as the first key, and Ctrl must be the right control key, not the left one.

After experimenting on a German keyboard, I can execute C-M-\ like: AltGr+RCtrl+M+\, where RCtrl is my right-Ctrl key, M is my left/only Alt key and \ is my ß?\ key. (The value of w32-alt-is-meta is t.)
This key-chord is cumbersome so perhaps it's better to define the C-M-ß combination as suggested by @OlegPavliv.
Answer: Add the following to your .emacs
(define-key (current-global-map) (kbd "C-M-ß") 'indent-region)

This way it will indent the region on C-M-ß
Answer: Press C-M.
Release.
Press AltGr-ß to produce \
Works for me. Where is the problem?
Comment: This results in the output "\". It is as if I just press AltGr + "ß".
Comment: In Emacs, C-M-\ means control-meta-backslash, not control-M, backslash. If ctrl-esc generates control-meta for you, this is a good solution.


Panel abrir fechado JS

Question: Estou com o seguinte panel:
$(document).on('click', '.panel-heading', function(e){
    var $this = $(this);
    if(!$this.hasClass('panel-collapsed')) {
        $this.parents('.panel').find('.panel-body').slideUp();
        $this.addClass('panel-collapsed');
        $this.find('i').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down');
    } else {
        $this.parents('.panel').find('.panel-body').slideDown();
        $this.removeClass('panel-collapsed');
        $this.find('i').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up');
        $('html, body').animate({scrollTop: $(".btn-modal").offset().top}, 1000);
    }
});

A minha dúvida é: Não esto conseguindo fazer com que ele comece fechado (sem collapse), ou seja, só depois que clicar ele irá aparecer e descer, e ao clicar novamente, irá voltar para o formato fechado. O que eu faço?
Comment: Poderia colocar o HTML do Panel e, se possível, a parte `$(document).on('ready', function (){});` do seu código?
Comment: não consegues fazer um [JSFiddle](http://jsfiddle.net/)?
Comment: Pode colocar um pouco de mais código?
Answer: Experimente colocar no .ready pra fechar todos panels
$(document).ready(function() {
    $('.panel-heading').each(function (index) {
        var $this = $(this);
        if(!$this.hasClass('panel-collapsed')) {
            $this.parents('.panel').find('.panel-body').slideUp();
            $this.addClass('panel-collapsed');
            $this.find('i').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down');
        }
    });
});

Answer: Hitch, como você não postou o código completo,  percebi que você esta utilizando o Bootstrap - Collapse
Se você precisa deixar todos os collapse fechados no  começo é bem simples, basta você remover a class in na div do conteúdo que esta visivél:
Exemplo: jsfiddle

Panel abrir fechado JS


Difference between two solution for Closest pair of points

Question: I'm having a problem with understanding the difference between two solution of of closet pair of point in plane.
According to the the Wikipedia when we are merging two planes we need to check at most 6 points. Why 6 points? because they draw a rectangle in the other plane and claim that at most 6 points can be in the other side. And the following picture is the summery of the their solution:

I got satisfy with this solution, but I have problem with the another solution which has been mentioned in this thread. According to this solution we should check at most 7 points. How 7 points? Due to figure there are two separate square with one edge overlapping. My first question is how they have draw these two squares or one triangle. I mean how they located this triangle, they've just mentioned that its center is on line L, but they haven't mentioned about how they draw it with respect to two other points, why they haven't slip it upper or downer?

And in sum up are these two solutions different from each other or not ?
Answer: AFAIR the algorithm works with the divide-and-conquer paradigm. It splits the plane (and the set of points!) by 'half', solves the problem recursively and then merges the results. The merging is done in such way, that the points get ordered along the splitting line. Then you just scan the left part and the right part in parallel to find a pair crossing the border, which might be closer than the closest pair of points found so far in either part (whose distance is $\delta$ here).
Of course you can skip points that are farther than $\delta$ from the border, as well as point that are lower than $\delta$ below the current point — those certainly will NOT make a pair closer than $\delta$. That way you have a grey area which may contain a point sought. However you already know that there is no pair of point on either side, which are closer than $\delta$. Based on that you can prove, that there can be at most 6 such points in the grey area, hence you don't need to keep more than 6 most recently checked points for future comparisions in a single merge pass.
EDIT
Look again at the description in the right part of this image, which shows 6 dots but tells about 8 points:

Apparently authors assumed that input data may contain duplicated points, which fall into separate subsets during the recursive 'divide' phase at some point. Such duplications are usually forbidden in geometric algorithms — most often when someone defines a quadrilateral ABCD, you don't expect it to be actually a triangle due to D=A, do you?  Also, if duplicates are allowed, then there might be any number of the single point duplicates; I can't understand, why they assume there will be only two.
Anyway if they presume that every point may appear max. twice, hence there might be maximum 8 points in the indicated area, one of which is the point currently analyzed, then that current point needs to be checked with at most 7 other points.
OTOH authors of the algorithm described in Wikipedia assumed no duplicates and similary find out there can be at most 6 points in the $\delta\,\times\,2\delta$ rectangle. Then the next point analyzed on one side of the splitting line needs to be checked against at most 6 points from the other side.
Comment: Actually it doesn't matter. Once a distance 0 is found no further pair will improve that, so it won't matter which points will be compared and which discarded. On the other hand, if there is some zero-distance pair waiting to be detected, it doesn't matter which point we compare and which discard now – whatever we do, we eventually will find the zero. Anyway alhough it seems to give correct results, it doesn't make a feeling of a reliable approach.
Comment: you're right about the duplicates.. Actually there's no reason that all points won't merge.. then there could be infinite points in the Rectangle... The algorithm should terminate if distance 0 is found... (or don't allow duplicates..)
Comment: The author assumed it to be just 2 because there can only be 2 in that situation. The distance between points on either side is Delta, but the split distance is 0 when overlapping. If there were more than 2 overlapping in that picture, then the distance on one of the sides would be 0 and that would cause no points to be added to the middle strip for counting the split distance. Remember that a point p is added to this strip if abs(p.x - medianp.x) < Delta. So the algorithm should work regardless of the overlaps


Travar registro (lock) no SQL Server

Question: Utilizando SQL Server e Delphi, preciso controlar para que em uma certa tabela do banco de dados duas alterações não possam ser feitas ao mesmo tempo no mesmo registro, não posso iniciar o update se já houver outra alteração em andamento. Preciso saber se isso é possível. O cenário é o seguinte: tem-se a tabela TabelaTeste com n registros, e dois terminais de acesso, A e B. Se o terminal A deseja alterar algum dado do registro 1, ele deve adquirir um lock nessa linha, de forma que se o terminal B tentar alterar essa mesma linha ele recebe uma memsagem de erro. Mas alteração de linhas diferentes é permitida.
Para isso consegui obter um certo sucesso. O fluxo é o seguinte atualmente:
1 - Transação iniciada;
2 - Execução de uma query para travar o registro solicitado:
-> 'select * from TabelaTeste with (updlock, nowait) where codigo = :codigo';
3 - Se não der erro ao executar a query acima, o registro está livre e o fluxo continua, senão é gerado um erro e a operação é abortada;
4 - Realizada a operação de update necessária;
5 - Transação é comitada;
Estou tendo problema com a seguinte situação:
1 - Terminal A inicia a alteração da linha 1 dessa tabela;
2 - Terminal B inicia a alteração da linha 2 dessa tabela. Aqui aqui tudo bem, são linhas diferentes;
3 - Terminal A tenta executar seu update (passo nº 4 do esquema acima). Aqui está o problema, enquanto o Terminal B não concluir ou cancelar seu processamento, esse update aqui não será realizado, deixando o usuário esperando;
Se alguém possui algum conhecimento para auxiliar, dizer se é a combinação dos hints que estão sendo utilizados no select, ou se realmente essa situação não é possível.
Comment: Boa tarde @Túlio.  Por acaso eu hoje passei por uma pergunta bem parecida.  De uma olhada para ver se é esse o seu caso..: https://pt.stackoverflow.com/questions/73667/lock-de-registro.  Neste link aponta para um outro link que achei que se encaixa no seu problema..:  https://www.xpertdeveloper.com/2011/11/row-locking-with-mysql/  . Se esses links forem úteis de uma resposta informando isso :) Abraços.
Comment: Bom dia Ricardo, mas não é o mesmo caso, embora semelhantes. A sintaxe entre o Mysql e o SQL Server são diferentes inclusive. Meu caso está mais diretamente ligado ao fato de necessitar que o update dê um lock na tabela em nível de linha, e não em nível de página ou tabela, como parece estar ocorrendo.
Answer: Resolvido, além de alterar o índice da tabela para não permitir lock por página (alter index MyIndex on MyTable set (allow_page_locks = off)), removi um campo que era preenchido por uma trigger e funcionou.

Travar registro (lock) no SQL Server


Why is the normalization constant for the covariance std(x)std(y)?

Question: I understand that the correlation coefficient is just the normalized covariance, where covariance is
$\mathrm{cov}(x, y) \equiv \mathrm{E}[(x-\bar{x})(y-\bar{y})]$
From the definition of the correlation coefficient, I know that the normalization constant is $\sigma_x\sigma_y$, or equivalently I suppose that the maximum value of the covariance is $\sigma_x\sigma_y$.
I have an intuitive understanding of why this should be the case (the root-square combination in the standard deviation gets rid of all the negative signs) but is there a more rigorous way of proving this?
Answer: You just need to invoke Cauchy-Schwartz inequality:
$\mathrm{cov}(x, y) \equiv \mathrm{E}[(x-\bar{x})(y-\bar{y})] \leq \sqrt{\mathrm{E}[(x-\bar{x})^2]}\sqrt{\mathrm{E}[(y-\bar{y})^2]}$
And the left hand side quantities are the standard deviations you are looking for.


TCP Congestion Control

Question: "End points view congestion as increased delays; therefore, they will aggravate congestion instead of alleviating it."

Can somebody pls explain this statement to me ?

2nd question: Why does Fast Recovery not recover very well from multiple losses ?

Here's my understanding of Fast Recovery: Upon reception of three duplicate ACKs, TCP launches a retransmission and then performs Fast Recovery: The congestion window is halved and raised by one segment for each duplicate ACK. So I think this includes the three duplicate ACKs that have started the Fast Retransmit, meaning cwnd_new = cwnd_old + 3 + 1 for every further incoming duplicate ACK. For some reason (why?) after the first non-duplicate ACK arrives at the receiver, cwnd is set to cwnd_old / 2 and then Congestion Avoidance is performed.

Grateful for any help!
Comment: Homework questions?
Answer: One can only speculate w/o more context on the precise meaning whoever said that to you had in mind, but here we go.
Retransmissions in TCP (Reno) can be triggered in 2 ways: RTO & DUPACK. RTO is the retransmission timeout - a state reached when there is no ACK for the senders data. DUPACK - duplicate acks sent when the sender misses a packet or they are reordered.

To your first question: I do not see how TCP is aggrevating congestions, except if this is related to RTO. TCP will congest a network a bit more in the immediate timeframe, when RTO is reached since it will resend unacked segments. However RTO event resets the congestion window to one segment and then slow-start phase begins which should alleviate the congestion after that retransmission.
To your second question: That is because in TCP Reno algorithm when multiple losses are encountered it often reaches a state where the only recovery mechanism is a retransmission timeout. How can this happen, see this video for an example: https://www.youtube.com/watch?v=M6pG9sEVTkg
For some reason (why?) after the first non-duplicate ACK arrives at the receiver, cwnd is set to cwnd_old / 2 and then Congestion Avoidance is performed. when a normal ack is received, the Congestion Avoidance starts, which defines cwnd as cwnd_old / 2 (the cwnd_old is the one that was reached when durring the time of a timeout or 3xdupacks). This was choosen as a convenient half-way point. You don't want to start at the cwnd_old since it gave you problems, you don't want to start at 1, since it's not efficient, so it is quite reasonable to start @ cwnd_old / 2.
Comment: thx very much! The first sentence refers to network congestion without TCP mechanisms to prevent it.. what I still don't understand about fast recovery is: I increase cwnd_old/2  linearly due to incoming DUPACKs. But once the first non-duplicate ACK arrives I decrease it again to cwnd_old/2 . Why would I do that?
Comment: cwnd_old/2 + 1 due to DUP follows one of design principles of TCP -  *conservation* (put 1 packet on network only if 1 is removed). A received DUPACK means that receiver is receiving packets, so you can send 1 packet for each dupack w/o increasing the cwnd (= w/o violating conservation principle).
Comment: Decrease to cwnd_old/2 is because ssthresh (transition point between fast-recovery and congest. avoid. phases) is defined as cwnd_old/2. Think if you could continue doing cwnd_old/2 + 1? No you can't because it is assumed that other packets were sent durring the Fast Recovery and they will get ACKs (those acks will increase cwnd + 1) after the first ACK is received. The value would increase too fast in that case.
Comment: Consider upvoting and accepting if it was helpful.

TCP Congestion Control


Convertendo JSON para arraylist android

Question: Boa tarde!
   Estou tentando fazer o consumo de uma API no android porém estou com dificuldade pois no arquivo JSON ele trás uma categoria, eu tentei adicionar a variavel "sigla" mas não deu certo; o JSON retornado na variavel resposta é esse:
Esse "brl": {, é onde acredito que seja a informação que não estou onseguindo colocar na lista!
{"brl":{"name":"Real","txWithdrawalFee":9,"MinWithdrawal":30,"txWithdrawalPercentageFee":0.0025,"minConf":1,"minDeposit":0,"txDepositFee":0,"txDepositPercentageFee":0,"minAmountTrade":1,"decimal":8,"decimal_withdrawal":8,"active":1,"dev_active":1,"under_maintenance":0,"order":"010","is_withdrawal_active":1,"is_deposit_active":1},"btc":{"name":"Bitcoin","txWithdrawalMinFee":0.0001,"txWithdrawalFee":0.0001,"MinWithdrawal":0.004,"txWithdrawalPercentageFee":0,"minConf":1,"minDeposit":0,"txDepositFee":0,"txDepositPercentageFee":0,"minAmountTrade":0.0001,"decimal":8,"decimal_withdrawal":8,"active":1,"dev_active":1,"under_maintenance":0,"order":"020","is_withdrawal_active":1,

Segue as variaveis da minha classe modelo:
public class Currencies {
//ATRIBUTOS
private String sigla;
private String name;
private String txWithdrawalFee; //taxa de retirada
private String txWithdrawalPercentageFee; //percentual da taxa de retirada
private String minConf;
private String minAmountTrade; //quantidade minima para trade
private String decimal;
private String active;

abaixo vem os metodos getter and setters.
E essa é a classe que faz a conexão
public class HTTPService extends AsyncTask<Void, Void, Currencies> {
//ATRIBUTOS
private ArrayAdapter adapter;
private ListView listView;
private Context context;
private List<Currencies> currenciesList;
private ArrayList<Currencies> currenciesArrayList;
private ProgressBar load;
private int task;
private String call;

private static final String URL_CURRENCIES = "https://braziliex.com/api/v1/public/currencies";

public HTTPService(ArrayList<Currencies> mCurrencies, Context c, int param){
    this.currenciesArrayList = mCurrencies;
    this.context = c;
    this.task = param;
}

@Override
protected Currencies doInBackground(Void... voids) {
    //reposta da chamada da API da Braziliex
    StringBuilder resposta = new StringBuilder();

    //bloco que tenta executar a chamada da API
    try{
        //verificando qual será a chamada
        switch (task){
            case 1:
                call = URL_CURRENCIES;
                break;
        }

        //fazendo a chamada da API
        URL url = new URL("https://braziliex.com/api/v1/public/currencies");

        /**** ABRINDO A CONEXÃO ****/
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);//tempo maximo tentando conexão
        conn.connect();

        //----- LENDO AS INFORMAÇÕES OBTIDAS -----/
        Scanner scanner = new Scanner(url.openStream());
        currenciesArrayList.clear();

        while (scanner.hasNext()){
            resposta.append(scanner.next());
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //O ERRO ACONTECE NESSA LINHA, AO PASSAR PARA A LISTA
    currenciesList = new Gson().fromJson(resposta.toString(), new TypeToken<List<Currencies>>(){}.getType());

    return currenciesList.size() > 0 ? currenciesList.get(0) : null;

}

Ao executar, na linha onde marquei que acontece o erro apresenta a seguinte exceção:

Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

O retorno no site da braziliex:

Obrigado!
Comment: Traduzindo... ele está esperando um início do array (`[`) mas está recebendo um início de objeto (`{`) na linha 1 e coluna 2
Comment: ok, e como corrigir isso ?
Answer: É que na verdade o JSON retornado não é uma lista, ele é um objeto com 2 objetos dentro, btc e ltc. Portanto, ao invés de converter o JSON em uma lista, você precisa identificar o objeto ltc e converter, depois identificar o objeto btc e converter também.
JSONObject respostaJsonObject = new JSONObject(resposta.toString());

JSONObject ltcJsonObject = respostaJsonObject.getJSONObject("ltc"); //Pegando apenas o
//objeto ltc dentro do json, você pode manusear a classe JSONObject ou fazer
//como eu fiz abaixo

Currencies ltc = new Gson().fromJson(ltcJsonObject.toString(), Currencies.class);

Currencies btc = new Gson().fromJson(
      respostaJsonObject.getJSONObject("btc").toString(),
      Currencies.class
);

Comment: Obrigado Diego, tratando ele como um objeto eu consegi retornar as informações que precisava!

Convertendo JSON para arraylist android


How could I send daily or weekly email in cron() function?

Question: I have a content type in which I have drop down list with the values of "daily" and "weekly" and one field is of email. I want to setup the cron function like when the value of that drop down list is "daily" then email will be send daily to the email address of whatever entered in the email field and when the value is "weekly" then the email will be send weekly.
I don't have any idea about this. How will I do this?
Comment: You can use this answer for inspiration: http://drupal.stackexchange.com/questions/10542/how-to-create-a-task-which-run-at-cron-time-and-send-emails-to-users
Comment: https://drupal.stackexchange.com/a/275911/34384
Answer: How are you generating your email?  It sounds to me like you need a custom module that implements hook_cron.  It would have to save the email address and send_interval to it's own table (or you'll have to build a query to select the email and interval from wherever you've stored it) in the database during hook_nodeapi with the update $op and/or the insert $op.  I recommend creating a 3rd column in your table with a date for the last time email was sent.  That way if cron gets interrupted it can continue where it left off.  Use a sql query to select all of the rows with column interval == daily and date < NOW() and send emails out.  Then do the same if the date is a Sunday or whenever you want to send weekly emails for those.  As you process a row, update the date field to the current time which indicates the email was sent.
If you're not up for custom development, you may want to see if the notifications module suites your needs.
Comment: but how could I code in hook_cron()? As this function can only be declared once in module file and I have two conditions. I did not understand your logic. You mean I have to place two if conditions in the hook_cron() function? like `if(value="daily" && date="now() . '12:00:00'"){//send email} if(value="weekly" and day="Monday") {//send email}`
Answer: use the module simplenews and schedule your emails, you don't need programming for that or use triggers and input the time as your variable
Comment: No I have to code in hook_cron(). I don't need any built in module.


Meu programa imprime o mesmo printf duas vezes. C

Question: Olá, eu estou com uma atividade para calcular se um número é primo, se ele não for, calcular seus divisores.
O problema é quando ele é primo, imprime duas vezes o printf.
Gostaria de solucionar para saber o que estou fazendo de errado
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int primoteste (int n)
{

    int cont,divisor;

    for (cont=2;cont<=n/2;cont++)
    {
        if ((n%cont) != 0)
        {

            printf(" %d eh primo.\n",n);
        }
        else
        {
            break;
        }

    }
    for (cont=2;cont<=n/2;cont++)
    {
        if ((n%cont) == 0)
        {
            printf(" %d eh divisor de %d.\n",cont,n);
        }

    }
    return 0;
}

int main ()
{

int n;

printf("Digite um valor \"N\".\n");
scanf(" %d", &n);
primoteste(n);

    return 0;
}

Answer: Você está testando todos os números pra ver se trata-se de um divisor. Quando o numero não é um divisor, você conclui que é um numero primo. Assim, 2,3 e 4 não são divisores de 35, mas 35 não é um numero primo. O que seria melhor, era implementar um contator de divisor. caso no fim, o divisor esteja zerado, então trata-se de um numero primo
    ...
int primoteste (int n)
{
    int totalDivisor=0;
    for (cont=2;cont<=n/2;cont++)
    {
       if ((n%cont) == 0)
       {
           totalDivisor++;
           printf(" %d eh divisor de %d.\n",cont,n);
       }
    }

    if (totalDivisor == 0){
       printf(" %d eh primo. --%d \n",n,cont);
    }
}

alias, não precisa testar ate a metade do n, pode ser ate 3. ou mais precisamente, até a raiz do n. mas se trocar o cont<=n/2 por cont<=n/3
já será bem mais eficiente, caso teste para números muito grandes
Comment: Obrigado, ajudou bastante!


DotVVM: using custom bindings inside the GridViewTemplateColumn ContentTemplate

Question: I've made a jQuery AutoComplete binding for KO. It allows to perform a server side search for suggestions by term. It also allows to fill a text box or an non-input html element with single value retrieved from the server by ID. So far it works OK.
When I place same binding into a ContentTemplate, during the first render of the GridView all the bindings work fine, the data for each id in items is retrieved from the server and the correct Name is injected into the span.
If I am trying to move to a second page of the grid, the main data is retrieved from server, I am getting the new ReviewObjectId-s for each row item, but the server is not requested(no requests in network tab of chrome debugger) and moreover the binding is not initialized at all, the names appear exactly like on previous page. Same behaviour occurs mostly until I go to the last page in pager or until more paging numbers are rendered in pager. Sometimes clicking the next page does the job
Filtering the DataSource to show the same Name for each row (every item has same
target ReviewObjectId) often shows the same result.
The custom binding looks like this

The "find" is autocomplete api url which produces a list of suggestions.
The "get" is a fill api url, which provides entity by Id (ReviewObjectId).
TextItem and ValueItem are provided for mapping the received JSON to viewModel.
I am using the same GridViewDataSet as DataSource both in GridView, DataPager and filter, the datasource is always filtered according to page and filter values correctly.
What am I doing wrong? Where should I dig to?
UPD: the binding:
ko.bindingHandlers.autoComplete = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //initialize autocomplete with some optional options
        var options = valueAccessor().apiOptions;
        if (options && options.find) {
            var value = valueAccessor().selectedValue;
            var data = options.data || { data: {} };
            var searchOptions = { url: options.find, textItem: options.textItem, valueItem: options.valueItem };

            //init text on first load
            if (value() && options.get) {
                var fillOptions = { url: options.get, textItem: options.textItem, valueItem: options.valueItem };
                var fillData = value();
                var fillResult = function (data) {
                    if (data) {
                        if ($(element).is('input')) {
                            $(element).val(data);
                        } else {
                            $(element).html(data);
                        }
                    }
                };

                var promise = new Promise(function(resolve, reject) {
                    fetcher.search(fillOptions, fillData, fillResult);
                });
                if ($(element).is('input')) {
                    promise.then(fetcher.initAutoComplete(element, options, searchOptions, data, value));
                }
            }
            else {
                if ($(element).is('input')) {
                    fetcher.initAutoComplete(element, options, searchOptions, data, value);
                }
            }
        }
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        //var value = ko.utils.unwrapObservable(valueAccessor()) || null;
    }
};

var fetcher = {
    initAutoComplete: function (element, options, searchOptions, data, valueAccessor) {
        $(element).autocomplete({
            delay: options.delay || 300,
            minLength: options.minLength || 3,
            classes: {
                "ui-autocomplete": "dropdown-menu"
            },
            source: function (request, response) {
                //loading values from cache
                if (request.term) {
                    var cacheKey = searchOptions.url + '-' + request.term;
                    if (cacheKey in this.cache) {
                        response(this.cache[cacheKey]);
                        return;
                    }
                }
                //querying server, contract data MUST contain Term
                data.Term = request.term;
                this.search(searchOptions, data, response);
            }.bind(this),
            select: function (e, i) {
                valueAccessor(i.item.val);
                $(element).val(i.item.label);
            }
        });
    },
    search: function(options, data, response) {
        $.ajax({
            url: options.url,
            data: JSON.stringify(data),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function(responseData) {
                var textItemName = options.textItem || "value";
                var valueItemName = options.valueItem || "key";

                //cache results if exist
                var cacheKey = '';
                if (Array.isArray(responseData)) { //search by term
                    var result = $.map(responseData,
                        function (item) {
                            return {
                                label: item[textItemName],
                                val: item[valueItemName]
                            }
                        });
                    if (result.length > 0) {
                        cacheKey = options.url + '-' + data.Term;
                        this.cache[cacheKey] = result;
                    }

                } else { //init by bound value
                    if (responseData[textItemName] && responseData[textItemName].length > 0) {
                        cacheKey = options.url + '-' + responseData[valueItemName];
                        this.cache[cacheKey] = responseData[textItemName];
                    }
                }
                //send result to response
                response(this.cache[cacheKey]);
            }.bind(this),
            error: function (responseData) {
                console.log("error");
            },
            failure: function (responseData) {
                console.log("failure");
            }
        });
    },
    cache: {}
}

Answer: I think that you are ignoring the update event in your binding handler. When the page is changed, only the view model is refetched and bindings are updated, the page is not refetched. Have a look at the knockout.js documentation how to use the update function http://knockoutjs.com/documentation/custom-bindings.html:
ko.bindingHandlers.yourBindingName = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.
    }
};

Knockout basically watches any changes of observables touched when the binding is initialized and then invokes the update function when any of these changes.
Comment: Actually you are right. KO is smart enough to ignore empty update function. Did some refactoring  for the update & all works just great. Thank you.
Comment: Well, actually autocomplete is setting the value for the bound property in `select function` and updates the text, it is not supposed to react to bound property  change for now
Comment: The point is that when you change the page of the GridView, the bindings inside just get updated, the page is not refetched every time.
Comment: The update is not even fired, I mean during paging only if the init was called, the update is called too.  But if the page has different size than the previous, then everything works OK.  For example: page size is 30. We have 6 pages, the last one has only 3 items. 1 page binding works, 2-3-4-5 pages has the same values for the organization name field and neither init nor update functions of the binding are entered, 6 page works OK, bindings work, values change. Start paging back to 5 - binding works, 4-3-2-1 - all the same.
Comment: Maybe that's because the size of the page changes, so the entire table is reinitialized. But when the page size does not change, it's only updated.
Comment: I think that the `update` function is not fired when knockout sees, that you are not watching any observalbe value here. Try to upwrap the selected value here.


C++ Code Encryption without using password nor key

Question: Do you have any idea how to encrypt a C++ code? I do not want to use a password nor key, I just want to save the code on its form, but remove comments, change the variable names and making the code more mysterious and complex to be understood.
Comment: Not going to fool anyone with at least a little bit of skill in understanding code...
Comment: He didn't say that was his goal; he's simply asking what the term for such a tool is.
Comment: @RedRoboHood: and what OTHER goal would there be in doing this? [Yes, I understand that people can ask hypothetical questions, but even when you ask "I have a friend who wonders if..." or "I would like to know if it is possible to...", there is some sort of purpose to why you would like to perform whatever the action is - even if it's just a plot for a novel or film script, if you ask "How would you break into a bank?", the idea isn't to break into a bank without reaching the money, right?
Comment: @MatsPetersson I understand what you're saying, but obviously there must be a valid use case behind obfuscators for people to put so much effort into writing them, correct?
Comment: Yes, the main reason is to removed comments and variables names that explain what to code does. But it's still not going to stop someone from understanding the code if they really want to - just like taking some compiled code and disassembling some code will be understandable if you really put your mind to it.
Answer: I think what you're looking for is an obfuscator.


MySql - Update para null coluna unique

Question: Boa tarde galera.
Gostaria de saber se há a possibilidade de realizar um UPDATE para NULL onde o campo permita somente valores UNIQUE.
Tentei dessa forma:
update FUNCIONARIO set codigocartao = NULL where situacao = 'DESATIVADO'

Mas me retornou o erro de registro duplicado.
O cenário que eu preciso é:  o campo codigocartao deve ter registro único,  mas também pode ser nulo.
o cenário que tenho hoje é: toda vez que preciso setar o campo para NULL, eu acabo tendo que deletar o funcionario da tabela.
Estou fazendo algo errado ou essa possibilidade não existe no MySQL?
Alguém tem alguma idéia?
Comment: rray, não, o campo estava definido com UNIQUE e NOT NULL (este o problema). obrigado.
Comment: Em teoria é possível pq um nulo nunca é igual a outro. `codigocartao` é FK também? poderia colocar a mensagem original do erro? e definição da tabela.
Answer: Sim, você pode fazer isso. veja a  documentação MySQL (versão 5.5).

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE  index allows multiple NULL values for columns that can contain NULL.

Verifique se você não definiu a coluna como NOT NULL
Comment: A coluna estava definica como NOT NULL, este estava sendo o problema
Comment: Renato, obrigado pela resposta.
Comment: Então é isso, resolvido ;)

MySql - Update para null coluna unique


How do I have the same toolbar for every layout with Android?

Question: I'm currently trying to create an interface for an application on Android. I'm a beginner with Android, and I would like the same toolbar on every layout I create. Here's my code :
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:fitsSystemWindows="true"
    android:background="#FFC8A6"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
            android:background="#FF0000" app:popupTheme="@style/AppTheme.PopupOverlay">
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main"/>

</android.support.design.widget.CoordinatorLayout>

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main" tools:context=".MainActivity">

    <Button
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:layout_weight="50"
        android:text="Start training"
        android:id="@+id/buttonStart"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp" />

    <Button
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:layout_weight="50"
        android:text="Help"
        android:id="@+id/buttonHelp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="160dp" />
</RelativeLayout>

Now, I'd like to keep what's in activity_main.xml and apply it to every layout, so just the content would change. I know that the color in content_main.xml will have to be applied everywhere, but is there a way to at least keep the toolbar? Thank you.
Answer: Create a layout E.g: toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:title="@string/app_name"
android:titleTextColor="@color/white"
android:theme="@style/ToolbarStyle"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:background="@color/form_completion_top_text"/>

And in every layout, just place this line of code anywhere
<include @layout/toolbar/>

By default, you'll have the same toolbar
Comment: It worked! Thank you very much! I had to do some other manipulations (as I didn't delete the Toolbar in activity_main.xml at first), but it worked in the end!
Comment: and how to have `popupTheme` not hardcoded, but defined in XML style? eg. I want to have the same toolbar with different styles on different activities?


How to choose a way to obtain maximum likelihood estimation

Question: Given an example random variables $ X_1, X_2,\ldots, X_n $, and assume that
we have a distribution function  to describe the data (Bernoulli):
$f(x_i;p)  = p^{x_i}(1-p)^{(1-x_{I})} $
Here $p$ is the unknown parameter, with which we want to find maximum likelihood estimator (MLE).
In my understanding there are two ways to obtain that MLE:

Is by using calculus, do it on paper like this way. This lead us to obtain $\hat{p} = \frac{\sum_{i=1}^n X_i}{n}$. With which then we can just plug-in the $ X_1, X_2,\ldots, X_n $ value and get the actual value for $\hat{p}$.
Numerical (iterative) search procedure like using bbmle::mle2 package in R.

My question, given a problem how can we decide which method to use to find MLE. With calculus or numerically search procedure?
Answer: There is nothing special about MLEs here, since what you're asking really applies to any optimisation problem.  In this broader sense, you want to know what methods are desirable to maximise/minimise a function.
Applying standard calculus methods for optimisation, you should be able to get an equation for the critical points for the function, and the second-order-conditions for optimisation, and this will usually allow you to find the maximising point.  Often the maximising point is a critical-point, and in this case, optimisation involves finding the solution(s) to the critical point equation.  In some problems the critical point has an explicit closed-form solution, as in the example in your question.  In other problems there is no closed-form solution to the critical point equation, and in this case it is usual to solve this equation via iterative numerical methods (i.e., start at some arbitrary point, and then move closer and closer to the critical point via some iterative algorithm).
The best way to distinguish these cases is simply to try to optimise algebraically, and see if this leads you to an explicit solution, or a case that requires numerical methods.  If it is possible to get an explicit closed-form solution for the maximising value then you are finished, and no numerical methods are required.  If you require numerical methods to find the solution to the critical point equation, then you can either form this iterative process algebraically, or rely on a package such as bbmle in R.  At the end of the day, optimisation requires familiarity with calculus; with experience you will be able to anticipate which problems give closed-form solutions and which will require iterative methods.


Drupal 7 Views - Add a wrapper around rows for unformatted list from admin panel

Question: I have a views which rendered html like this

Some Text here

Some Text here

Some Text here

Now I want to wrap the rows using a wrapper div like so.

Some Text here

Some Text here

Some Text here

Comment: What's your question exactly? Where are you stuck?
Comment: @Clive : I want to add a wrapper div from views admin panel
Answer: Assuming you know how to override theme templates (that would be a separate question) you can override the views_view_unformatted.tpl.php template and make your override something like this:
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>

  <?php foreach ($rows as $id => $row): ?>
    <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>
      <?php print $row; ?>

  <?php endforeach; ?>

You could also override the views-view.tpl.php template instead and in the part that says:
<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

do something like
<?php if ($rows): ?>

      <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

It's up to you which way you want to do it.
Comment: I want to add wrapper div from admin panel.
Comment: Sorry, your question didn't really specify that. It says drupal 7 views and then says wrapper around rows of unformatted list. You should add more specific information to your question. Unfortunately I don't have time for answering any more questions for at least the next few days.
Answer: You can go to your view under format click on format settings see List section, select one of the list types and type name of your class. li, ol, de tag will be placed where you want it.
Comment: The question isn't about making a html list it is about adding a wrapper div to an unformatted list view.


Alternativa para File API para navegador ultrapassado

Question: Preciso ler o binário de um arquivo e postar para uma determinada URL, mas sem armazenar o arquivo propriamente dito para o servidor (não posso armazenar o arquivo).
Para complicar - eu adoraria usar a API de arquivos do HTML5 para isso, mas tenho que suportar o IE9 (em todos os sentidos da palavra "suportar"), que não implementa HTML5.
Existe alguma forma? Seria possível, por exemplo, usar algum mecanismo de upload para interceptar o arquivo no momento em que está subindo, para então ler seu conteúdo e cancelar o upload via Javascript?
Answer: Você não pode armazenar o arquivo nem temporariamente?
Se sim, você poderia fazer o seguinte:
1) Você cria um ajax que faz o upload do arquivo para uma pasta /tmp (propositalmente para o arquivo ser apagado depois);
2) Esse ajax chama um método no seu servidor ( pode ser shell script ou php mesmo);
3) Esse método vai ler e retornar o binário que vc quer e apagar o arquivo;
4) Esse binário estará armazenado no seu objeto javascript (success), depois basta pegar o valor desse objeto e colocar na sua url.
Se precisar de ajuda para implementar esse passo a passo me avisa que eu edito a resposta e coloco um código exemplo.


SQL will output my query only if I alias my columns in my select statement... Not sure why

Question: Alright this is my curiosity, my question is why...
First this is the ERD to understand the tables and connections...
Now my Query is supposed to "Provide a table that provides the region for each sales_rep along with their associated accounts. Your final table should include three columns: the region name, the sales rep name, and the account name. Sort the accounts alphabetically (A-Z) according to account name"
I created this query:
select acc.name , reg.name , srep.name
from region reg
join sales_reps srep
on srep.region_id = reg.id
join accounts as acc
on acc.sales_rep_id = srep.id
order by 1;

This resulted in outputting only the first column of my query like so:

But it's not until I add aliases to each of my columns that the output is generated:
select acc.name account_name
 , reg.name region_name
 , srep.name sales_rep_name
from region reg
join sales_reps srep
on srep.region_id = reg.id
join accounts as acc
on acc.sales_rep_id = srep.id
order by 1;

Output:

Can anyone tell me why that is ? Thank you !!!!
IMPORTANT CONTEXT INFO:This is using MODE and it's part of the SQL Course on Udacity COURSE Joins Section step 12
Answer: You never told us what your actual SQL engine is (e.g. MySQL, SQL Server, Oracle, etc.).  But this doesn't really even matter, because on most engines your first select would in fact have generated a result set with three columns all called name.  You may confirm this behavior by just running your query directly against the actual SQL database.
What is likely happening here is that the Udacity SQL tool has inserted some layer in between the SQL database and the UI, the latter whose output you have been posting in your question.  This additional layer is, for some reason, resolving duplicate column names in the result set by keeping only one of them.  The workaround, as you have already figured out, is to just use unique aliases.
Comment: I knew it had to do something with Udacity, I was sure my query would output the columns, I really appreciate your feedback! I was curious because I wasn't sure if it was a SQL rule or something but it does seem to be just something with Udacity. Thanks, Tim, hope you have a great day/night!


$\mathbb R$ as continuum many of pairwise disjoint of Bernstein sets

Question: The set $B\subset\mathbb R$ is called Bernstein set if neither $B$ nor $\mathbb R\setminus B$ contains any perfect sets.
Theorem: $\mathbb R$ can be written as continuum many of pairwise disjoint Bernstein sets.
Proof:  Let $\mathcal{P}$ be a family of all perfect subsets of $\mathbb R$. Then  $|\mathcal{P}\times\mathbb R|=\mathfrak c , $ so we can choose an enumeration $\{\langle P_\xi,y_\xi\rangle\colon\xi<\mathfrak c\}$ of $\mathcal{P} \times \mathbb R.$
We will construct, by induction on $\xi<\mathfrak c,$ a
sequence $\{x_\xi\colon \xi<\mathfrak c\}$ such that
$$x_\xi\in P_\xi\setminus\{x_\zeta\colon \zeta<\xi\}$$
Since each $x_\lambda\neq x_\xi$ for all $\lambda<\xi<\mathfrak c$, we can define $f$ on $\{x_\xi\colon \xi<\mathfrak c\}$ such that $f(x_\xi)=y_\xi$ and $f(x)=0$ otherwise.
Claim : $f^{-1}(r)$ is Bernstein set for each $r\in\mathbb R.$
Indeed, for each $r\in\mathbb R$ and $P\in\mathcal P$ there is an $\xi<\mathfrak c$ such that $\langle r,P\rangle = \langle r_\xi, P_\xi \rangle$,  then $x_\xi\in f^{-1}(r_\xi)\cap P_\xi=f^{-1}(r) \cap P\neq \emptyset.$  Also the same true for the complement for $f^{-1}(r)$ (as $f^{-1}(t)$ where $t\neq r$).  Then $f^{-1} (r)$ is Bernstein for all $r\in\mathbb R$. It is clear that $$ \mathbb R=\bigcup_{r\in\mathbb R} f^{-1} (r)$$ as we need.
I have no probelm with this proof at all. My question is Can we have the same result without  define function like that? I mean just start to construct the by transfinite induction. I would love to see completely different approache to get the same result. I am hoping for theos who have deeply understanding for transfinite induction to share their proofs.
Comment: Proper notation is $\langle P_\xi,y_\xi\rangle,$ not $< P_\xi,y_\xi>.$ I edited accordingly.
Comment: @MichaelHardy, Thank you for fixing
Answer: First, and least important, your construction is by recursion, not by induction: induction is a proof technique.
Next, the argument doesn't really use the function $f$ at all: you could just as well define your Bernstein sets by letting $B_r=\{x_\xi:y_\xi=r\}$ for each $r\in\Bbb R$.
Finally, your construction does not ensure that the union of your Bernstein sets is all of $\Bbb R$; it could, for instance, be $\Bbb R\setminus\Bbb Q$ if you happened to choose irrational numbers for all of your points $x_\xi$. If you want them to be a partition of $\Bbb R$, you have to be a bit more careful in your recursion.
Enumerate $\Bbb R=\{r_\xi:\xi<\mathfrak{c}\}$. At stage $\eta$, when you've already chosen $x_\xi$ for all $\xi<\eta$, let $\mu=\min\big\{\zeta<\mathfrak{c}:r_\zeta\in P_\eta\setminus\{x_\xi:\xi<\eta\}\big\}$, and let $x_\eta=r_\mu$. This is just your construction with a little extra care taken in choosing which point of $P_\eta\setminus\{x_\xi:\xi<\eta\}$ to use as $x_\eta$, so it does give you pairwise disjoint Bernstein sets $B_r=\{x_\xi:y_\xi=r\}$ for $r\in\Bbb R$.
Suppose that $\Bbb R\setminus\bigcup_{r\in\Bbb R}B_r\ne\varnothing$, let $r_\nu\in\Bbb R\setminus\bigcup_{r\in\Bbb R}B_r$ and let $X=\{\xi<\mathfrak{c}:r_\nu\in P_\xi\}$; then $|X|=\mathfrak{c}$, and $x_\xi\in P_\xi$ for each $\xi\in X$. For each $\xi\in X$ there is a $\mu(\xi)<\mathfrak{c}$ such that $x_\xi=r_{\mu(\xi)}$, and the points $x_\xi$ are distinct, so the map $\mu$ is injective. Let $M=\{\mu(\xi):\xi\in X\}$; $|M|=\mathfrak{c}$, so we can let $\theta=\min\{\mu\in M:\nu\le\mu\}$. Note that $\theta=\mu(\eta)$ for some $\eta\in X$, and $x_\eta=r_\theta$.
By hypothesis $r_\nu\notin\bigcup_{r\in\Bbb R}B_r$, so there is no $\xi<\mathfrak{c}$ such that $x_\xi=r_\nu$, and therefore $\theta>\nu$. But this is impossible: $r_\nu\in P_\eta\setminus\{x_\xi:\xi<\eta\}$, and $\nu<\theta$, so at stage $\eta$, when we chose $x_\eta$, $\theta$ was not the least element of $\big\{\zeta<\mathfrak{c}:r_\zeta\in P_\eta\setminus\{x_\xi:\xi<\eta\}\big\}$, and we did not set $x_\eta=r_\theta$.
Added: Here are a few links to answers of mine containing constructions by transfinite recursion, and one to an old paper of mine that does so; I've arranged them very roughly in ascending order of complexity. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 [PDF; see Theorem $\bf{5}$].
Comment: @Brain You are right. Once again, Could you say by words, how can I understand the definition. $B_r=\{x_\xi\colon y_\xi=r\}  I do not know why I have trouble with this definition. It seems useful since it uses for many different construction
Comment: @00GB: Recall that $\{\langle P_\xi,y_\xi\rangle:\xi<\mathfrak{c}\}$ is an enumeration of $\mathscr{P}\times\Bbb R$. If $r\in\Bbb R$, each of the pairs $\langle P,r\rangle$ for $P\in\mathscr{P}$ is a different $\langle P_\xi,y_\xi\rangle$. That is, there are $\mathfrak{c}$ different ordinals $\xi$ such that $y_\xi=r$, and if $X$ is the set of those ordinals, then $\{P_\xi:\xi\in X\}=\mathscr{P}$, because $r$ gets paired with every perfect set. I'm just setting $B_r=\{x_\xi:\xi\in X\}$: for any perfect $P$ there is a $\xi\in X$ such that $P=P_\xi$, and $x_\xi\in B_r\cap P_\xi$.
Comment: @Brain, that's help. If you know could you refer me the reference ( book , notes, etc) that has more example about  construction is by recursion. This would be great
Comment: @00GB: I originally learned to carry out such constructions partly be seeing a few in lectures but mostly by encountering them in papers, so I'm not sure that I can easily come up with a source or two containing a useful number of different examples, but I'll give it some thought; I might be able to offer a couple of suggestions.
Comment: Brian  Please do so this would be great. I was trying but I could not find
Comment: @00GB: I've added some links to old answers of mine that contain constructions by transfinite recursion; some are very simple, and a couple are fairly complicated.
Comment: We  can construct a pair-wise disjoint $F=\{F_x: x<c\}$ where $|F|=c$ and each $F_x$ intersects  every perfect set. Consider $G=\{G_x: x< c\}$ where $G_x=F_x$ for $x\ne 0$ and $G_0=F_0\cup (\Bbb R \setminus \cup F).$
Comment: @BrianM.Scott,Thank you very much
Comment: @00GB: You're very welcome. I hope that they help.
Comment: @BrianM.Scott, Yes, it does
Comment: @BrianM.Scott, I believe the same will be working if we need to show that each Bernstein set can be written as a continuum of many pairwise disjoint Bernstein sets. Or, there is an easy way to show that
Comment: @BrianM.Scott, the same can be used if we need to show that every Bernstein set can be partitioned into $\mathfrak c$-many Bernstein sets, Is that right? Or there is another to see that