Trying to understand the basics of bayesian inference

Question: This paper gives a somewhat gentle introduction to Bayesian inference: http://www.miketipping.com/papers/met-mlbayes.pdf
I got to section 2.3 without much problems but got stuck in understanding that section onwards. It starts by presenting a probabilistic regression framework where the likelihood of all data is given as:
$$
p(t|x,w,\sigma^2) = \prod_{n}p\left(t_n|x_n,w,\sigma^2\right)
$$
where $t_n=y(x_n;w)+\epsilon_n$ is the 'target' value. Next, given a set of parameters $w$ and a hyperparameter $\alpha$, the prior is given as:
$$
p(w|\alpha)=\prod_{m}\left(\frac{\alpha}{2\pi}\right)^{1/2}\exp\left({-\frac{\alpha}{2}w_m^2}\right)
$$
I can then compute the posterior $p\left(w|t,\alpha,\sigma^2\right)$. What I don't understand is the following:

In the first equation above, how should I interpret the product over the $N$ pairs of data $(t_n,x_n)$? Lets say I get two initial measurements from the real world, is $p\left(t|x,w,\sigma^2\right)$ supposed to give me a single real-valued probability? And how do I account for $w$ since it is not known yet?
As far as I got it, $w$ is supposed to be a vector of size $M$ where $w_i$ contains the $i$th estimated value. Now, how can a prior for $w$ have a reference to its own vector elements if I don't know them yet? Shouldn't a prior be an independent distribution such as a Gaussian or Beta? Also, shouldn't a prior be independent of hyperparameters?
Figure 4, on the article's page 8 has a plot from the prior and from the posteriors of an example using the $y=\sin(x)$ function with added Gaussian variance 0.2. How could I plot something similar in, say, Octave/Matlab or R?

I don't have a strong background in statistics so forgive me if this is too basic. Any help is appreciated.
Thanks in advance!
Comment: To answer your second question, the prior has $w$ as a variable because it is function of $w$. It maps all possible values of $w$ to a probability. Furthermore, it *is* a Gaussian. See footnote #3 in that paper...I think you're getting confused by the subtle distinction b/t a probability density and a likelihood function.
Comment: @jerad Ok, would that answer the first question a little as well? Since _tn_ and _xn_ are known, is the first equation also a function of _w_? Thanks!
Comment: The first equation is a distribution over $t$ *conditional* on some $x,w,\sigma^2$.
Comment: Thanks. This is part of my confusion. Take a look at this videolecture for instance: http://videolectures.net/mlss09uk_bishop_ibi/, and jump to minute 10:33 (Bayesian inference). There he says that p(x-hat|theta) is a function over theta given the new observed values x-hat.
Comment: Yes, well as explained in the [wikipedia article on likelihood functions](http://en.wikipedia.org/wiki/Likelihood_function), it is merely a matter of perspective. I think anytime you see $p(\cdot)$ you should try to visualize a plot with probability on the Y-axis and parameters on the X-axis. You can either evaluate that function for a parameter value and return a probability, or you can view it as a function of the variables, ie. the whole plot.
Answer: First question:
The product is the joint probability of the sample, often also called the likelihood (see the footnote on page 5). Yes, it gives you a single probability. It is simply the individual probabilities multiplied together, since they are assumed independent. This equation is sort of like an intermediate step. From there on, they drop $x$ from the notation. Then they end up with equation (11), where this first equation is combined with a prior and the normalizing constant. This is sort of the essence of Bayesian inference: we don't know the parameter $w$, but we know that the data depends on it. Using Bayes' theorem, we can thus get a posterior distribution by having a prior distribution.
Second question:
The vector $\mathbf{w}=(w_1, w_2, \dots, w_M)$ does not contain estimates. It contains the random variables $w_1, w_2, \dots, w_M$, i.e. the parameters. Not sure how/where they reference themselves?


Doctrine queryBuilder: return object not array

Question: I have this query created with doctrine querybuilder, the return i get is an array of arrays.
I would like to get a return that is an array of objects, is this possible?
I know that normally Doctrine returns objects of an entity, bit since i have an inner join to get the name from another table it returns arrays.
Thanks in advance.
   $qb->select('u', 'h.name')
        ->from('AppBundle:UserHose', 'u')
        ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
        ->where('u.userId = :userId')
        ->orderBy('u.id', 'DESC')
            ->setParameter('userId', $userId);

    return $qb->getQuery()->getResult();

Answer: you can use this:
return $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

Or this:
return $qb->getQuery()->getArrayResult();

Answer: This isn't possible this way. In other words, you are doing it wrong.
You are telling Doctrine to return a collection of collections containing an entity and a string so this is what you get. Doctrine won't make an object out of that since it does not know how to hydrate such result.
[
  [entity, string],
  [entity, string],
  ....
]

If you wish to receive a collection of objects only, you would need to create a new entity that has both fields (related entity and a string property), then use a ResultSet mapping to hydrate that.
Answer: if you want array of objects you have to set relation betwen Entities, and create a query by the owning side of relation.
example:
Tourney entity , Invite entity

Invite
    /**
     * @ORM\ManyToOne(targetEntity="Tourney", inversedBy="invites")
     */
    protected $tourneys;

Tourney
    /**

     * @ORM\OneToMany(targetEntity="Invite", mappedBy="tourneys", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable=true, onDelete="CASCADE")
     */
    protected $invites;

now you have to make query to the owning side of relation (Invite)
and it will be holding all your join object data with Tourneys in field $invites
and it gives you array of objects. based on your query
remeber of setter $invites as setInvites(Tourney $invites) and by inverse side of relation setTourneys(Invite $tourneys)
Answer: Just add \Doctrine\ORM\Query::HYDRATE_ARRAY on getResult() like this
$qb->select('u', 'h.name')
   ->from('AppBundle:UserHose', 'u')
   ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
   ->where('u.userId = :userId')
   ->orderBy('u.id', 'DESC')
   ->setParameter('userId', $userId);

return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

Comment: Might want to read the question a bit closer.  He is already getting an array result for some reason.  He want an array of objects.


$\operatorname{trace}(e_1e_2)=\operatorname{trace}(f_1f_2)$ for certain idempotents of a $C^*$ algebra with trace

Question: Indirectly inspired by this post  we  ask the following question:
Let $A$ be a $C^*$ algebra which is equiped with a faithful positive normal trace.
Assume that  $e_1,e_2,f_1,f_2$ are idempotents in $A$. Assume that $e_1 \simeq_h f_1$ and $e_2\simeq_h f_2$  where $\simeq_h$ is the homotopy equivalent of idempotents. Does this imply that
$\operatorname{trace}(e_1e_2)=\operatorname{trace}(f_1f_2)$?
Comment: Homotopic projections are unitarily equivalent in a unital $C^*$-algebra, so unless the same unitary $u$ relates $e_i$ with $f_i$ I feel like there is probably a counterexample, just my initial thoughts though.
Answer: I have never seen the notion of homotopy of idempotents, but I will assume what I think it should be: $e\simeq_h f$ means there exists $F:[0,1]\to A$, continuous,  such that $F(0)=e$, $F(1)=f$.
In that case, the answer is no. Take $A=M_2(\mathbb C)$, and
$$
e_1=f_1=\begin{bmatrix} 1&0\\0&0\end{bmatrix},\quad e_2=\begin{bmatrix} t&\sqrt{t-t^2}\\ \sqrt{t-t^t2}&1-t\end{bmatrix} ,\quad f_2=\begin{bmatrix} s&\sqrt{s-s^2}\\ \sqrt{s-s^t2}&1-s\end{bmatrix},
$$
where $t,s\in[0,1]$ are to be chosen.
Then all four projections are homotopic, and
$$
\operatorname{Tr}(e_1e_2)=t,\qquad \operatorname{Tr}(f_1f_2)=s.
$$
Comment: Thank you very much
Comment: The homotopy of idempotent is the stronget equivalent relation on space of idempotents of an algebra: two idempotent are homotopic if there is a continuous curve of idempotents joining them. It is stronger than similiarity and similiartty is stronger than Mourray Von Neumann equivalent


Prove that $(A×B)\setminus(C×C)= ((A\setminus C) ×B) ∪ (A×(B\setminus C)$

Question: Let $A, B$ and $C$ be sets, with $C\subseteq A\cap B$. Prove that

$$(A×B)\setminus(C×C)= ((A\setminus C) ×B) ∪ (A×(B\setminus C))$$
  MY try:
  $$∃(x,y):(x,y)∈(A\setminus C) ×B ∨ A×(B\setminus C)≡$$$$(x∈(A\setminus C) ∧ y∈B ) ∨ ( x∈A ∧ y∈(B\setminus C)≡$$$$(x∈A ∧ x∉C ∧ y∈B) ∨ (
x∈A ∧ y∈B ∧ y∉C)≡$$$$((x,y )∈A×B ∧ x∉C) ∨ ( (x,y )∈A×B ∧ y∉C)≡$$$$((x,y )∈A×B ∧(x,y )∈A×B) ∨ (x∉C ∧
y∉C)≡$$$$((x,y)∈A×B ) ∨ ((x,y)∉C×C )$$
  But this is not the right answer, so what should I do?
Comment: First specify a universal set containing $A$, $B$, and $C$.
Answer: The first line of your 'proof' begins with $\exists(x,y)$... this is not a good way to start an elementary equality of sets proof. Your proof should go something like this:
"Suppose that $(x,y)\in(A\times B)\setminus(C\times C)$. Then ... [insert proof here] ... and therefore $(x,y)\in((A\setminus C)\times B)\cup(A\times(B\setminus C))$. Now suppose that $(x,y)\in((A\setminus C)\times B)\cup(A\times(B\setminus C))$. Then ... [insert proof here] ... and therefore $(x,y)\in(A\times B)\setminus(C\times C)$."
This is the structure you're aiming for. And each line needs to follow clearly from the last simply by the definitions of each set. Also I've noticed a problem some small but rectifiable problems in the last two lines of what you've written: There's a redundancy on the second last line (can you spot what it is), and on both the last two lines you write $\vee$ where you should have written $\wedge$.
Other than that what you've written is good, it just needs some words explaining what you're actually doing to make it a proof. Hopefully that helps.
Answer: Starting from your third row:
$$[(x \in A \wedge y \in B) \wedge (x \notin C)] \vee [(x \in A \wedge y \in B) \wedge (y \notin C)]=$$$$=(x \in A \wedge y \in B) \wedge [(x \notin C)\vee (y \notin C)]$$ by the distributive law.
$(x \in A \wedge y \in B) \wedge [(x \notin C)\vee (y \notin C)] = (x \in A \wedge y \in B) \wedge [\neg((x \in C)\wedge (y \in C))]$
$$\Rightarrow (x,y) \in A\times B \setminus  (C\times C)$$


How is this bar an example of the rule given in Tonal Counterpoint text?

Question: The rule given in Green and Jones' The Principles and Practice of Tonal Counterpoint is:

The seventh may move into another voice before resolving, but when the
  harmony changes it will almost always resolve down by step.

I see what they're talking about in the first bar, the chordal 7ths being indicated by the dashed line, and the resolution by the arrow, but this isn't shown in the second bar. The chordal 7th does not appear to change voices. Are they referring to the resolution to Eb-maj that happens with the final eighth note?
Comment: Yeah, I suspect the second half is illustrating the fact that the seventh sometimes has an ornamented resolution. By the way, the resolution to Eb-maj happens on beat 3, before the final eighth note; the seventh just becomes a suspension with a delayed resolution.
Comment: Is there another rule on the page that explains the second bar?
Comment: I don't think there's another rule. Directly before the stated rule is an example for the previous rule.
Comment: @PatMuchmore You should turn this into an answer; this is definitely what's being illustrated.
Answer: I suspect the second half is illustrating the fact that the seventh sometimes has an ornamented resolution. I guess it's kind of similar to the point about how a seventh can be transferred to another voice, because the seventh is introduced at the beginning and then seems to go away, but is then reintroduced on the upbeat of beat 2, reestablishing the seventh before moving to the Eb chord on beat 3. It doesn't shift voices, but it does have a similar status since it looks on the surface like it isn't resolving down like a seventh should. Indeed, there's a further delay of the standard downward resolution as the seventh hangs on as a suspension in the Eb chord, which is then itself further delayed by a decorated resolution. The ultimate resolution of the seventh introduced on beat 1 doesn't happen until the final note of the measure, after many changes of embellishing function and several surface embellishments of the embellishment.
Aside from the similarity that both voice shifting and extensive decoration cause what looks like a surface violation of the downward resolution of all sevenths, I can't explain why they're put in the same example. I'm very surprised there isn't some text explaining these details, which are an important additional example of the underlying principle of delayed resolution. Perhaps there was a breakdown during the editing process.


Show that $(P \to R) \land (Q \to R)$ is equivalent to $(P \lor Q) \to R$

Question: I have checked the answer, but do not understand one step.
$(P \to R) \land (Q \to R)$ is equivalent to $(\neg P \lor R) \land (\neg Q \lor R)$
which is equivalent  to $(\neg P \land \neg Q ) \lor R$
I don't understand the second equivalent. How to arrive to this?
Comment: As @DerekElkins pointed out, what you're trying to prove is false. Your attempt suggests that the problem actually involved $(P\to R)\land (Q\to R)$, which is equivalent to $(P\lor Q)\to R$.
Comment: @AndreasBlass Sorry. I have a typo
Answer: A different approach for the problem is to convert P,Q,R to Boolean variables and form a truth table where $0$ represents False and $1$ represents True.
\begin{array}{|c|c|} \hline
P & Q & R & P\rightarrow Q & Q\rightarrow R & (P\rightarrow Q)\land(Q \rightarrow R) &P\lor Q &(P \lor Q)\rightarrow R\\ \hline
0 & 0 & 0& 1& 1& 1& 0& 1 \\ \hline
0 & 0 & 1& 1& 1& 1& 0& 1 \\ \hline
0 & 1 & 0& 1& 0& 0& 1& 0 \\ \hline
0 & 1 & 1& 1& 1& 1& 1& 1 \\ \hline
1 & 0 & 0& 0& 1& 0& 1& 0 \\ \hline
1 & 0 & 1& 0& 1& 0& 1& 0 \\ \hline
1 & 1 & 0& 1& 0& 0& 1& 0 \\ \hline
1 & 1 & 1& 1& 1& 1& 1& 1 \\ \hline
\end{array}
So both the statements are equivalent. Hope this helps...
Another approach is to replace $P\rightarrow Q$ by $\neg P \vee Q$ and solve the expression
Answer:
$(P \to Q) \land (Q \to R)$ is equivalent to $(\neg P \lor R) \land (\neg Q \lor R)$

No, that is meant to be $(\neg P \lor Q) \land (\neg Q \lor R)$ .

which is equivalent  to $(\neg P \land \neg Q ) \lor R$

$$\begin{align}&(\neg P \lor Q) \land (\neg Q \lor R)
\\=~&((\lnot P\lor Q)\land\lnot Q)\lor((\lnot P\lor Q)\land R)\\=~& (\lnot P\land\lnot Q)\lor((\lnot P\lor Q)\land R)\\=&~ ((\lnot P\land\lnot Q)\lor(\lnot P\lor Q))\land((\lnot P\land\lnot Q)\lor R)\\=&~ (\lnot P\land\lnot Q)\land((\lnot P\land\lnot Q)\lor R)\\=&~ (\lnot P\land\lnot Q)\lor R\end{align}$$
Comment: I don't think the second line correct.
Comment: Why the second line $(\lnot P\land \lnot Q)\lor (P\land R)\lor (Q\land\lnot Q)\lor(R\land R)\\$ is so?
Comment: @GrahamKemp I am really sorry. I messed up the symbol in the question.

Can you modify the answer again? It is close.
Answer: One way is to take each pair of expressions and try to reconcile them using known rules, e.g. De Morgan's laws.
The second approach is brute force, namely using truth tables. Not particularly elegant, but it works.
In your case, the unknown variables are P, Q and R. You take 2^3 = 8 combinations of true/false for each variable, and check all your formulas yield the same answer.
You may check this by hand. Example code for Mathematica
formulaA[p_, q_, r_] := (p~Implies~q)~And~(q~Implies~r);
formulaB[p_, q_, r_] := (Not[p]~And~r)~And~(Not[q]~Or~r);
formulaC[p_, q_, r_] := (Not[p]~And~Nor[q])~Or~r;
BooleanTable[{p, q, r} -> formulaA[p, q, r], {p, q, r}] // TableForm
BooleanTable[{p, q, r} -> formulaB[p, q, r], {p, q, r}] // TableForm
BooleanTable[{p, q, r} -> formulaC[p, q, r], {p, q, r}] // TableForm
It yields something like this. Did you write your first formula correct?
{p,q,r} -> result
{True,True,True}->True
{True,True,False}->False
{True,False,True}->True
{True,False,False}->False
{False,True,True}->True
{False,True,False}->False
{False,False,True}->True
{False,False,False}->True
Answer: Work with truth values $1,\,0$ instead of true, false, so $P\lor Q=\max\{P,\,Q\}$. Then the claim is that $P,\,Q\le R$ is equivalent to $\max\{P,\,Q\}\le R$, which is trivial.


Wake on LAN for Microsoft Security Essentials?

Question: Is it possible to have an iMac (running Windows 7 via BootCamp) to Wake on LAN overnight and run a Microsoft Security Essentials scan?
Answer: Yes.
iMac's support WoL, and when they're running Windows they're just like any other EUFI-based PC, so yes you can.


Can the entropy of a random variable with countably many outcomes be infinite?

Question: Consider a random variable $X$ taking values over $\mathbb{N}$. Let $\mathbb{P}(X = i) = p_i$ for $i \in \mathbb{N}$. The entropy of $X$ is defined by
$$H(X) = \sum_i -p_i \log p_i.$$
Is it possible for $H(X)$ to be infinite?
Comment: Googling "random variable infinite entropy" gives [this](http://j.ee.washington.edu/~bilmes/classes/ee514a_winter_2012/hw2-solns.pdf) example.
Comment: @David: You could turn that into a full answer by quoting the distribution.
Answer: Consider the independent variables $ X_1, X_2 , X_3 \cdots$, where $X_k$ have non overlapping discrete uniform distributions over $2^k$ values: $X_1 \sim U[2\ldotp\ldotp3]$, $X_2\sim  U[4\ldotp\ldotp7]$, $X_3 \sim  U[8\ldotp\ldotp15]$, etc. The respective entropies are $H(X_k) = k$ bits.
Now, we pick one of the $X_k$ according to some probability mass function $m_k$ ($\sum_{k=1}^\infty m_k=1)$. That is,
$Y =X_M$ where $P(M=k)=m_k$. This is known as a mixture, with mixing distribution $m_k$, and the resulting entropy (because the components do not overlap) is
$$\begin{array}{}
H(Y)&=&H(M)+m_1  H(X_1)+ m_2 H(X_2) + m_3 H(X_3) +\cdots \\
&=& H(M) + m_1  + 2 \, m_2 + 3 \, m_3 \cdots \\&=& H(M) + \sum_{k=1}^\infty \, k \, m_k  \\&=& H(M) + E(M)
\end{array}$$
Hence, by chosing any mixing distribution $m_k$ with infinite mean ($E(M)=\sum k \, m_k=+\infty$), we attain infinite entropy. For example: $m_k=A/k^2$ (the example in David's answer essentially corresponds to this choice). Or, similarly, $m_k = \frac{1}{k}-\frac{1}{k+1}=\frac{1}{k^2+k}$
Answer: Yes, it can.
In this pdf, it is shown that the following random variable $X$ has infinite entropy:
Let $X$ take the values $2,3,\ldots$ and define $$p_n={1\over A n\log^2_2 n},\ \ \ n\ge2,$$ where $A = \sum\limits_{n=2}^\infty {1\over n\log^2_2 n}$ ($A$ is a convergent sum by the Integral Test). Then $X$ with the probability mass function $P[X=n]=p_n$, $n\ge 2$, has infinite entropy.
For completeness, I'll reproduce the argument contained in the link above  that $H(X)=\infty$ here:
We have
$$\eqalign{
H(X)&=-\sum_{n=2} p_n \log_2 p_n   \cr
&=\sum_{n=2}^\infty\bigl( -\log_2(p_n)\bigr) p_n\cr
&= \sum_{n=2}{\log_2( An \log_2^2 n  )\over A n\log_2^2 n}   \cr
&=\sum_{n=2}^\infty {{\log_2 A+\log_2 n +2\log_2(\log_2 n))}\over A n \log_2^2 n}\cr
&=\sum_{n=2}^\infty\biggl[\ \color{maroon}{\log_2 A\over A n\log_2^2 n}+\color{darkgreen}{1\over A n\log_2 n}+\color{darkblue}{2\log_2(\log_2 n)) \over A n\log_2^2 n}\    \biggr].\cr
}
$$
Now
$$
\color{maroon}{
\sum\limits_{n=2}^\infty {\log_2 A\over A n\log_2^2 n}}
={\log_2 A\over A}
\sum\limits_{n=2}^\infty {1\over  n\log_2^2 n} ={\log_2 A\over A}\cdot A=\log_2 A.
$$
and
$$
\color{darkblue}{
\sum\limits_{n=2}^\infty {2\log_2(\log_2 n)\over A n\log_2^2 n}}
$$
is a sum consisting of nonnegative terms.
It will  follow that $H(X)=\infty$, if we can show that the sum
$$
\color{darkgreen}{\sum_{n=2}^\infty {1\over An\log_2 n}}
$$
diverges to $\infty$.  But, this follows easily from the Integral Test.

(From the Integral Test, it follows that $\int_2^\infty {dx\over x\log_2^p x}$
converges if and only if $p>1$.)
Comment: Thanks! I wonder if there are sufficient (or even necessary and sufficient) conditions for entropy to be finite.
Comment: @VSJ I knew there is a sufficient condition, but the necessary condition is really nowhere that I know of, I post this question on MO. http://mathoverflow.net/questions/264401/a-necessary-condition-for-differential-entropy-to-be-finite
Comment: Don't you need to also show that the p_n add up to 1?
Comment: @PyRulez The presence of the factor $A$ in the definition of $p_n$ insures that.
Comment: @DavidMitra Oh yeah, I see now.


Tie breaker in combined climbing

Question: In Olympic combined climbing, the three scores are multiplied.
However I want to know what happens if there is a tie. Consider the following:
Climber A: 1st speed, 2nd Bouldering, 3rd lead
Climber B: 2nd speed, 3rd Bouldering, 1st lead
Climber C: 3rd speed, 1st Bouldering, 2nd lead
All three finish on 1x2x3=6 points. How is the winner decided in this case?
Answer: Googling proved surprisingly useless, but finally I just went straight to the source: https://cdn.ifsc-climbing.org/images/World_Competitions/IFSC_Rules_2020_v151_PUBLIC_compressed.pdf

each relevant competitor will be ranked in ascending order of the Ranking Point Total (i.e.
lower values are better), provided that where any competitors have the same Ranking Point
Total, the relative ranking of the tied competitors shall be determined for any round:

by comparing the head-to-head performance of such competitors within the round; and
where following (1) any competitors remain tied, by comparing:

where applicable, the Combined Ranking following the Qualification round; and/or
if necessary, the Seeding of the relevant competitors.

It's not spelled out what a "head-to-head" comparison of the performance means. In your example, I feel that the competitors have the same head-to-head performance, because they had the exact same rankings, just in different stages of the event, and they're all supposed to be of equal importance.
So then in your example, they'd be compared based on their seeding.
I guess an example with head to head comparison could be something like:
Climber 1: 1st, 1st, 6th
Climber 2: 2nd, 3rd, 1st.
According to my understanding, in this case, Climber 1 will win, because he beat the other climber twice and only lost to that other climber once.

Tie breaker in combined climbing


Black Scholes PDE

Question: How to show that $V_1(S,t)=S\frac{\partial V(S,t)}{\partial S} $ satisfies Black-Scholes PDE given as $\frac{\partial V}{\partial t} + \frac{\sigma^2 S^2}{2}\frac{\partial^2V}{\partial S^2} + rS\frac{\partial V}{\partial S} -rV = 0$ ?
Comment: I have tried to differentiate $V_1(S,t)$ and plug it in the Black-Scholes PDE, but could not produce the required relation. Any ideas?
Comment: Why do you think that $V_1(S,t)=S\frac{\partial V(S,t)}{\partial S}$ satisfies equation?
Comment: Well, I do not think, I just want to prove it. The original question is: Given that $V(S,t)$, the solution of PDE mentioned above, is infinitely differentiable in $S>0$ and $t<T$, show that $V_1(S,t)=S\frac{\partial V}{\partial S}(S,t)$ also satisfies the Black-Scholes PDE.
Answer: Let $V(S,t)$ --- solution of the PDE.
Then
$$
S\frac{\partial}{\partial S}\left(\frac{\partial V}{\partial t} + \frac{\sigma^2 S^2}{2}\frac{\partial^2V}{\partial S^2} + rS\frac{\partial V}{\partial S} -rV\right) = 0
$$
$$
S\left(\frac{\partial^2 V}{\partial t \partial S} + \frac{\sigma^2 }{2}\left(2S\frac{\partial^2V}{\partial S^2} + S^2\frac{\partial^3V}{\partial S^3}\right) + r\frac{\partial V}{\partial S} + rS\frac{\partial^2 V}{\partial S^2} - r\frac{\partial V}{\partial S} \right) = 0
$$
$$
\frac{\partial}{\partial t}S\frac{\partial V}{\partial S} + \frac{\sigma^2 S^2 }{2}\left(2\frac{\partial^2V}{\partial S^2} + S\frac{\partial^3V}{\partial S^3}\right) + rS^2\frac{\partial^2 V}{\partial S^2} = 0.
$$
Here we note that $\frac{\partial^2}{\partial S^2}\left(S\frac{\partial V}{\partial S}\right) = 2\frac{\partial^2V}{\partial S^2} + S\frac{\partial^3V}{\partial S^3}$
and $rS\frac{\partial}{\partial S}\left(S\frac{\partial V}{\partial S} \right) =
rS\frac{\partial V}{\partial S} + rS^2\frac{\partial^2 V}{\partial S^2}$.
And finally
$$
\frac{\partial V_1}{\partial t} + \frac{\sigma^2 S^2}{2}\frac{\partial^2V_1}{\partial S^2} + rS\frac{\partial V_1}{\partial S} -rV_1 = 0.
$$
Comment: Thank you. Is there any underlying idea for the first line?
Comment: Also, for this given problem, there is a boundary condition $V(S,T)=f(S)$. Is it possible to check that derived PDE also satisfies boundary condition?
Comment: The idea is "try and error". You also should change boundary condition: $V_1(S,T) = SV'_S(S,T) = Sf'(S)$
Comment: Thank you for your help. The second part of the question was to show that $\rho(S,t) = \frac{\partial V}{\partial r}(S,t)$ satisfies the following PDE:

$\frac{\partial \rho}{\partial t} + \frac{\sigma^2 S^2}{2}\frac{\partial^2 \rho}{\partial S^2} +rS\frac{\partial \rho}{\partial S} - r\rho = V - S\frac{\partial V}{\partial S}$, which I have done by following your way from the first part.
Comment: Then the question is: given that the PDE above uniquely determines $\rho$, and assuming that both $V$ and $S\frac{\partial V}{\partial S}$ are of the order $o(1/(T-t))$ as $t \to T^-$, show that $\rho(S,t) = (T-t)\Big(S\frac{\partial V}{\partial S}(S,t) - V(s,t)\Big)$.
Comment: It would be better to formulate the second part as another question (not in comments). It is kind a rule of this site.
Comment: Thank for your work Nikita. I also separated second part of the question. please find "interesting boundary problem of PDE "

Black Scholes PDE


Migration to IdentityServer 4.1 and IDX10501 error

Question: I'm currently trying a migration from IdentityServer 3.x to 4.1.1, and I have followed this
migration guide:
https://docs.abp.io/en/abp/4.0/Migration-Guides/Abp-4_0
The problem is that I got an IDX10501 error now, please have a look at the full log here:
https://github.com/abpframework/abp/issues/7452
My "old" tempkey.rsa files are still there but new files are generated "tempkey.jwk".
So, do you think it is related? and how can I change this?
At the end, my goal is just to fix this IDX10501 error... any idea is welcome.
Answer: Tempkey.jwk is generated by this command
<code>builder.AddDeveloperSigningCredential();
</code>
and this is fine for development but not in production.
The error you get is that the key is not found in the JWKS endpoint. You need to use the AddSigningCredential method to add your old key as the signing key.
The kid claim found in the tokens must match what you see from the /.well-known/openid-configuration/jwks endpoint.


Partial fractions, disagreement with Wolfram Alpha

Question: On my math homework, I have this problem, and WolframAlpha says that $A=-\frac{1}{7}$ and $B=\frac{1}{7}$. However, while solving the problem on my own, I found a restriction that $A \neq -B$. How is it that this answer works? The problem in question is:
$$\dfrac{1}{x^2 - 3 x - 10} = \dfrac{A}{x+2} + \dfrac{B}{x - 5}$$
Comment: If you managed to solve for $x$, then you were doing the wrong problem. The problem is to find $A,B$ so that the equation holds for *all* $x$. It's a little like saying you solved for $x$ in $x+x=Ax$.
Comment: How did you come up with your restriction?
Comment: Your link solves your own question. Look at the line beneath the $A=-\frac 17$ etc, and you see a second condition from which answers surface.
Comment: while solving the problem, I managed to solve for x. The denominator was A+B, and the denominator cannot be 0, so A≠-B
Comment: For large $x$ the fraction will tend to zero as $\sim 1/x^2$, while each term in the partial fraction expansion goes to zero as $\sim 1/x$. This means that the leading asymptotic behavior of the two terms must cancel out and that means that A must equal minus B.
Comment: @GerryMyerson It is more like solving $0x+1=1$ for $x$.
Answer: Here's the full derivation: $$\frac{1}{x^2-3x-10}=\frac{A}{x+2}+\frac{B}{x-5}\implies$$ $$(x+2)(x-5)\left(\frac{1}{x^2-3x-10}\right)=(x+2)(x-5)\left(\frac{A}{x+2}+\frac{B}{x-5}\right)\implies$$ $$1=A(x-5)+B(x+2)=A(x)-5A+B(x)+2B=x(A+B)+1(2B-5A)$$
Hence we need $A+B=0\space\text{and}\space2B-5A=1$. So substitute $A=-B$ into the second equation: $$2B-5(-B)=1\implies7B=1\implies B=\frac{1}{7}$$
But we have the condition that $A+B=0$ and we know $B=\frac{1}{7},$ hence $$A+\frac{1}{7}=0\implies A=-\frac{1}{7}$$ Thus $$\frac{1}{x^2-3x-10}=\frac{A}{x+2}+\frac{B}{x-5}=\frac{1}{7(x-5)}-\frac{1}{7(x+2)}$$
Comment: Alternatively, once you get to $1=A(x-5)+B(x+2)$, you can substitute $x=5$ to get $B=1/7$, and $x=-2$ to get $A=-1/7$.
Answer: To find $A$ and $B$:
Note that
$(x + 2)(x - 5) = x^2 -3x - 10; \tag 1$
then from
$\dfrac{1}{x^2 -3x - 10} = \dfrac{A}{x + 2} + \dfrac{B}{x - 5} \tag 2$
we have
$A(x - 5) + B(x + 2) = \dfrac{(x + 2)(x - 5)}{x^2 -3x - 10} = 1; \tag 3$
this may be written
$(A + B)x + (2B - 5A) = 1, \tag 4$
whence
$A + B = 0 \Longrightarrow B = -A, \tag 5$
so that
$-7A = 2(-A) - 5A = 2B -5A = 1 \Longrightarrow A = -\dfrac{1}{7}, \; B = \dfrac{1}{7}; \tag 6$
we check:
$\dfrac{A}{x + 2} + \dfrac{B}{x - 5} = -\dfrac{1}{7}\dfrac{1}{x + 2} + \dfrac{1}{7}\dfrac{1}{x - 5} = \dfrac{1}{7} \left ( \dfrac{1}{x - 5} - \dfrac{1}{x + 2} \right )$
$= \dfrac{1}{7}\left ( \dfrac{x + 2}{x^2 -3x - 10} - \dfrac{x - 5}{x^2 -3x - 10} \right ) = \dfrac{1}{7}\dfrac{7}{x^2 -3x - 10} = \dfrac{1}{x^2 -3x - 10}. \tag 7$
Answer: When you "solved for $x$," I presume you got something like $$(A+B)x=5A-2B+1$$ and then said, now we must divide both sides by $A+B$, but that's only allowed if $A+B\ne0$. But in fact the displayed equation is not meant to be solved for $x$; it's meant to hold for all values of $x$. The only way that can happen is for both $A+B$ and $5A-2B+1$ to be zero. That leads, as in the other answers that have been posted, to what Wolfram gave you.
Now, you ask, "How is it that this answer works?" Well, it's very easy to see how it works: you just work out $${-1/7\over x+2}+{1/7\over x-5}$$ and see that you get $1/(x^2-3x-10)$.


Alter markup around a webform

Question: I have been trying to alter the markup generated by my webform. .
Example changes which I would like to do:

Add the class "form-horizontal" to the classes under <form class=""/>.
Add the class "input-xxlarge" to each input field.
Remove any markup generated by the webform module (e.g. form-item, webform-component, webform-component-textarea).

I've been trying to override these values with the help of Devel. Using webform-form-[nid].tpl.php, I have the following line before I make any print statements:
$form['#attributes']['class']['0'] = 'form-horizontal';

The issue is that I can not alter the form classes. Any insight that can be shared would be highly appreciated!
Answer: Have you tried theme_form_element ?

Returns HTML for a form element.

This hook is used to alter the thme of form element in Drupal.
Check theme_field as well.
How to theme form element in Drupal 7
Comment: theme_form_element was the key that I was missing. Using this, I was able to add new classes to a field.
Comment: how it is possible in drupal 8

Alter markup around a webform


Action Bar Sherlock doesn't keep transparency when orientation is changed from portrait to landscape

Question: I'm using Android Sherlock in one project where I show a VideoView. When the screen orientation is portrait, the video and some text is shown. When is landscape, only the video in fullscreen is shown.
Well, my doubt is: why the alpha color (of the Sherlock Action Bar) is shown when the orientation is portrait, but changes it's alpha property (becames opaque) when the orientation is landscape?
My onCreate() is showed below:
public void onCreate(Bundle savedInstanceState) {
    // Makes action bar become translucent, and sets layout of this activity.
    requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);
}

Well, I'm using requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY), which allows the alpha color in the action bar.
When the orientation changes, I call onConfigurationChanged(), which calls setScreenLayout(). This method sets the video size and change the action bar background color.
/**
 * Sets the screen layout, according with the current orientation.
 *
 * @param isInLandscapeMode
 */
public void setScreenLayout(Boolean isInLandscapeMode) {
    // If orientation is landscape.
    if (isInLandscapeMode) {
        // Hides text of the layout.
        mTextScrollView.setVisibility(View.GONE);
        // Set the size of the video.
        setVideoDimensions((int)Math.floor(mWindowWidth * (1 / WIDESCREEN_RATIO)), mWindowWidth);
        // Sets window to full screen.
        setWindowToFullScreen();
        // Sets action bar background color.
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.bg_translucent_black));
    }
    // If orientation is portrait.
    else {
        // Shows text of the layout.
        mTextScrollView.setVisibility(View.VISIBLE);
        // Set the size of the video.
        setVideoDimensions(mWindowWidth, (int)Math.floor(mWindowWidth * WIDESCREEN_RATIO));
        // Sets window to normal screen.
        setWindowToNormalScreen();
        // Sets action bar background color.
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.bg_translucent_black));
    }
}

This color is set in res/colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="bg_translucent_black">#11EEEEEE</color>
</resources>

In my AndroidManifest.xml, I set the VideoActivity with the android:configChanges="orientation" property, which allows the video to continue playing if the orientation is changed.

<activity
    android:name=".VideoActivity"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:configChanges="orientation"
/>

Therefore, when the orientation is changed, the onCreate() isn't call.
I think what is happening is that the requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY) allows the alpha only in the first orientation when the activity is created (in this case, in portrait). This way, the landscape orientation doesn't became alpha color. But I'm not sure.
What I'm sure is that I need the alpha color of the action bar in both orientations.
Anybody knows if is possible for my video to have alpha color in both orientations?
Answer: I believe ActionBarSherlock needs Android to handle the configuration changes, and not your app. Using the android:configChanges "hack" and ActionBarSherlock together in one app isn't possible.
Comment: Well, so how can I have two different alpha color in my Action Bar, for both orientations of my video?
Comment: Get the orientation of the device in the onCreate of your Activity, and set the alpha color of your ActionBar dynamically that way.
Comment: The default orientation of my video activity must be portrait. So, I won't get the orientation. I'll just get it after the video starts (when the flip could be done).
The matter is that the alpha isn't working (and I need two different alpha's for each orientation while the video is playing).
The alpha works only after onCreate() being called. But in this activity I'm using **android:configChanges="orientation"** in the AndroidManifest, which prevents the onCreate() to be called when the orientation changes.
Comment: I need the same behavior of the youtube app (in portrait mode the action bar is translucent and in landscape also, but fullscreen).
In ICS this flip pauses the video and then restarts in the new orientation (from where it stopped). In my app I can't use this process because it must run in API's 7 to 10, which has slower processing. Many times this process (pause video, flip cel, restart video) causes delay into the video.
My only alternative is to change the action bar alpha when the cel flips, which isn't working.
Comment: To get the same behavior as the youtube app, you can't use configChanges="orientation". ActionBarSherlock relies on this to redraw it's Views. It's either you take out the configChanges hack, or you don't use ActionBarSherlock.


Facebook Graph API Message - Word or Character Limit

Question: I have used PHP, json and API Cache to successfully show a Facebook Feed Message on a website. However some of the messages are too long to fit into the space provided on the website.
Does anyone know if there is a way to limit the amount of Words or Characters the message will display?
Best scenario would to have the message show fully if below limit and then show certain amount of words or characters i over followed by [...] read full post @pagename
Then I can add the link to the Facebook post to view full message. I know how to add the post link and text, just need to scale the message down.
Here is the PHP code I am using:
<?php $fb_message = $fb_json->data[0]->message; ?>
<?php echo $fb_message; ?>

Any help would be greatly appreciated.
Thanks,
Steve

Thanks to James Pearce I was able to get it working using the following code:
<?php $fb_message = $fb_json->data[0]->message; $truncated = substr($fb_message, 0, strrpos(substr($fb_message, 0, 100), ' ')); echo $truncated . '...'; ?>

It works if the message is more than 100 characters, but if it is less it will only show the first word and no more....?
Anyone know what I am doing wrong?
Comment: that code above works for me, perfectly
Comment: added another concise alternative in the answer if you want to accept it
Answer: There is no way to get the Facebook API to truncate the string for you. However, there are lots of ways you can do this in PHP.
One simple way is using the wordwrap function (http://www.php.net/wordwrap) and taking everything before the first line break.
See also How to Truncate a string in PHP to the word closest to a certain number of characters?
This seems work fine:
<?php
    $fb_message = $fb_json->data[0]->message;
    echo array_shift(explode("\n", wordwrap($fb_message, 100)));
?>

Comment: Thanks James, that headed me down the right path. I have it working for messages that are longer than 100 characters, but not working if shorter. I posted the code and new problem under my original one. Any further help would be great.
Answer: Here is the code I used to check how long the Facebook "message" field is and then to either truncate it, if it is longer than 100 characters, or display the whole thing if it is short enough:
$post->message = $fbdata->data[0]->message;
$messageLength = strlen($post->message);
if ($messageLength < 100) {
     $outputMessage = $post->message;
} else {
     $outputMessage = substr($post->message, 0, strrpos(substr($post->message, 0, 100), ' ')) . ' ...';
}
echo $outputMessage;


COMPARISONS OF ODDS RATIOS

Question: For example, if I have 3 different trials each for 3 different drugs and I used meta analysis (sub group analysis) to generate effect sizes. How can I interpret the effect sizes? All drugs are being compared to placebo e.g.
Drug A - 3 RCTs - pooled odds ratio 1.5
Drug B - 3 RCTs - pooled odds ratio 1.7
Drug C - 3 RCTs - pooled odds ratio 3
I am aware of network meta analysis but I was suggested to avoid this as it's not necessary for my project. I am able to make simple indirect comparisons as long as I state the limitations.
Firstly, would I be able to say, drug C had the greater effect compared to placebo (at a particular outcome) so can be considered the better of the three drugs, though head to head trials are necessary to confirm this.
What are the general limitations of this method?
I have tried to ensure the studies I have used are as similar in the design as possible. All comparing to a common comparator, placebo.
Also should I make comments on the heterogeneity between the 3 studies used for each drug.
Also should I do this using a random or fixed effects model?
Answer: To test whether the odds ratios are different, you could run a meta-analysis on all 9 RCTs and test drug type as a moderator, with drug 3 set as the reference group. If it's significant, you could say it has the greater effect relative to placebo. Personally, I would comment on heterogeneity for this single analysis. You can't conclude that these odds ratios are different from each other without at least examining their confidence intervals.
Whether you want to use a fixed or random effects model depends on whether you believe that the studies all estimate one true effect size and the only source of differences is random error, in which case you'd want fixed effects, or whether you believe it's possible that the true effect size differs from study to study. Assuming the studies aren't sampling the same population, you likely want to use random effects meta analysis.
Source: Borenstein, Hedges, & Rothstein, 2007

COMPARISONS OF ODDS RATIOS


Lasso and Ridge Regression: Variance and Bias

Question: I  am studying about learning methods in statistics and the regression section explains that the main difference between Lasso and Ridge regressions is the formulation of the regularization term, which for Lasso is the ℓ1 norm, and for Ridge the ℓ2 norm.
Given that Lasso regression shrinks some of the coefficients to zero and Ridge regression helps us to reduce multicollinearity, I could not gain a grasp of the effects of these regularization methods on variance and bias.
I am looking for a possible mathematical or intuitive explanation of how variable elimination affects model variance and bias.
Answer: They both use regularisation, which tends to shrink the regression coefficients towards zero, and in doing so introduce bias but can reduce variance.  They can handle multicollinearity and even having more predictors than observations.
The hope is that they can reduce the mean square error (sum of variance and the square of bias) on out-of-sample predictions. Their effects can be adjusted through tuning;  cross-validation can be used as a tool to tune and even to choose between them or to choose some intermediate method such as elastic net.
As you say, the biggest noticeable difference between them is that Lasso often reduces some of the regression coefficients to $0$ in situations where Ridge regression does not.  Which works better in different situations is often an empirical rather than a theoretical question.


Reference request: Relativizing a formula with respect to a predicate in first order logic

Question: I am looking for a reference to the following, I searched far and wide but perhaps I am using the wrong terminology or something.
Let $\tau$ be a relational vocabulary. For $\mathfrak{A}$ a structure in $\operatorname{Struct}(\tau)$, $P(x,y)$ a predicate and $y$ in the domain of $\mathfrak{A}$, let $\mathfrak{A}^{P(\cdot, y)}$ be the induced substructure of $\mathfrak{A}$ with domain consisting of $y$ and all $x$ such that $P(x,y)$ is true. The result I want is that for every FO formula $\phi(x_1,\ldots, x_j)$ there is a formula $\phi^{P}(y,x_1,\ldots, x_j)$ such that for all $(y,x_1,\ldots, x_j)$ in the domain of $\mathfrak{A}$ with $P(x_i,y)$ true for all $i\in [j]$, we have
$$ (\mathfrak{A},y,x_1,\ldots, x_j)  \models \phi^P\quad\text{iff}\quad (\mathfrak{A}^{ P(\cdot, y) },x_1,\ldots, x_j)\models \phi. $$
This formula should likely be obtained by replacing in $\phi$ every occurrence of $\exists x \psi$ by $\exists x ( P(x,y) \rightarrow \psi)$ and similarly for $\forall$.
I managed to prove something to this effect myself already. However, I know this is (a simple variant of) a fairly simple result, and $\phi^P$ is sometimes called the relativization of $\phi$. But I need the result as a reference, so I would rather just refer to somewhere where it is clearly stated instead of proving it myself. Wherever I found this technique the authors simply state it as fact or hand wave.
Note: I am working with a relational vocabulary, this is not strictly necessary but is there to omit some requirements that the constants be in $\mathfrak{A}^{P(\cdot,y)}$ and similar problems for functions.
Comment: @AtticusStonestrom It will be used in a paper. That's why I would like a reference instead of the proof I did mysefl :) Especially since I just need for a small 'technicality'
Comment: hi Permuton. may I ask what the context where you will be using this is? (is it in a paper, an assignment, lecture notes, etc...?)
Comment: that makes sense! :) I don't know of a reference, though I'm absolutely sure there is one... but in the worst case if you're not able to find one it doesn't seem completely out of the question to me to just write "the relativization of $\phi$ to $P$"!
Comment: (eg you could just give the inductive definition of $\phi^P$, and then write a remark along the lines of "a proof by induction shows ...etc")
Answer: See Theorem 5.1.1 in Hodges Model Theory (p. 203) or Theorem 4.2.1 in Hodges A Shorter Model Theory (p. 101). Hodges only discusses the case of relativization to a unary predicate $P(x)$, but you can obtain your version parameterized by $y$ by just replacing $P(x)$ everywhere by $P(x,y)$.
By the way, what you suggested is not quite right: $\exists x\psi$ should be replaced by $$\exists x(P(x,y)\land \psi),$$ while $\forall x\psi$ should be replaced by $$\forall x(P(x,y)\rightarrow \psi).$$
Comment: Thanks for the reply. I had already found this reference but expanding to binary predicates and explaining that the logic Hodges uses includes FO takes roughly the same amount of space as a proof :) I should probably accept that there will no reference saying precisely what I need.
Comment: @Permuton I agree with Atticus in the comments that for a research paper, stating the result and giving a reference to Hodges with no further explanation would be sufficient. Most readers will know what you mean by "the relativization of $\phi$ to $P$", and if they don't, they should be able to fill in the details for themselves after looking at Hodges. One is allowed to expect a bit of mathematical maturity from the reader of a research paper.


View doesnt work properly when logged out

Question: I have a question about a problem I met. I'm working on Drupal 7 site that has a menu made with a view but for some reason the structure of menu is totaly different when user is logged in than when the user is logged out.
Everything works fine when I'm logged as admin but when I logged out it seems like some of configurations doesnt load. I don't have any errors in console.
I`m not sure what kind of informations from view I can share or will be usefull so I will add every need informations which you asked for.
Adding a code from inspect:
Image with both inspects
Comment: In the view check the 'Access' settings. Maybe there are restrictions based on the role.
Answer: A possible cause is that anonymous users don't have access to the content or fields. The inspect images aren't helpful to determine what permissions could be missing. In the UI, go to People > permissions and check that:

Anonymous users can see published content
If there are field-level permissions, anonymous can see all the fields involved in the view
There aren't restrictions to access the view (this is unlikely, the view wouldn't render at all)


Nomeando subblocks de qualquer metablock com uma única classe?

Question: Estou tentando fazer com que apenas uma classe seja necessária para nomear os subblocks de qualquer metablock que usar essa classe na hora do registro, ou seja, nomeá-los como se fossem valores de parâmetro, mas sem usar um.
Apesar de isso girar em torno de uma API (Minecraft Forge), acho que o problema é mais de Java, então faço aqui uma breve explicação de como funciona o que tenho intenção de fazer.
Um metablock é composto de subblocks, que são variações do mesmo bloco (como por exemplo, o mesmo bloco, mas que só muda a textura e o nome). Cada subblock precisa de um nome para o identificar. Esses nomes são listados na classe ExemploItemBlock em uma String[], e depois são nomeados no formato nomeDoMetablock.nomeDoSubBlock (ex.: ExemploMetablock.azul, ExemploMetablock.verde, etc.), com
// Classe ExemploItemBlock

public static final String[] SUBNAMES = new String[] {"azul", "verde", "amarelo"};

@Override
public String getUnlocalizedName(ItemStack itemStack)
{
    int i = itemStack.getItemDamage();
    return getUnlocalizedName() + "." + SUBNAMES[i];
}

Depois o metablock ExemploMetaBlock é instanciado e registrado com
// Classe onde são feitos os registros

public static Block ExemploMetaBlock = new ExemploMetaBlock();

GameRegistry.registerBlock(ExemploMetaBlock, ExemploItemBlock.class, "ExemploMetaBlock");

Após isso, tudo funciona sem problemas, porém eu teria que criar uma classe ItemBlock para cada metablock novo que eu quiser fazer, e não acho isso muito prático ou apropriado, achando melhor criar uma única classe para ser usada por qualquer metablock futuro.
Como é possível perceber, o segundo parâmetro do método GameRegistry.registerBlock() (que é um método da API) requer um valor do tipo Class. E é aí que está o problema: como vou tornar a classe ExemploItemBlock dinâmica sem usar instâncias?
Eu até tentei adicionar um parâmetro String[] no construtor da ExemploItemBlock e usar uma instância com os nomes no lugar do nome da classe, mas como era de esperar, acusou incompatibilidade de tipos, pois é apenas Class o tipo aceito.
Eu procurei por toda parte um jeito de fazer isso, mas só encontrei dois jeitos:
1. criar uma classe ItemBlock para cada novo metablock;
2. trocar SUBNAMES[i] no getUnlocalizedName() por i ou itemStack.getItemDamage() nomeando assim os subblocks por números ao invés de nomes (ex.: ExemploMetaBlock.0, ExemploMetaBlock.1, etc.), sem precisar usar o String[] nem nada e se tornando uma classe universal. Porém esse jeito também é bem antiprático, porque depois dificulta bastante na hora de identificar qual subblock é qual.
Então minha pergunta é: há algum jeito de se conseguir uma classe ItemBlock universal, mas nomear os subblocks por nomes (palavras)?
Conteúdo das classes: ExemploMetaBlock, ExemploItemBlock.
Answer: Acabei encontrando a solução no próprio Forge, como pode ser acompanhado aqui.
Mas pelo bem da informação, vou dar uma explicada sobre a solução.

Não sabia, mas o método GameRegistry.registerBlock() também aceita um quarto parâmetro, do tipo Object[]. Então basta colocar a lista com os nomes dentro do Object[], apenas iniciar a variável String[] da ExemploMetablock, e passar os valores definidos no parâmetro Object[] para a variável String[]. Ficando assim:
public static String[] SUBNAMES;
private IIcon[] icon;

public ExemploMetaBlock(Material material, String name, CreativeTabs tab, String[] subnames)
{
    super(material, name, tab);
    SUBNAMES = subnames;
}

E ao invés de usar a classe ExemploItemBlock, uma classe criada separada, no parâmetro Class, recomendo que use no lugar uma classe que já existe no próprio código do Minecraft e que faz praticamente a mesma coisa que o ExemploItemBlock, que é a classe ItemMultiTexture (isso caso não tenha nada a mais que não tenha na ItemMultiTexture). Ficando o registro assim:
public static final String[] SubNames = new String[] {"azul", "verde", "amarelo", "vermelho"};
public static Block ExemploMetablock = new ExemploMetablock(Material.rock, "ExemploMetablock", Tabs.ExemploModTab, SubNames);

GameRegistry.registerBlock(ExemploMetablock, ItemMultiTexture.class, "ExemploMetablock", new Object[]{SubNames});

Porém, isso não compilará. Ocorrerá o erro NoSuchMethodException na linha do registro (GameRegistry.registerBlock ....).
O construtor da classe ItemMultiTexture pega os valores definidos nos parâmetros do método registerBlock() que correspondem com os tipos dos parâmetros de seu construtor, que são Block, Block, String[].
Foi informado um String[]? Sim. Foi informado um Block? Sim. Foi informado um segundo Block? Não. "Não há tal método", não há um construtor da ItemMultiTexture com parâmetros Block, String[].
Isso acontece porque, como foi dito, o construtor da classe ItemMultiTexture requer dois valores Block.
Para resolver isso, simplesmente crie uma nova classe (ou substitua a ExemploItemBlock) estendendo ItemMultiTexture e que super os dois Blocks no parâmetro. Ficando assim:
public class ItemMultiTextureHelper extends ItemMultiTexture
{
    public ItemMultiTextureHelper(Block block, String[] names)
    {
        super(block, block, names);
    }
}

E o registerBlock() assim:
GameRegistry.registerBlock(ExemploMetablock, ItemMultiTextureHelper.class, "ExemploMetablock", new Object[]{SubNames});

E uma última coisa, mas não menos importante: remova o modificador static do SUBNAMES, caso contrário isso causará a maior bagunça nos metablocks futuros, como por exemplo, todos os sub-blocks dos metablocks sendo nomeados com os nomes dos do primeiro metablock criado, sub-blocks repetidos, etc. (Eu passei por esses problemas agora mesmo, e corrigi removendo o static.) Então o correto é, na verdade, assim:
public String[] SUBNAMES;


single clean to check variable is not 'undefined' and undefined

Question: I am using node backend. I have some typescript code where I have a variable that sometimes print as string 'undefined' instead of just being undefined (in some cases). Is there a single clean check to ensure that the variable is NOT equal to 'undefined' and undefined. It doesnt look very clean to do it like:
    if (xxx && xxx!= 'undefined') {}
Comment: https://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript
Answer: You could create a string:
if(String(one) === 'undefined') {
    // true for undefined and 'undefined'
}

Here are some things to consider.
The first option, which creates a string, has the benefit of not giving false positives for other falsey values such as null and false and has the cost of perhaps being harder to understand.
The second option, which performs two comparisons, has the benefit of being easier to understand and has the cost of giving false positives for falsey values such as null, 0, and false.
The third option, which performs more involved comparisons, has the benefit of being easier to understand and the cost of being a longer expression.

const one = undefined;
const two = 'undefined';
const three = 0;

// creating a new string
if(String(one) === 'undefined') console.log("one is undefined");
if(String(two) === 'undefined') console.log("two is undefined");
if(String(three) === 'undefined') console.log("three is undefined");

// doing two checks; this seems easier to understand
// but returns false positives
if(!one || one === 'undefined') console.log("one is undefined");
if(!two || two === 'undefined') console.log("two is undefined");
if(!three || three === 'undefined') console.log("three is undefined"); // false positive

// doing two checks; this seems easier to understand
// but the expression is longer
if(one === undefined || one === 'undefined') console.log("one is undefined");
if(two === undefined || two === 'undefined') console.log("two is undefined");
if(three === undefined || three === 'undefined') console.log("three is undefined");


Django 1.11. Servir arquivos tipo robots.txt, sitemap, etc

Question: Preciso saber como servir esses arquivos que geralmente vão pra raiz do projeto.
Estou fazendo uma rota para cada um deles no arquivo urls.py mas não me parece a forma correta.
Qual é o jeito certo?
Comment: 'Esses arquivos' você quer dizer arquivos estáticos ? -  Servir sobre qual contexto? Local ou produção ?
Comment: @OtávioReisPerkles acredito que sim, sejam estáticos. Seria em produção. Todo arquivo que mandam eu tenho que criar uma rota pra eles e jogá-los na pasta templates e não acho que isso seja certo. Na teoria seria só colocar na raiz e estaria de boa.
Comment: Está falando sobre ter uma pasta separada só pros arquivos estáticos? Já viu essa [página](https://docs.djangoproject.com/pt-br/2.0/howto/static-files/) na documentação?
Answer: Geralmente o mais correto é delegar essa tarefa para o Nginx ou Apache, que na maioria dos casos já vão estar servindo os arquivos estáticos do projeto.
Caso esteja utilizando Nginx, segue um exemplo:
server {
  server_name example.com;

  access_log /opt/example.com/logs/nginx_access.log combined;
  error_log /opt/example.com/logs/nginx_error.log;

  location /static/ {
    alias /opt/example.com/static/;
  }

  location /media/ {
    alias /opt/example.com/media/;
  }

  location = /favicon.ico {
    access_log off;
    log_not_found off;
    rewrite (.*) /static/img/favicon.ico;
  }

  # restante do arquivo de configuração...

}

Eu costumo usar essa configuração para favicon.ico, robots.txt e algumas vezes para o sitemap.xml quando este é estático. Se sua aplicação for uma voltada para conteúdo SEO é importante, talvez valeria a pena considerar o sitemaps framework, que faz parte das apps Django.
Mas, voltando à sua pergunta. O exemplo acima seria para o Nginx. Caso esteja usando Apache, segue um exemplo retirado da documentação oficial:
Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
Require all granted
</Directory>

<Directory /path/to/mysite.com/media>
Require all granted
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>


Is index function in to_csv I have used correctly according to problem statement?

Question:
Problem Statement :
1) Create another Series named heights_B from a 1-D numpy array of 5 elements derived from the normal distribution of mean    170.0 and standard deviation 25.0.
Note: Set random seed to 100 before creating heights_B series. Use numpy.
2) Create another Series named weights_B from a 1-D numpy array of 5 elements derived from the normal distribution of mean    75.0 and standard deviation 12.0.
Note: Set random seed to 100 again before creating weights_B series. Use numpy.
3)Label both Series elements with s1, s2, s3, s4 and s5.
4)Create a dataframe df_B containing the height and weight of students s1, s2, s3, s4 and s5 belonging to class B.
5)Label the columns as Student_height and Student_weight respectively.
Write the contents of df_B without the index to a CSV file named classB.csv.
Note: Use the index argument of to_csv method.
Solution :

import pandas as pd
import numpy as np
import random
height_A=np.array([176.2,158.4,167.6,156.2,161.4])
s1=pd.Series(height_A,index=['s1','s2','s3','s4','s5'])
weight_A=np.array([85.1,90.2,76.8,80.4,78.9])
s2=pd.Series(weight_A,index=['s1','s2','s3','s4','s5'])
df={'Student_height':s1,'Student_weight':s2}
hdf=pd.DataFrame(df)
random.seed(100)
x=np.random.normal(loc=170.0,scale=25.0,size=5)
s3=pd.Series(x,index=['s1','s2','s3','s4','s5'])
random.seed(100)
y=np.random.normal(loc=75.0,scale=12.0,size=5)
s4=pd.Series(y,index=['s1','s2','s3','s4','s5'])
df1=df={'Student_height':s3,'Student_weight':s4}
hdf1=pd.DataFrame(df1)
hdf1.to_csv('classB.csv',index=False)

I have written code according to problem statement but online compiler is not accepting my solution , please tell me if I have done any mistake.
Answer: add one more line to code
m = pd.read_csv("classB.csv"); print(m)

Answer: Use this code :
import os
import numpy as np

np.random.seed(100)
x=np.random.normal(loc=170.0,scale=25.0,size=5)
np.random.seed(100)
heights_B=pd.Series(x,index=['s1','s2','s3','s4','s5'])
np.random.seed(100)
y=np.random.normal(loc=75.0,scale=12.0,size=5)
weights_B=pd.Series(y,index=['s1','s2','s3','s4','s5'])
df_B = pd.DataFrame({'Student_height': heights_B,'Student_weight':weights_B}, index = weights_B.index)
df_B.to_csv("classB.csv",index=False)
os.system("cat classB.csv")


Como suprimir o retorno de curl_init php?

Question: Essa mesma função coloquei numa outra pergunta por outro motivo, nesta pergunta estou querendo suprimir o texto que o $result devolve:
...
$fields = http_build_query($data);
$post = curl_init();

$url = $url . '?' . $fields;
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_RETURNTRANSFER, false);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($post);

curl_close($post);

Acontece que o REST no servidor onde não tenho acesso direto, sempre devolve uma mensagem (string) além do true e false, eu precisava suprimir essa mensagem pois ela me atrapalha na construção do html que preciso mostrar ao usuário...
Tentei curl_setopt($post, CURLOPT_RETURNTRANSFER, false);
Mas não surtiu efeito, estou começando a usar esse curl_init agora
O que eu preciso é simplesmente saber se o $result é true ou false
Answer: Use o curl_setopt($post, CURLOPT_RETURNTRANSFER, 1) para que não seja mostrado o resultado da requisição ou curl_setopt($ch, CURLOPT_NOBODY, 1) se o corpo da resposta for insignificante.
Para saber se a requisição foi bem sucedida, ou não, poderá acrescentar o curl_setopt($ch, CURLOPT_FAILONERROR, 1) para que o $result seja false se o HTTP Code for >= 400. Entretanto, o HTTP Code for 300 ele não irá seguir a requisição, acrescente o CURLOPT_FOLLOWLOCATION se houver necessidade.
Para então comparar faça um $result !== false:
$fields = http_build_query($data);
$post = curl_init();

$url = $url . '?' . $fields;
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);

// Acrescentado:
curl_setopt($post, CURLOPT_FAILONERROR, 1)
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1)
curl_setopt($post, CURLOPT_NOBODY, 1)

$result = curl_exec($post);
$info = curl_getinfo($post);
curl_close($post);

if($result !== false){
   echo 'Erro com código de ' . $info['http_code'];
}else{
   echo 'Requisição bem sucedida';
}

Estou ignorando possíveis problemas de segurança e não testei o código.
Comment: Deu certo, valeu


Why am I getting a "page not found" error for this implementation of hook_menu()?

Question: Here's the implementation of hook_menu() in my theme, "myTheme":
function myTheme_menu() {
    $items = array();
    $items['ajax'] = array(
        'title' => 'AJAX',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    $items['blog'] = array(
        'title' => 'sonia blog',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

example.com/ajax is working fine, but example.com/blog is returning me a "page not found" error. I have cleared my cache.
Do you have any idea about what is going wrong?
EDIT
One of the commenters suggested that I need a page_callback property. However, the documentation on hook_menu does not say that it's required. Regardless, I tried adding this callback but still no luck. Here's the code with it:
function myTheme_menu() {
    $items = array();
    $items['blog'] = array(
        'title' => 'sonia blog',
        'access arguments' => array('access content'),
        'page callback' => 'myTheme_callback_blog',
        'type' => MENU_CALLBACK
    );
    return $items;
}

function myTheme_callback_blog(){
    return '';
}

Comment: Both your menu items are missing the `page callback` property, see [`hook_menu()`](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7) for more details
Comment: `/blog` is used by the core Blog module
Comment: Are you sure `/blog` is not already defined by another module ? Did you try another path, just for checking ?
Comment: Are you defining this in a *theme* or a *module*?
Comment: @maxedison It's only not required if the item can inherit the page callback from a parent item. So if the path 'page' has a `page callback` then the path `page/sub-page` will inherit it. Otherwise its required or Drupal has no function to run to get the page content :) Not sure why the `ajax` path works though so maybe that's not quite right. As others have said though, `blog` is already a defined path so you need to alter it in `hook_menu_alter()` rather than redefine it
Comment: My ! How could I miss that ?
Comment: @Clive -- I didn't think this was a required property. Certainly the documentation for hook_menu() doesn't specify it as such. And the fact that the `ajax` menu entry works fine also suggests that this isn't the issue. Regardless, I added a page_callback and it still doesn't work (see edit to my post).
Comment: @MPD - in a theme.
Comment: @Laxman13 -- I don't have that module enabled.
Answer: I believe you cannot define a hook_menu() implementation in a theme; it should be defined in a module.
When you make changes to a hook_menu() implementation, you need to ensure that you rebuild the menu router, as well. To that end you can manually look at your database's "menu_router" table to see if the callback is being registered.
Comment: This is correct; a theme can implement `hook_menu_alter()` on Drupal 7, but it cannot implement `hook_menu()`.
Answer: You are trying to implement these in a theme, which will not work; you need to add these in a module.
See How to use hook_user_login and hook_user_logout to output content to the page.


If $a,b,p,q$ are non-zero real numbers, then the 2 equations $2a^2x^2-2abx+b^2=0$ and $p^2x^2+2pqx+q^2=0$ have...

Question:
If $a,b,p,q$ are non-zero real numbers, then the 2 equations $2a^2x^2-2abx+b^2=0$ and $p^2x^2+2pqx+q^2=0$ have:
  (a)no common root
  (b)two common roots if $3pq=2ab$
  (c)one common root if $2a^2+b^2=p^2+q^2$
  (d)two common roots if $3qb=2ap$

Okay so the answer given is 'no common root'. How I approached the question...I used the condition for common root which gives me
$$(b^2p^2-2a^2q^2)^2=(-2abq^2-2b^2pq)(4a^2pq-2abp^2)$$
Now I don't know how to prove that this equation can't be satisfied for any values of $a,b,p,q$.
Comment: Consider the discriminant in the first equation being a negative times some squares of $a$ and $b$ and thus has no real roots.
Answer: Hint: the second equation is $\,(px+q)^2=0\,$ then substituting $\,x=-q/p\,$ into the first one gives $\,a^2q^2 + (aq+pb)^2=0\,$.


Binary expansion and bijection

Question: Using the idea of binary expansion ($1011$ is $1\cdot2^0 + 1\cdot2^1+0\cdot2^2+1\cdot2^3 = 11$) to find a bijection that
(a) maps $\mathbb{N}$ to the set of all finite subsets of $\mathbb{N}$
(b) maps the set of all finite subsets of $\mathbb{N}$ to $\mathbb{N}$
For (a) I am looking at a table of the first $30$ $\mathbb{N}$ and trying to figure out how I can map that into {{1},{2},{3}...{n},{1,1},{1,2},{1,3}...{1,n} and so on}, but I am drawing a complete blank. Any suggestions would be greatly appreciated!
Answer: For any natural number $n$ written in base 2, you can construct the finite subset of $\mathbb N$ $f(n)$ such that

$\forall p\in \mathbb N$, $p \in f(n)$ if and only if the $p$th number of $n$ is $1$.

For example, if $n=13$, ie $n=1101$ in binary, then $f(n)$ is the set $\{0,2,3\}$ (the $0$th digit of $n$ is 1, so we take 0, the $1$st digit of $n$ is 0, so we don't take 1, the $2$nd digit is 1, so we take 2, and the $3$rd digit is $1$, so we take 3)
Using the same idea, you can define a map from finite subsets of $\mathbb N$ to $\mathbb N$, and show they are each other inverses.
Comment: Thank you for the response! If I am reading this correctly $p$ is a finite subset of $\mathbb{N}$. By $p$th number do you mean the 'last' element of $p$?
Comment: No, here I define the map from $\mathbb N$ to finite subsets of $\mathbb N$. So, from a natural $n$, you want a finite subset of $\mathbb N$, and I propose to define it by listing its elements $p\in\mathbb N$. I edit my answer to make it clearer.
Comment: Excellent, I understand now, thank you very much!!

Binary expansion and bijection


Subdomain from different S3 bucket on same cloudfront distribution

Question:
I have example.com served from idxxxx.cloudfront.net, this goes to S3 bucket nr 1. This works well.
I now need subdomain.example.com to also be served from same cloudfront distribution, and point to S3 bucket nr 2. It's a completely different static website hosted on this bucket.

What I tried:
I edited origins for my idxxxx.cloudfront.net distribution - I added a new origin there, to point to S3 bucket nr 2, then in Route53 I added this new recordset:
Name: subdomain.example.com
Type: A - IPv4 Address
Alias: yes
Alias target: idxxxx.cloudfront.net
The outcome of this attempt: calling subdomain.example.com shows me the contents of S3 bucket nr1 when my intention was to show the content of S3 bucket nr 2 on this subdomain. Is this because for my use case I actually must create another CF distribution? Or can I somehow work with the same distribution?
Maybe useful info -  my CF distribution is configured for these CNAMEs: example.com, *.example.com
I also tried adding in Route53 the IPv4 alias that points directly to the S3 bucket nr 2 for subdomain.example.com, and while it works to show me the desired contents of bucket 2, its not retrieved through cloudfront as I actually want it, therefore I dont benefit from things like https and such.
Is my use case impossible with just one CF distribution? Many thanks in advance.
Best regards,
Comment: I'm posting the answer for the question you've asked... but in case I am missing something, I'll also ask: what is your motivation for using 1 (free) distribution instead of 2 (free) distributions?
Comment: There isn't a charge for a CloudFront distribution -- an actual CloudFront distribution itself has no associated cost.  You pay a charge per request handled by CloudFront, and a charge per gigabyte of traffic. https://aws.amazon.com/cloudfront/pricing/
Comment: @Michael-sqlbot because of the cost for having two separate CF distributions :) I thought I could try to use one distribution for both. Please tell me what do you mean by (free) distributions? As I understood, each CF distribution is billed separately.
Comment: Yes but the ACLs are a cost per cloudfront, so multiple cloudfronts are a multiplier effect
Answer:
It's a completely different static website

A completely different web site needs a completely separate CloudFront distribution.  Identical sites with multiple domain names would be the case where you'd serve multiple sites and associate multiple hostnames from a single distribution.


How to generate random points on a plane that do not overlap?

Question: I want to generate a bunch of random dots on the (x,y) plane, where the coordinates are integers drawn from some distribution F (e.g., the uniform distribution). Each dot is a square of size SxS and I don't want any two dots to overlap on the plane. What is the algorithm I can use to generate that?
Comment: generate points using uniform distribution until you find one that doesn't overlap with existing points.
Answer: Let's say your coordinates $(X,Y)\sim P(x,y)$.
Let $p_i :=(x_i,y_i)$, then $p_1$ will be generated from $P(p_i)$, $p_2$ will be generated from $P(p_2|p_2 \notin \{p_1\})$.
In general,  $p_j \sim P(p_j|p_j \notin \bigcup_{i<j} p_i\})$.
You'll need a way to either draw directly from these conditional distributions or use an acceptance-rejection scheme.


Lipschitz in $\mathbb R^1$ implies Lipschitz along any line in $\mathbb R^k$ (for convex functions)

Question: I'm trying to solve a homework problem (baby rudin course) and realized that Lipschitz continuity really makes the problem easier for me. However, since it is not defined in Rudin I have to prove the properties if I want to use them.
I have just argued that convex functions are (locally) lipschitz in $\mathbb R^1$. I'm trying to avoid arguing that it holds in $\mathbb R^k$ directly since the proof is messy and too difficult. However, I really need it to apply to any line in $\mathbb R^k$. I wrote:
"ii) Convex functions are locally Lipschitz along any line in $\mathbb R^n$.
Let $f$ be defined on some set $C \in R^n$ let $I=\{u| a< u<b\} \subset K$ be a line with $a<s<t<u<b$. We have assumed without loss of generality that the line is a linear combination of $e_1$. This is further justified in c) but really it is just a matter of notation in this case. Then by convexity (c.f. excercise R4.23)
$$\frac{f(t)-f(s)}{t-s}\leq \frac{f(u)-f(s)}{u-s}\leq \frac{f(u)-f(t)}{u-t}$$
Now choose
$$K=\max\left[\left|\frac{f(t)-f(s)}{t-s}\right|,\left|\frac{f(u)-f(t)}{u-t}\right|\right]$$
It follows that
$$  \frac{\left|f(u)-f(s)\right|}{\left|u-s\right|}\leq K \rightarrow |f(u)-f(s)|\leq K|u-s|$$
And thus $f$ is locally Lipschitz on $I$ and we have the result desired."
I feel that my argument that it applies to $\mathbb R^k$ is not very strong at the moment. I was considering induction, but I'm unsure what to induct on really.
Thanks in advance.
EDIT:
I think I solved it:
For $\mathbb R^n$ consider the function $f$ restricted to any line $I \in R^n$, this can be considered a convex function on a subset of $\mathbb R^1$, and then the result follows.
Answer:
For $\mathbb R^n$ consider the function $f$ restricted to any line $I\in \mathbb R^n$, this can be considered a convex function on a subset of $\mathbb R^1$, and then the result follows.

You should be more careful. It is true that convexity is determined by line restrictions, i.e., a function $f:\mathbb R^n\to \mathbb R$ is convex if and only if its restriction to every line is. But for the Lipschitz condition this is false unless we have uniform control on Lipschitz constant. The problem is that a function may be Lipschitz on every line, but with a constant depending on the line; since there are infinitely many lines to consider, we might not be able to pick a Lipschitz constant that works for all of them, even locally. This is not just an abstract concern: the function
$$f(x,y) = \frac{xy^2}{x^2+y^4},\qquad f(0,0)=0$$
is locally Lipschitz on every line, but is not continuous at $(0,0)$.
You can still fix the argument by making the one-dimensional version quantitative. That is, show that if $f:\mathbb R\to \mathbb R$ is convex, then it is Lipschitz on $[-a,a]$ with a constant that depends only on $a$ and $\sup_{[-2a,2a]} |f|$. (It is  important to have the larger interval in the supremum.) The proof goes like this: if some secant of $f$ on $[-a,a]$ has a large slope, then it grows large either at $2a$ or at $-2a$, and $f$ will be even bigger there.
With this quantitative version, the argument by line restriction works. Let $M$ be the supremum of $|f|$ on a ball of radius $2R$ cantered at the origin. Consider the restriction of $f$ to the ball of radius $R$ centered at the origin: this restriction will be Lipschitz on every line, with a uniformly bounded constant, independent of line.


Change the value of button after clicking on it and posting it to the database in php

Question: There are some answers on stackovervlow but not one that solves my problem, I have tried to find it but I just can't find it.
This is the code, it must be something simple I guess.
?><input type='submit' <?php echo "name= ".$Buttons[$Teller].""; ?> value='Schrijf in!'>
<?php

After Pressing it some info sent to the database.
But I want the Schrijf in! value changed to Schrijf uit!
I really can't find it, nor here or in Google :)
Comment: I know that, but that is not my question, Joost understood it perfectly :)
Answer: You'll have to make a database call each time you load that page, to check if the button should say 'Schrijf in' or 'Schrijf uit'. Perhaps test if the logged in user is already in the database table or something of that sort. Then set the button value based on that conditional.
Alternatively, you could create a $_SESSION variable to keep track of whether or not the user has clicked the button already..


DNA use in court cases

Question: I am currently studying the following case of Neil Owen, based on the following article I found a newspaper:

"A 20-year-old student was jailed for life yesterday for the brutal
  rape and murder of a schoolgirl, after one of the biggest DNA testing
  programmes in British criminal history. Neil Owen was arrested a year
  after the murder when his genetic fingerprint was matched with DNA
  found at the scene, following a mass DNA screening of 2000 men on the
  estate. He lived just 100 yards from the victim's house. Laboratory
  tests revealed the chances of anyone else being the killer were 1 in
  160 million."

Now first of all I am aware that there is an issue with prosecutors fallacy here. Because the 1 in 160 million is interpreted as P(innocence|matching blood type evidence) when it actually refers to P(matching blood type evidence|innocence). But my question refers to the reasoning of the defence.
Counsel for the defence pointed out that there are about 30 million males in the United Kingdom, and argued that the correct probability that Owen was guilty is about 16/19, not high enough to convict beyond a reasonable doubt. So my two questions are
1.  How do you think that the figure 16/19 was calculated? (I am sure the population of 30
    million and the probability of 1 in 160 million was used?)
2. What implicit assumptions were made, and how reasonable are they?
Comment: Not that this makes the question any less important or interesting, but from reports I've found on the web, it appears that Owen claimed they had consensual sex and somebody else murdered her - so I suppose that the DNA evidence was not an important factor in his conviction (except that his connection to the case would not have been discovered without it)?
Comment: See https://law.stackexchange.com/questions/83781/does-statistically-significant-have-a-specific-legal-meaning
Answer:
Given your assumption that 1 in 160 millions being P(matching DNA evidence|random person), the number 16/19 is roughly the chance that none of the other 30 million males in the UK would also match the DNA evidence: binomial chance of 0 hits, given 30 millions trials with p = 1/160 millions. I get about 0.83 for this probability and 16/19 is roughly 0.84. Since 19/23 is a better approximation of the probability I calculated I am not certain if this is how they got it.
Assumptions of whom? The counsel? If I am right, he makes the incorrect assumption that the existence of another man with matching DNA would mean that his client is inoccent. But of the 30 million men many would have alibis and/or life far away from the crime scene which gives them a relative miniscule prior probability of being the killer.

Statistically it makes sense to assume he's guilty. If we had a measure of often the killer lives near and therefore how likely it is that he is part of the 2000 people tested, we could calculate the probability. Let's say it's relatively low, say 5%. Let be G be the event that the guilty one is part of the 2000 and let E be the event that at least one of the 2000 tests positive.
Then
$$
P(G|E)=\frac{P(E|G)P(G)}{P(E)}.
$$
P(G) is assumed to be 0.05 and $P(E|G)$ should be about 1 if the lab does it's work properly. In practice it's probably slightly lower, so let's assume it's just 0.9. OTH
$$
P(E) = P(E|G)P(G)+P(E|!G)P(!G)=0.05*0.9+ p*0.95
$$
with p being the binomial chance of at least 1 positive result out of 2000 with a hit chance of 1/160 million. It turns out that this is small, with p being about $0.000012$. This means we get $P(E)=0.045$ and
$$
P(G|E) \approx 0.99974.
$$
Comment: I also calculate 1/80,000.
Comment: Very interesting. An alternative defence argument is that, since 2000 men were examined, the probability of nding an innocent person who matched the DNA at the scene was 20001=160 million, 1/80,000, greatly weakening the strength of the match evidence. Prosecution counters that the search in fact eliminated 1999 individuals who might otherwise have been considered as possible alternative perpetrators, and so strengthened the evidence against Owen. Are these arguments correct?
Comment: It's roughly 1/800000. You are off by a factor of 10. You can find that number above as p. I don't think a small number like that weakens the match evidence at all. As for the rest, my argument remains as follows : Given a reasonable chance a priori chance that the perpetrator is among the 2000 (my 5%) the test results make it very likely ($P(G|E)$ that the perpetrator is indeed among the tested persons, and therefore the one that tested positively. Notice that the argument would not hold if they tested 2000 random people from all over the world.
Comment: True. My bad, note that the numerical version above is correct (i.e. 1/80000). Got confused adding up the zeroes in my head.
Comment: I was also thinking: whereas the first intuition focuses directly on HD: the hypothesis that some one in the database is guilty the latter one focuses on HS: that the accused is actually guilty. What needs to be kept in mind is that these two hypotheses are only equivalent after there was discovered that the database D contains exactly one match. Before making this observation they were not equivalent. I am correct in assuming this?

DNA use in court cases


Why is a write to a memory-mapped peripheral register not actioned (LPC43xx)?

Question: I'm building an application for NXP LPC4330 (Arm Cortex M0/M4 dual core). I'm compiling using arm-none-eabi-gcc 4.9.3. At one point in my code, I am performing a write to a (32-bit) memory location. Immediately afterwards, if I read back from that memory location, around one time in ten the result indicates that the write did not occur. Subsequent reads at later times indicate the same thing, so it is not a transient condition. Interrupts are disabled at the global level, and the assembler generated by the compiler is clearly attempting the write, so how is it possible that the write is not being actioned?
Specifically, I am writing to SLICE_MUX_CFG0 which is a memory-mapped register in the SGPIO peripheral. When the write works, the peripheral functions correctly. When the read-back indicates that the write has not worked, the peripheral does not function correctly. So, it seems that the register in question is not being set correctly, as indicated by the read-back.
Looking into the .asm (listed below), the write is clear. When I read back the value afterwards, it reads as zero, which - given the listing below - seems to me to be impossible. If I perform a read immediately before the write (see the .c listing, below), the problem goes away, which is perhaps a clue.
So the above indicates, what? Does this break some rule for use of the memory bus? I've looked at the GCC bugs list and can't see anything that relates to this.
The function follows, both source and ASM, with some annotation. What could be happening, here? Why does the write at "store value" apparently not have any effect?
20000f7c <camera_SGPIO_init_sub>:
; disable interrupts globally
20000f7c:   b672        cpsid   i
20000f7e:   2346        movs    r3, #70 ; 0x46
20000f80:   4a16        ldr r2, [pc, #88]   ; (20000fdc <camera_SGPIO_init_sub+0x60>)
20000f82:   6013        str r3, [r2, #0]
20000f84:   4a16        ldr r2, [pc, #88]   ; (20000fe0 <camera_SGPIO_init_sub+0x64>)
20000f86:   6013        str r3, [r2, #0]
20000f88:   4a16        ldr r2, [pc, #88]   ; (20000fe4 <camera_SGPIO_init_sub+0x68>)
20000f8a:   6013        str r3, [r2, #0]
20000f8c:   4a16        ldr r2, [pc, #88]   ; (20000fe8 <camera_SGPIO_init_sub+0x6c>)
20000f8e:   6013        str r3, [r2, #0]
20000f90:   4a16        ldr r2, [pc, #88]   ; (20000fec <camera_SGPIO_init_sub+0x70>)
20000f92:   3301        adds    r3, #1
20000f94:   6013        str r3, [r2, #0]
20000f96:   4a16        ldr r2, [pc, #88]   ; (20000ff0 <camera_SGPIO_init_sub+0x74>)
20000f98:   6013        str r3, [r2, #0]
20000f9a:   4a16        ldr r2, [pc, #88]   ; (20000ff4 <camera_SGPIO_init_sub+0x78>)
20000f9c:   6013        str r3, [r2, #0]
20000f9e:   4a16        ldr r2, [pc, #88]   ; (20000ff8 <camera_SGPIO_init_sub+0x7c>)
20000fa0:   6013        str r3, [r2, #0]
20000fa2:   4a16        ldr r2, [pc, #88]   ; (20000ffc <camera_SGPIO_init_sub+0x80>)
20000fa4:   6013        str r3, [r2, #0]
20000fa6:   2240        movs    r2, #64 ; 0x40
20000fa8:   4b15        ldr r3, [pc, #84]   ; (20001000 <camera_SGPIO_init_sub+0x84>)
20000faa:   601a        str r2, [r3, #0]
20000fac:   2290        movs    r2, #144    ; 0x90
20000fae:   4b15        ldr r3, [pc, #84]   ; (20001004 <camera_SGPIO_init_sub+0x88>)
20000fb0:   0512        lsls    r2, r2, #20
20000fb2:   601a        str r2, [r3, #0]
; load value
20000fb4:   23c6        movs    r3, #198    ; 0xc6
; load destination address
20000fb6:   4a14        ldr r2, [pc, #80]   ; (20001008 <camera_SGPIO_init_sub+0x8c>)
; store value
20000fb8:   6013        str r3, [r2, #0]
; read value back
20000fba:   6810        ldr r0, [r2, #0]
20000fbc:   4a13        ldr r2, [pc, #76]   ; (2000100c <camera_SGPIO_init_sub+0x90>)
20000fbe:   6013        str r3, [r2, #0]
20000fc0:   4a13        ldr r2, [pc, #76]   ; (20001010 <camera_SGPIO_init_sub+0x94>)
20000fc2:   6013        str r3, [r2, #0]
20000fc4:   4a13        ldr r2, [pc, #76]   ; (20001014 <camera_SGPIO_init_sub+0x98>)
20000fc6:   6013        str r3, [r2, #0]
20000fc8:   4a13        ldr r2, [pc, #76]   ; (20001018 <camera_SGPIO_init_sub+0x9c>)
20000fca:   6013        str r3, [r2, #0]
20000fcc:   4a13        ldr r2, [pc, #76]   ; (2000101c <camera_SGPIO_init_sub+0xa0>)
20000fce:   6013        str r3, [r2, #0]
20000fd0:   4a13        ldr r2, [pc, #76]   ; (20001020 <camera_SGPIO_init_sub+0xa4>)
20000fd2:   6013        str r3, [r2, #0]
20000fd4:   4a13        ldr r2, [pc, #76]   ; (20001024 <camera_SGPIO_init_sub+0xa8>)
20000fd6:   6013        str r3, [r2, #0]
; enable interrupts globally
20000fd8:   b662        cpsie   i
20000fda:   4770        bx  lr
20000fdc:   40086480    .word   0x40086480
20000fe0:   40086484    .word   0x40086484
20000fe4:   40086488    .word   0x40086488
20000fe8:   40086494    .word   0x40086494
20000fec:   40086380    .word   0x40086380
20000ff0:   40086384    .word   0x40086384
20000ff4:   40086388    .word   0x40086388
20000ff8:   4008639c    .word   0x4008639c
20000ffc:   40086208    .word   0x40086208
20001000:   40086204    .word   0x40086204
20001004:   40050064    .word   0x40050064
20001008:   40101080    .word   0x40101080
2000100c:   401010a0    .word   0x401010a0
20001010:   40101090    .word   0x40101090
20001014:   401010a4    .word   0x401010a4
20001018:   40101088    .word   0x40101088
2000101c:   401010a8    .word   0x401010a8
20001020:   40101094    .word   0x40101094
20001024:   401010ac    .word   0x401010ac

The C-code which compiled to the above follows.
volatile uint32_t vol_dummy_for_read;
#define __SFS(addr, value) *((volatile uint32_t*)addr) = value;
#define SGPIO_SLICE_MUX_CFG0 (*((volatile uint32_t*)  ... some address ... ))

uint32_t camera_SGPIO_init_sub()
{
    __asm volatile ("cpsid i" : : : "memory");

    //  configure pins to SGPIO
    __SFS(P9_0, SCU_SFS_INPUT | 6); // D0, SGPIO0
    __SFS(P9_1, SCU_SFS_INPUT | 6);
    __SFS(P9_2, SCU_SFS_INPUT | 6);
    __SFS(P9_5, SCU_SFS_INPUT | 6);
    __SFS(P7_0, SCU_SFS_INPUT | 7);
    __SFS(P7_1, SCU_SFS_INPUT | 7);
    __SFS(P7_2, SCU_SFS_INPUT | 7);
    __SFS(P7_7, SCU_SFS_INPUT | 7); // D7, SGPIO7

    //  SGPIO8
    __SFS(P4_2, SCU_SFS_INPUT | 7); // PCLK, SGPIO8

    //  configure pins to GPIO
    __SFS(P4_1, SCU_SFS_INPUT | 0); // HSYNC, GPIO2[1]

    //  bring SGPIO clock up to full speed (same as PLL1, M4)
    CGU_BASE_PERIPH_CLK = (0 << 1) | (0 << 11) | (9 << 24);

    //  SLICE_MUX_CFG
    uint32_t SLICE_MUX_CFG_VALUE =
          (1 << 1) /* clock on falling edge */
        | (1 << 2) /* clock from external pin */
        | (3 << 6) /* shift 8 bytes per clock */
        ;

////    see note above (this fixes it)
//vol_dummy_for_read = SGPIO_SLICE_MUX_CFG0 ;

    SGPIO_SLICE_MUX_CFG0  = SLICE_MUX_CFG_VALUE; // A
    uint32_t ret = SGPIO_SLICE_MUX_CFG0;
    SGPIO_SLICE_MUX_CFG8  = SLICE_MUX_CFG_VALUE; // I
    SGPIO_SLICE_MUX_CFG4  = SLICE_MUX_CFG_VALUE; // E
    SGPIO_SLICE_MUX_CFG9  = SLICE_MUX_CFG_VALUE; // J
    SGPIO_SLICE_MUX_CFG2  = SLICE_MUX_CFG_VALUE; // C
    SGPIO_SLICE_MUX_CFG10 = SLICE_MUX_CFG_VALUE; // K
    SGPIO_SLICE_MUX_CFG5  = SLICE_MUX_CFG_VALUE; // F
    SGPIO_SLICE_MUX_CFG11 = SLICE_MUX_CFG_VALUE; // L

    __asm volatile ("cpsie i" : : : "memory");

    return ret;
}

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/80462/discussion-on-question-by-rattus-ex-machina-why-is-a-write-to-a-memory-mapped-pe).
Answer: (I am answering my own question; this answer was reached based on clues offered in the comments, above).
Short Answer
The peripheral is not actioning the register update reliably because the peripheral clock that is driving it (CGU_BASE_PERIPH_CLK) has only just had its speed changed at the time of the write operation. Setting the AUTOBLOCK bit when updating the clock's speed eliminates the problem.
Discussion
Presumably, the clock to the peripheral is transiently invalid during the frequency change, depending on conditions. Perhaps, if the timing of edges happens to be just-so, very short clock pulses find their way through during the change. Or something similarly unpleasant finds its way down the clock line to the peripheral. In any case, in these unpredictable conditions, the write may not occur, causing the reported failure.
Waiting for a period of time between the clock speed change and the subsequent assignment also eliminates the problem, understandably. As reported in the question, performing a read of the register prior to the write also eliminates the problem; whether this is because it takes time, or the read operation blocks (for reasons unclear) until the peripheral clock has settled, is unclear.
AUTOBLOCK is documented only as far as the statement of function: "Block clock automatically during frequency change". The User Manual gives no indication of the conditions under which the bit should be set, or left clear, during a clock speed change. However, given the evidence reported here, a policy of always setting AUTOBLOCK when updating the speed of a clock in one of these devices, unless there is a known reason to leave it clear, seems wise.
Reference: NXP User Manual for LPC43xx, UM10503 Rev 1.9, Chapter 13.
Comment: Glad you found the bug. Most other MCUs that size switch clock dividers synchronously without option to deactivate. However, the problem might be deeper, if you switch over to PLL clock and **that** has not locked already. That might very well be the reason for this bit. However, I do not have time to study the ref man right now, just had a short peek.
Comment: Yes, that's a point worth making, could potentially cause a similar issue. However, in this case, the PLL has already been configured and locked when this code runs.


Reduzir Tempo de execução Python3

Question: To resolvendo um desafio aqui, que é, basicamente, ver quantos elementos de uma lista encaixam em TODOS os intervalos de uma matriz.
E minha solução foi essa:
def countSignals(frequencies, filterRanges):
    corretos = 0
    len_fR = len(filterRanges)
    for i in frequencies:
        for a in range(len_fR):
            if i in range(filterRanges[a][0], filterRanges[a][1] + 1):
                passou = True
                if passou and filterRanges[a] == filterRanges[-1]:
                    corretos+=1
            else:
                 break
    return corretos

if __name__ == '__main__':

    frequencies_count = int(input().strip())

    frequencies = []

    for _ in range(frequencies_count):
        frequencies_item = int(input().strip())
        frequencies.append(frequencies_item)

    filterRanges_rows = int(input().strip())
    filterRanges_columns = int(input().strip())

    filterRanges = []

    for _ in range(filterRanges_rows):
        filterRanges.append(list(map(int, input().rstrip().split())))

    result = countSignals(frequencies, filterRanges)

    print(result)

Como funciona a execução:
Recebo um número, que será equivalente à len(frequencies). Depois, recebo cada um dos elementos que irá compor a lista frequencies. Em seguida, recebo o valor de len(filterRanges). Depois recebo a dimensão de cada uma das listas que compõe filterRanges No final, recebo os valores de cada uma das listas.
Exemplo de input:
5 #-> len(frequencies)
20 #-> frequencies[0]
5 #-> frequencies[1]
6 #-> frequencies[2]
7 #-> frequencies[3]
12# -> frequencies[4]
3 #-> len(filterRanges), sendo que este é composto por listas
2 #-> tamanho das listas que compõe filterRanges
10 20 #-> filterRanges[0] = [10,20]
5 15 #-> filterRanges[1] = [5,15]
5 30 #-> filterRanges[2] = [5,30]

O código precisa contar quantos valores de frequencia estão no intervalo de TODAS as listas que compõe filterRanges.
Nesse caso, por exemplo, o retorno seria 1, pois apenas o numero 12 se encaixa em todos os intervalos.
Ele passou em 10 dos 15 testes, e os outros 5 deu timeout. alguém tem alguma sugestão para otimizar o código? O erro que deu foi "Terminated due to timeout", porque o codigo ficou executando por mais de 10 segundos (ele dá timeout qunado chega em 10). Como faço pra otimizar esse código?
EDIT APÓS SUGESTÕES:
def countSignals(frequencies, ranges):
    ranges = [range(i[0], i[1] + 1) for i in ranges]
    return sum(1 if all(f in r for r in ranges) else 0 for f in frequencies)

if __name__ == '__main__':

    frequencies_count = int(input().strip())

    frequencies = []

    for _ in range(frequencies_count):
        frequencies_item = int(input().strip())
        frequencies.append(frequencies_item)

    filterRanges_rows = int(input().strip())
    filterRanges_columns = int(input().strip())

    filterRanges = []

    for _ in range(filterRanges_rows):
        filterRanges.append(list(map(int, input().rstrip().split())))

    result = countSignals(frequencies, filterRanges)

    print(result)

Passei em 12/15 testes. Preciso otimizar mais... Não consigo alterar nada definido no método main, apenas consigo alterar a função countSignals.
Comment: coloca o link para o desafio, talvez fique melhor para dar sugestões
Comment: https://www.hackerrank.com/tests/2h92ckdchlg
Comment: infelizmente pede para se cadastrar
Comment: eu coloquei o que ele pede. simplesmente falar quantos valores de "frequencies" se encaixam em todos os intervalos dentro de "filterRanges"...
Answer: Algumas dicas:
Pelo menos na IDLE do Python, não é preciso utilizar o método strip na função input, visto que ao pressionar Enter o caractere '\n' não é levado em conta. Porém se for algo que não é exigido na competição, recomendo remover.
Ao ler os valores do filterRanges, transforme os valores em um objeto range ao invés de uma lista.
for _ in range(filterRanges_rows):
    ini, fin = (int(i) for i in input().split(' '))
    filterRanges.append(range(ini, fin+1))

A função countSignals você pode fazer em uma linha:
def countSignals(frequencies, ranges):
    return sum(1 if all(f in r for r in ranges) else 0 for f in frequencies)

Por partes:
f in r
# verifica se f está em r

f in r for r in ranges
# retorna um iterável de booleanos onde cada elemento
# indica se f está em r para cada r na lista ranges

all(f in r for r in ranges)
# verifica se todos os elementos desse
# iterável são verdadeiros (True), ou seja,
# se a frequência f está em todos os
# intervalos da lista ranges

1 if all(f in r for r in ranges) else 0
# retorna 1 se todos os elementos do iterável
# são verdadeiros, senão retorna 0

1 if all(f in r for r in ranges) else 0 for f in frequencies
# repete essa operação para todas as frequencias

sum(1 if all(f in r for r in ranges) else 0 for f in frequencies)
# soma todos os elementos que possuem 1
# ou seja, a quantidade de frequencias que
# estão em todos os intervalos da lista ranges

Veja se essas dicas melhoram o tempo de execução do seu código.
EDIT: Haha, desculpa, não sabia que a parte do main era pré-definido pela plataforma. Você pode ir modificando alguns fatores da função countSignals e vendo o resultado:
Tente utilizar expressões geradoras ao invés de compreensão de listas quando são criados os objetos range na primeira linha da função, onde
ranges = [range(r[0], r[1] + 1) for r in ranges]

se torna
ranges = (range(r[0], r[1] + 1) for r in ranges)

Tente substituir o uso dos objetos range por comparações dos elementos na própria lista ranges, onde
ranges = [range(r[0], r[1] + 1) for r in ranges]
return sum(1 if all(f in r for r in ranges) else 0 for f in frequencies)

se torna
return sum(1 if all(f >= r[0] and f <= r[1] for r in ranges) else 0 for f in frequencies)

Você pode também remover o uso do else 0 visto que ele não interfere na função sum.
return sum(1 for f in frequencies if all(f >= r[0] and f <= r[1] for r in ranges))

Comment: Tem um problema só kkkk. A parte de baixo (depois do main) é tudo pré-definido pela plataforma. O que eu fiz, para seguir as suas sugestões, é criar uma nova lista e num for loop atribuir os valores da lista de antes, mas como range. Vou adicionar esse código abaixo, como um edit para você me ajudar...
PS: a performance do código melhorou bastante e passei por 12/15. Agora faltam 3, se puder me ajudar
Comment: Adicionei o código na pergunta, se puder me dar uma ajudada <3 kkkk
Comment: Editei minha resposta, vê se ajuda em alguma coisa kkk

Reduzir Tempo de execução Python3


random forest regression with uncertainty output

Question: For a Bayesian optimization problem, I wish to use a random forest regressor in Python, able to predict for unseen data a probability distribution, like in the paper Decision Forests for Classification,Regression, Density Estimation, ManifoldLearning and Semi-Supervised Learning,
figure 4.3 page 55 for example.
Scikit-learn proposes a random forest regressor but the output is a predicted value with no uncertainty measure. Do you know any packages in Python implementing a random forest regressor able to predict a value for unseen data as well as some uncertainty over it (in the form of a probability distribution, or confidence interval) ?
Answer: Per reference you supplied (which, by the way, I recommend as good reading), the comparison between Least-Squares regression and Forest regression is particularly interesting.  Per the presented example,  for one of the more simpler cases (at lower dimensionality), it appears that near the centroid (the point X-bar, Y- Bar), both Least-Squares and Forest regression are surprisingly close in their prediction/confidence intervals.  However, at points removed from the training sample (and the centroid), the confidence intervals correctly becomes larger, and in the case of Least-Squares, surprisingly larger.
As such, I would recommend applying Least-Squares regression model based prediction intervals as an approximation for the Forest regression model precision (uncertainty) estimates, at least for lower orders of dimensionality.
Comment: thank you for your answer. In this context, are what you call centroids the conditionnal means (green curve of fig 4.6 page 55) ?