A bicategory ($=$ weak 2-category) is a 0-cell in what category?

Question: Question.
What, in your opinion, should replace the "?" in:

If (category)$=$(0-cell in CAT), then (bicategory)$=$(0-cell in ?).

Remarks.

"bicategory" as usual means "weak 2-category".
I am well aware that this is sort-of-opinion-based and does not have an uncontroversial precise answer, and is not asking much more than for mathematicians more experienced in category theory to suggest

what the category of all bicategories should mean precisely,

how the category of all bicategories should be denoted.

Still, I think there is some justification for asking this. It is useful in some contexts to be able to think of "category" as "0-cell in the category of categories", and there is use, too, for being able to do the same for "bicategory" instead of "category".
There are some issues what definition of "functor between two bicategories" to adopt, in the first place, but I will not get into this here (see the next remark). It can be argued that the definition should at least

make $\mathsf{CategoryOfBicategories}$ have a all finite products.

I do not give explanations of technical terms since I am curious what others think should be the "canonical" answer here.
Comment: What do you mean by a "weak bicategory"? Do you mean a bicategory in the sense of Bénabou? If so, bicategories and lax functors (called ''morphisms of bicategories'' by Bénabou) form a category, subcategories of which are obtained by restricting the morphisms to the pseudofunctors (or "homomorphims") or the strict functors. All three of these categories have finite products (and so have terminal objects). Furthermore, all three of these categories can be extended to 2-categories, whose 2-cells are "icons" defined by Lack, and they have finite products in the strict 2-categorical sense.
Comment: The category of bicategories and pseudofunctors (first recognised by Bénabou, and, as you say, called $\textbf{Hom}$ in some articles of Street) is often called $\textbf{Bicat}$ (and indeed, this is what I use). The categories of bicategories and strict/lax functors are then correspondingly denoted $\textbf{Bicat}_s$ and $\textbf{Bicat}_l$. I do agree that pseudofunctors are in some sense the "correct" notion of morphism of bicategories, but that is not to impugn the other two kinds of morphism, both of which are useful.
Comment: @AlexanderCampbell: yes, here, "weak bicategory"$=$"bicategory in the sense of Bénabou". In particular, left unitor, right unitor and associator are only required to be natural isomorphisms, not identities. I wrote "weak" for emphasis. I know it is somewhat of a pleonasm, since the "bi" is usually taken to be sufficient to indicate the weak sense. Thanks for drawing attention to this, though, I will modify the question a bit.
Comment: And thanks for pointing out that my having opted for the desideratum "all finite products" renders the explicit mentioning of "terminal 0-cell" redundant. This was an oversight, resulting from the eternal issue of whether to write "all binary products" or "all finite products", conditions which oftentimes, in a certain context, are equivalent. You made me aware of a nice subtlety though, namely that this choice is not indifferent, the consequences of this choice are different.
Comment: @AlexanderCampbell: I understand that the category of bicategories in the sense of R. Street's 1980 Cahiers-article is some sort of standard $\mathsf{CategoryOfBicategories}$. Do you, roughly, agree with this? The notation $\mathsf{Hom}$ that is sometimes used for it seems not the most felicitous; did you meet alternatives for $\mathsf{Hom}$, and which do you recommend? Would you find $\mathsf{BiCat}$ instead of $\mathsf{Hom}$ acceptable?
Answer: Since it seems too complicated for this question to first ask the commenter whether they would like to make the comment an answer, I'll write one here myself (thanks to Alexander Campbell for confirming that $\mathsf{Bicat}$ is a usual notation): arguably the most usual $\mathsf{CategoryOfBicategories}$ is the category which is denoted $\mathsf{Hom}$ in Street's 1980 article in Cahiers de topologie et géométrie différentielle catégoriques, but the most usual notation nowadays is $\mathsf{Bicat}$.
Subscripted variants thereof exist, to distinguish some-sort-or-full-subcategories of $\mathsf{Bicat}$, like e.g. $\mathsf{Bicat}_s$ and $\mathsf{Bicat}_l$ mentioned in a comment above, or $\mathsf{Bicat}_2$ in the sense of R. Garner, N. Gurski: The low-dimensional structures formed by tricategories. Math. Proc. Camb. Phil. Soc. 146 (2009),pp. 551--589.
And, to give one application of the usual notation, and another usual notation (namely $\mathsf{2Cat}$ for strict 2-categories), I mention that there is an adjunction
$$ \array{  &  &  &  & \xrightarrow[]{\quad\mathrm{strictification}\quad} \hspace{-10pt}  &  &  &  &  \\ &  & {\huge\mathsf{Bicat}}  &  & \perp &  &  & {\huge\mathsf{2Cat}}  & \\  &  &  &  &\xleftarrow[\quad\mathrm{inclusion}\quad]{} \hspace{-10pt}   & &  & &\qquad.   \\  }$$


Problem with Veblen's proof for the transcendence of $\pi$

Question: I'm trying to understand the following proof, (no need to read all of it), but there's one point where I'm stuck. The proof is by contradiction, so they use the definition of an algebraic number (a is algebraic if there exists a polynomial in the field extension such that $f(a)=0$:
"$x_1,...,x_n$ are algebraic, so they are the roots of an equation
$$f(x) = a_0+a_1x+...+a_nx^n$$
with integral coeffiecients, $a_0\neq0, a_n\neq0$."
Yet, on the last page the Girard–Newton formulas are used:
"But from Newton's formulas
$$S_1+a_1=0, S_2+a_1S_1+2a_2+0,...$$
it follows that $S_1,S_2,...,S_{s-p}$ are whole numbers.
Where from my own calculations based on Wikipedia (so not sure if this is correct), these formulas are given by
$$\sum^k_{i=1} (-1)^{i-1}a_{n-k+i}S_i = ka_{n-k}$$
for $1 \leq k \leq n$.
Meaning that we would get $a_nS_1 + a_1 = 0$ etc. So if $a_n$ isn't 1, if $f$ isn't monic, $S_i$ wouldn't be an integer. Why do we suddenly assume $f$ to be monic, since this doesn't follow from the definition of an algebraic number.
Is the proof wrong? What am I missing? This has been messing with me for days, thank you in advance.
Edit: This is guessing work, but I think we may assume $f$ is monic from the start. By looking at the proof for the transcendence of $e$, this is obvious.But I think there might be a way to choose $x_1,...,x_n$ as roots for $f$ such that it is monic and
$$c+\sum^{n}_{i=1} e^{x_i} = 0.$$
Edit²: The formulas should be as follow:
$a_nS_1 + a_{n-1} = 0, S_2 = S_1^2-2\frac{a_{n-2}}{a_n}$ etc
Comment: Not every algebraic number is a root of a MONIC polynomial with integer coefficients. So, if the proof would only work for algebraic numbers with this property (by assuming $f$ is monic) , it would be incomplete. I do not think this is the case. Rather I think that you somehow misinterprete the formulas. Please explain more clear, how you conclude $a_n=1$ !
Comment: @peter Thank you for your answer. I'm aware of this fact (eg rational numbers)! I was hoping, since we were allowed to choose integer roots, and since $pi$ isn't rational, f would be monic. I don't conclude $a_n=1$, but I think it's the only way for the proof to make sense...which I'm starting to lose faith in.
Answer: The statement is wrong.
The author states that if $f(x)=\sum_{0\le i\le n}a_ix^i$ is such that $a_0,a_n\ne0$ then \begin{align}S_1+a_1&=0\\S_2+a_1S_1+2a_2&=0.\end{align}
This is not true; for instance the monic polynomial $1-5x-4x^2+x^3$ has $a_1=-5$ but the sum of roots is $S_1=4$.
How did this error arise?
At the bottom of the page, there is the reference "*Cf. Burnside and Panton, Theory of Equations, Chapter VIII, or any book on higher algebra."
I found the PDF version of the book and Article 126, Chapter XII (note that Chapter VIII discusses limits instead) states

Let the equation be \begin{align}f(x)&=x^n+p_1x^{n-1}+p_2x^{n-2}+\cdots+p_n\\&=(x-a_1)(x-a_2)\cdots(x-a_n).\end{align}
[next page] whence, comparing this value of $f'(x)$ with the former, we have the following relations: \begin{align}s_1+p_1&=0\\s_2+p_1s_1+2p_2&=0\\s_3+p_1s_2+p_2s_1+3p_3&=0\\\cdots\end{align}

There are two things to note here. First is that this polynomial is monic, so the following discussion only applies to this case. Secondly, the indexing is the other way around; that is, $f(x)=\sum_{0\le i\le n}p_{n-i}x^i$.
Therefore, it is likely that these two points combined constituted to the incorrect equalities in the original paper.
Comment: @Tessa It seems there is no reasoning as to why the leading term must be one, so it is definitely not immediate (if at all true) that the sums of powers of roots are integers.
Comment: @Tessa For the proof to work, what would need to be an integer is $\,P_1S_1\,$, not necessarily $\,S_1\,$ alone. Maybe there is an argument why $\,a_n \mid P_1\,$, though that's not immediately obvious. Then the same would have to work for the other products $\,P_kS_k\,$, otherwise I don't see how this line of proof is salvageable.
Comment: Thank you! I also noticed that the author messed up the formulas, which is why I tried to make my own. Which I messed up too apparently! I think the formulas for $S_1$ and $S_2$ are correct now (in the second edit). These formulas do still include $a_n$ so I assume the whole proof can't be fixed?


Dealing with 0's in loglog regression by using indicator functions I(x > 0)?

Question: Assume we want to estimate the following model
$y = e^{\beta_0} * x_1^{\beta_1} * x_2{\beta_3}$ which we can linearize into
$\log(y) = \beta_0 + \beta_1 * \log x_1 + \beta_2 * \log x_2$
Assume that the IV's can have zero value entries.
To deal with this why does one not just insert indicator variables as:
$\log(y) = \beta_0 + I(x_1 > 0)\beta_1 * \log x_1 + I(x_2 > 0)\beta_2 * \log x_2$ where as $I(x > 0) = 1$ if $x > 0$ else $0$.
I have not seen anyone do this and i wonder why is that?
Comment: zero observations of X contribute nothing to the regression because any value of coefficients produces zero output, i.e. exact match to left hand side. thus, you can simply remove the zero values from the training data set. keeping zeros only props up regression diagnostics without actually helping with accuracy of the estimation
Comment: If you look at your model, which is the first expression, you will see @Aksakal 's point - a zero for either $x_1$ or $x_2$ makes the output zero regardless of the values of the coefficients, so the observation contributes nothing to the estimation procedure.  Consequently, dropping the observation(s) is the right thing to do.
Comment: You might find it insightful and constructive to think about how $\log y$ can differ from the modeled expression.  For example, maybe $\log y$ is a measurement that varies randomly above and below the model; or maybe $y$ has been rounded; or whatever.  That perhaps is the most important consideration for resolving your problem, because it leads to very different solutions.
Comment: another thing you didn't touch on is the errors: are they multiplicative? if they're additive then the log transformation itself would be problematic. consider $y=x^\beta+\varepsilon$ - how would you log transform this?
Comment: we still have the intercept?  just removing them might not be possible since it may remove a large portion of the dataset, lets say we have alot of ($x1=0, x_2 >0$) and ($x_1 > 0, x_2=0$) datapoints.
Comment: @jbowman but what about the second model which is the one we actually fit?
Comment: As you have realized, you can't fit it if you include the observations with zeroes.   Note that your proposed fix *changes* the model to a different one.  Considering the answer below, think about $x_1 = 0.0001$ and $\beta_1 = 1$.  If $x_1$ moves to zero, i.e., decreases by 0.0001, you effectively replace it with 1, which rescales the right-hand side by a factor of about 10,000 relative to $x_1 = 0.0001$.   This is a huge asymmetry relative to the effect of increasing $x_1$ by 0.0001.
Answer: Your suggestion is equivalent to using the function if x<=0 then 0 else log (x). This has a big discontinuity at 0, since the log of a small number is a large negative number.
If most values of X are large, and none are negative, then the usual workaround is log(x+1).
Comment: edited it, meant $log(y) = \beta_0 + I(x_1 > 0)\beta_1 * x_1 + I(x_2 > 0)\beta_2 * x_2$ ... thus the intercept remains.. is it still an issue?
Comment: My comment still applies. The prediction for $x1=1/1000000$ will still be very different from the prediction for $x1=0$


Riemann integrable vs Lebesgue integrable

Question: Let $f$ be a real-valued function on $[a,b]$. Assume $f$ is Riemann integrable with strictly positive Riemann integral over $[a,b]$ then $f$ is strictly positive on some nonempty open interval.
What if Lebesgue integrable instead of Riemann?
*What I'm thinking is the following for Riemann.
Assume otherwise, then for all open interval, say $(a',b')$,$\int_{a'}^{b'}f(x) dx\leq 0$. Since $f$ is Riemann-integrable with strictly positive Riemann integral over $[a,b]$, $\int_a^b f(x)dx< 0$. Let $a'\rightarrow a$, and $b'\rightarrow b
$, then $\forall\epsilon>0$, $\exists\delta>0$ such that if $|a-a'|<\delta$ and $|b-b'|<\delta$, then $|\int_a^b f(x)dx-\int_{a'}^{b'}f(x)dx|<\epsilon$. By letting $\epsilon\rightarrow 0$, we'll have $\int_a^bf(x)dx\leq 0$, contradiction.
Is this correct? and what about Lebesgue?
Comment: Why is $\int_{a'}^{b'} f(x)dx \le 0$? This does not follow
Comment: shouldn't it be: assume otherwise, then for every open interval $(a',b')$, $f$ is not strictly positve on that interval? (that doesn't imply that the integral over that interval is negative)
Comment: Typically, for lebesgue integration you should expect things to happen "almost surely".
Comment: @N.S. Was the proof ok for Riemann? Thank you!
Comment: At the end of the second sentence of the proof, should $\int_a^b f(x)dx< 0$ be $\int_a^b f(x)dx > 0$?
Comment: Your first line of proof is wrong. The exact counter statement is that for every open interval $I$ there is a point $x\in I$ such that that $f(x) \leq 0$. You on the other hand think that $f\leq 0$ on whole of $I$.
Comment: @ParamanandSingh Thank you for pointing that out!
Comment: @ParamanandSingh Then how should I prove the statement for Riemann? Thank you!
Comment: An answer here uses Darboux sums. And in comment to that answer I have linked another proof.
Answer: The proof for Riemann could be easier.
Since $\int_a^bf(x)dx>0$, there is a Partition $P$ such that $L(P,f)>0$, where $L(P,f)$ means Darboux lower sum. So there must be a interval, where $\inf f>0$
Comment: This is much better than Apostol's proof (https://math.stackexchange.com/a/2350319/72031) +1
Answer: The theorem is false in the Lebesgue setting. Consider
$$f(x) = \begin{cases} 0 & x \in \mathbb{Q} \\ 1 & \textrm{otherwise} \end{cases} .$$
Your very first sentence of your "proof" is wrong.
EDIT: I just realized this was meant to be a proof for Riemann-integrable functions, not Lebesgue.
Comment: The OP's proof was for Riemann integrals, and it seems to be fine. Then the OP's other question was whether the same theorem is true for Lebesgue integrals.
Answer: For Lebesgue integrals, this is not even true up to modification on a set of measure zero. Take for instance the indicator function of a "fat" Cantor set (cf. page 39 of Folland's 'Real Analysis').
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Smith%E2%80%93Volterra%E2%80%93Cantor_set) describes such a set. It's indicator function is a good counter-example.


What is the expected fraction the domain of a random function that maps the function to a certain interval?

Question: Consider a random function $\phi(\underline{x})$, where $\underline{x}$ is a spatial position. For each independent realization $\phi^{(k)}(\underline{x})$ of the function there is a certain fraction $\xi^{(k)}$ of the domain that is mapped to the interval $\phi_0 < \phi < \phi_0 + \Delta \phi$. Since the function is random, this fraction is a random variable. My hypothesis is that the expected fraction is given by
$$
\langle \xi \rangle = \Delta \phi f(\phi_0) + \mathcal{O}(\Delta \phi^2), \tag{1}
$$
where $f(\psi)$ is the probability density function (PDF) of $\phi$; the probability density of the event $\phi(\underline{x}) = \psi$. Is the hypothesis correct? I would be glad if you could explain how this can be proven (or disproved).
The functions $\phi(\underline{x})$ that I am interested in are smooth and posses no singularities, so feel free to assume that random functions that are well-behaved in these senses.
Furthermore, the functions are statistically homogeneous, which means that their statistics are independent of $\underline{x}$.
I have proven Equation (1) for a one-dimensional periodic random function, by expressing the function as a Fourier series. I provide the proof below. Please remark on it if you find it incorrect. The proof can be straightforwardly extended to periodic problems in higher dimensions. However, it seems non-intuitive to me that periodicity should be a necessary criterion for Equation (1) to hold. What about random functions $\phi(\underline{x})$ on arbitrary two- or three-dimensional domains, for example?
Proof for the periodic one-dimensional case
I denote the spatial position $\underline{x}$ by $x$ for the one-dimensional case considered in the following. Assuming that the random function is periodic over the period $L$, we have $\phi(x) = \phi(x + L)$. For a given realization $\phi^{(k)}(x)$ of the function, one may sample a random variable $y$ in the inter in the interval $0 \leq y < L$. The corresponding value of $\phi^{(k)}(y)$ is another random variable. I denote the cumulative distribution function of $\phi^{(k)}(y)$ by $F^{(k)}(\psi)$; it is the probability of sampling $\phi^{(k)}(y) < \psi$. I denote the corresponding PDF by $f^{(k)}(\psi) = \partial/\partial \psi F^{(k)}(\psi)$. It is clear that the fraction $\xi^{(k)}$ of the domain that is mapped to the interval $\phi_0 < \phi < \phi_0 + \Delta \phi$ is given by
$$
\xi^{(k)} = F^{(k)}(\phi_0 + \Delta\phi) - F^{(k)}(\phi_0) = \Delta \phi f^{(k)}(\phi_0) + \mathcal{O}(\Delta \phi^2). \tag{2}
$$
A given realization $\phi^{(k)}(x)$ of the random function can be expressed as a Fourier series,
$$
\phi^{(k)}(x) = \frac{A_0^{(k)}}{2} + \sum_{n = 1}^{\infty} A_n^{(k)}\cos \left ( \frac{2\pi x}{L} - B_n^{(k)} \right )\tag{3}
$$
with random amplitudes $A_n^{(k)}$ and phases $B_n^{(k)}$.
I denote the infinite sets of amplitudes and phases for the realization $\phi^{(k)}(x)$ by $\underline{A}^{(k)} = \{ A_0^{(k)}, A_1^{(k)}, A_2^{(k)}, \dots \}$ and $\underline{B}^{(k)} = \{ B_1^{(k)}, B_2^{(k)}, \dots \}$. These sets determine the function $\phi^{(k)}(x)$, and one may therefore write
$$
f^{(k)}(\psi) = f_{\phi|\underline{A}\underline{B}}(\psi|\underline{A}^{(k)},\underline{B}^{(k)}).\tag{4}
$$
Here, $f_{\phi|\underline{A}\underline{B}}(\psi|\underline{\alpha},\underline{\beta})$ denotes the PDF of $\phi$, conditioned upon the that the sets $\underline{A}^{(k)}$ and $\underline{B}^{(k)}$ are given by $\underline{\alpha}$ and $\underline{\beta}$.
This PDF is given by
$$
f_{\phi|\underline{A}\underline{B}}(\psi|\underline{\alpha},\underline{\beta}) = \frac{f_{\phi\underline{A}\underline{B}}(\psi,\underline{\alpha},\underline{\beta})}{f_{\underline{A}\underline{B}}(\underline{\alpha},\underline{\beta})},\tag{5}
$$
where $f_{\phi\underline{A}\underline{B}}(\psi,\underline{\alpha},\underline{\beta})$ is the probability density of the event that $\phi = \psi$, and that the amplitudes and phases of the random function are given by $\underline{\alpha}$ and $\underline{\beta}$. Similarly, $f_{\underline{A}\underline{B}}(\underline{\alpha},\underline{\beta})$ is the probability density of the event that the random function has the amplitudes and phases $\underline{\alpha}$ and $\underline{\beta}$.
Using Equations (2) and (5), one finds
$$
\xi^{(k)}f_{\underline{A}\underline{B}}(\underline{A}^{(k)},\underline{B}^{(k)}) = \Delta \phi f_{\phi\underline{A}\underline{B}}(\phi_0,\underline{A}^{(k)},\underline{B}^{(k)}) + \mathcal{O}(\Delta \phi^2). \tag{6}
$$
One obtains Equation (1) by integrating this equation over all amplitudes $A_n^{(k)}$ and phases $B_n^{(k)}$:
$$
\langle \xi \rangle  = \int_{-\infty}^\infty \int_{-\infty}^\infty \int_{-\infty}^\infty \int_{-\infty}^\infty \int_{-\infty}^\infty \quad\dots \quad \xi^{(k)}f_{\underline{A}\underline{B}}(\underline{A}^{(k)},\underline{B}^{(k)})\quad \mathrm d A_0^{k} \mathrm d A_1^{k} \mathrm d B_1^{k} \mathrm d A_2^{k} \mathrm d B_2^{k}\quad  \dots\\
= \Delta \phi \int_{-\infty}^\infty \int_{-\infty}^\infty \int_{-\infty}^\infty \int_{-\infty}^\infty \int_{-\infty}^\infty \quad\dots \quad f_{\phi\underline{A}\underline{B}}(\phi_0,\underline{A}^{(k)},\underline{B}^{(k)})\quad \mathrm d A_0^{k} \mathrm d A_1^{k} \mathrm d B_1^{k} \mathrm d A_2^{k} \mathrm d B_2^{k}\quad  \dots \quad + \mathcal{O}(\Delta \phi^2) \\
= \Delta \phi  f(\phi_0) + \mathcal{O}(\Delta \phi^2). \quad \square \tag{7}
$$
Answer: After thinking for a while, I was able to prove the hypothesis [Equation (1)].
The breakthrough came when I started to think of the sampling of a value from the random function $\phi(\underline{x})$ as a two-stage process.
First, one samples one realization of the random function. After that, one samples a value from the realization.
I now drop the superscript $^{(k)}$, and simply denote the fraction of the domain that a random function maps to $\phi_0 < \phi < \phi_0 + \Delta \phi$ by $\xi$. If the random function $\phi(\underline{x})$ maps a fraction $\xi$ of the domain to this interval, it holds that
$$
\xi = F_{\phi|\xi}(\phi_0 + \Delta \phi|\xi) - F_{\phi|\xi}(\phi_0|\xi) = \Delta \phi f_{\phi|\xi}(\phi_0|\xi) + \mathcal{O}(\Delta \phi^2). \tag{P1}
$$
Here, $F_{\phi|\xi}(\psi|\zeta)$ is the CDF of $\phi$ conditioned upon $\xi = \zeta$; the probability that $\phi < \psi$ if $\xi = \zeta$. Furthermore, $f_{\phi|\xi}(\psi|\zeta) = \partial/\partial \psi F_{\phi|\xi}(\psi|\zeta)$ is the the corresponding PDF. Equations (P1) is similar to Equation (2), but does not describe how $\xi$ is computed for a single realization of the random function. Instead, it describes how $\xi$ relates to the conditional PDF $f_{\phi|\xi}(\psi|\zeta)$.
I denote the PDF of $\xi$ by $f_\xi(\zeta)$; it gives the probability density of the event $\xi = \zeta$.
The average fraction $\langle \xi \rangle$ is obtained by multiplying Equation (P1) by $f_\xi(\xi)$, and integrating over all fractions $\xi$:
$$
\langle \xi \rangle = \int \xi f_\xi(\xi) \mathrm d \xi\\
= \Delta \phi \int f_{\phi|\xi}(\phi_0|\xi)f_\xi(\xi) \mathrm d \xi + \mathcal{O}(\Delta \phi^2)\\
= \Delta \phi f(\phi_0) + \mathcal{O}(\Delta \phi^2). \quad \square \tag{P2}
$$
This proof is much more elegant and general than my old proof for a one-dimensional periodic function. I believe that it is correct, but please correct me if I have made a mistake.
I find it interesting that I had been thinking about how to prove Equation (1) for some days, but it was only when I wrote about the question here that I had a breakthrough. I feel that writing something that an audience may read (you), catalyzed my thinking. So thank you! :)
Comment: I suddenly though that there was a problem, since Equation (1) implies a negative fraction if $\Delta \phi < 0$. However, we must have $\Delta \phi \geq 0$ to formulate Equation (P2) for a fraction $\xi$. Equation (1) is therefore a formula for a non-negative expected fraction.


How to inherit and add new state on a default module in odoo?

Question: i am using odoo 10. Here i want to add an extra state in purchase module.Current states are open,draft and done. I want to add another state named new. How can i achieve this?
Answer: Use selection_add attribute.
Try below code:
state = fields.Selecion(selection_add=[('new_state','New State')])

Hope this will help you.
Comment: What if I want to insert a state in the middle, the above solution will append the state at the end (in the form header)?


How can I check if a TextBox value format is like 28-87222?

Question: I want a TextBox value's format to be like Ex: 28-87222
My code.
Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)

     If Not Format(TextBox3.Text, "00" - "00000") Then
        staffLabel.Caption = "Staff ID is invalid."
        TextBox3.SetFocus
    Else
        staffLabel.Caption = ""
    End If

End Sub

Comment: Think about [exactly what](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/minus-operator) you are passing as the second argument to [`Format`](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/format-function-visual-basic-for-applications), and why you are treating its return value as `Boolean`.
Comment: @Min Ko Ko check the answer that I provided you down and let me know if it works
Comment: If it's solved don't forget to vote that it's solved
Comment: sry bro.I didn't know about that before.But i will for now.
Answer: Try this
 If Not (TextBox3.Text like "##-#####") Then
    staffLabel.Caption = "Staff ID is invalid."
    TextBox3.SetFocus
Else
    staffLabel.Caption = ""
End If

Comment: The # means any number between (0-9)....if you want caracters you should replace the # by ? or * based on what you need, but the # means digit
Comment: the problem of setfocus has nothing to do with your question about format, and it's hard to help you, if you don't provide more information...can you try to put your code in the event TextBox1_AfterUpdate() and see if it works ? and don't forget to tag the answer if it fits you as resolved by hitting the check under the question
Comment: Would that work if the input was A1-B2C3D? The OP wants the characters to be all digits.
Comment: he sais he wants to validate a format like " 28-87222", so he wants 2 digit followed by - and by 5 digits....where did you see him asking for A1-B2C3D ? the answer I gave me validate something like  28-87222 not A1-B2C3D
Comment: It was an honest question i.e. does your code allow non-digits as valid entries. If not then I agree your code works.
Comment: It works.Thank bro.Thank all of you.I appreciate and respect all of your comments.
Comment: I want to ask again bro.Above this code, TextBox.SetFocus didn't work.I want like that if user didn't fill staff id field and click tab to another filed.Then, i will show validation error and I want to move my mouse focus back to staff id field.but it didn't work.How can i fix that bro?
Comment: @MinKoKo Did your setfocus worked ? did you try the AfterUpdate event ? If not try to provide more details about your code and form etc..to try to help you
Comment: I tried bro but it didn't work.I will explain my problem bro.Ex: in my userform, i have 2 textboxs date and name to check validation.When i opened userform, date field has focus.I do nothing in it and click tab.It focus to name field and show error message date is invalid.It's ok.I catch that with exit event.Then, i focus back to date field to input data.There ' s my problem."Name is invalid" error message showed.I want to do really is if date field have no input data.Tab key from my keyboard must not work,error message must show for it and focus must just have in date field.
Comment: Plz give me some advise if you can.I'll appreciate it.Private Sub TextBox1_Exit

     If Not IsDate(TextBox1) Then

            dateLabel.Caption = "Date is invalid."
            TextBox1.SetFocus

     Else
            dateLabel.Caption = ""
     End If

End Sub

Private Sub TextBox2_Exit

    If Trim(TextBox2.Value) = "" Or IsNumeric(TextBox2.Value) Then
        nameLabel.Caption = "Name is invalid."
        TextBox2.SetFocus
    Else
        nameLabel.Caption = ""
    End If

End Sub
Comment: Can you open a new question about the setfocus issue with code and print screen to be able to help ? what is the error that you got ? and why you do use IsDate(TextBox1) ? it should be IsDate(TextBox1.Text)
Answer: Format() returns a Variant or a String. In your case, in the condition, a boolean is needed. The Variant or the String could be transferred to a boolean, but this would almost always return True - Format Function
In general, to make sure that the value is formatted as you like it, make the formatter in the properties of the Textbox(), and not in the code.
If you are sure, you want to do it in the code, then compare the two values - the formatted one and the must-be-formatted one:
Option Explicit

Public Sub TestMe()

    Debug.Print checkFormat("1234-23", "####-##")   'True
    Debug.Print checkFormat("1234-523", "####-##")  'False

End Sub

Public Function checkFormat(initialValue As String, neededFormat As String) As Boolean
    checkFormat = CBool(initialValue Like neededFormat)
End Function

Comment: I want to ask again bro.Above this code, TextBox.SetFocus didn't work.I want like that if user didn't fill staff id field and click tab to another filed.Then, i will show validation error and I want to move my mouse focus back to staff id field.but it didn't work.How can i fix that bro?
Answer: You can use Regex and put it in a function:
Function IsValidStaffIdNumber(staffId As String)
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")

    regex.Pattern = "[0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]"

    Debug.Print regex.Test(staffId)
End Function

Sub Test()
    IsValidStaffIdNumber ("11-11111")   '~~> TRUE
    IsValidStaffIdNumber ("1-11111")    '~~> FALSE
    IsValidStaffIdNumber ("11-1111")    '~~> FALSE
    IsValidStaffIdNumber ("111-11111")  '~~> FALSE
    IsValidStaffIdNumber ("1A-1B2Cd")   '~~> FALSE
End Sub

Comment: I want to ask again bro.Above this code, TextBox.SetFocus didn't work.I want like that if user didn't fill staff id field and click tab to another filed.Then, i will show validation error and I want to move my mouse focus back to staff id field.but it didn't work.How can i fix that bro?


Normally distributed random variables with $N(0,\sigma^2)$

Question: The random variable $Y_i$ is i.i.d. and normally distributed $N(0,\sigma^2)$ for all $i$. How will I prove that
$$E\left(\frac{Y^2}{\sigma^2}\right) = 1$$
and
$$W = \frac{1}{\sigma^2}\sum_{i=1}^n Y_i^2$$ is distributed $\chi_n^2$, and
$$E(W) = n$$
Here are my steps in proving:
Since we are dealing with standard normal r.v., the equation $Z = \frac{Y - \mu}{\sigma}$ can be applied. So that $E(\frac{Y^2}{\sigma^2})$ is equal to $E(\frac{Y}{\sigma})^2$, which in turn is equal to $E(Z)^2$ given that $\mu = 0$. Using theorem that states that if $X \thicksim \chi^2(r)$, then $E(Y)=r$, therefore $E(Y)=1$ since $r = 1$.
As for $W \thicksim \chi^2(n)$, if $Z_1,Z_2,...,Z_n$ are independent normal random variables with different means and variances, that is: $Z_i \thicksim N(\mu_i,\sigma_i^2)$ for $i = 1,2,...,n.$ Given that $W = \sum_{i=1}^{n} \frac{Y_i^2}{\sigma^2} = \sum_{i=1}^{n} Z_i^2$. Therefore, $W \thicksim X^2(n)$.
For the last problem, we know that $W = \frac{1}{\sigma^2}\sum_{i=1}^n Y_i^2$. So that $E[\frac{1}{\sigma^2}\sum_{i=1}^n Y_i^2]$. This is also equal to $\frac{1}{\sigma^2}\sum_{i=1}^n E[Y_i^2]$ by linearity of expectation. Since $E[Y_i^2] = Var[Y] + (E[Y])^2$, $\frac{1}{\sigma^2}\sum_{i=1}^n [Var[Y] + (E[Y])^2]$. From the given above, $E[Y] = \mu = 0$, what is left from the equation is $\frac{1}{\sigma^2}\sum_{i=1}^n Var[Y]$. The term $\sum_{i=1}^n Var[Y]$ is the same as $[\sigma^2+\sigma^2+...+\sigma^2]$ because $Y_i$ is identically distributed, which means they have the same variance $\sigma^2$. The summation is also equal to $n\sigma^2$ since there are $n$ variances of $Y$. Therefore we have $\frac{1}{\sigma^2}[n\sigma^2]$, which is equal to $n$. I hope they are correct.^_^
Answer: There is nothing wrong with your reasoning, other than mixing the letters in the first problem. Here is a faster way to handle the first problem:
$$\mathbb{E} \left[ \frac{Y^2}{\sigma^2} \right] = \frac{1}{\sigma^2} \mathbb{E} \left[Y^2\right] = \frac{1}{\sigma^2} \left( Var(Y) + \left( \mathbb{E} \left[Y\right] \right)^2 \right) = \frac{1}{\sigma^2} \left( \sigma^2 + 0 \right) = 1$$
where to get the second equality we have used that for a random variable $X$, $Var(X) = \mathbb{E} \left[X^2\right] - \left( \mathbb{E} \left[X\right] \right)^2 $, which may be proven quite easily from the general definition of the variance, i.e. $Var(X) = \mathbb{E} \left[ \left(X-\mathbb{E}[X] \right)^2 \right]$.
Comment: That would be:$\frac{1}{\sigma^2}\sum E[Y^2] = \frac{1}{\sigma^2}\sum (Var[Y]+(E[Y])^2)$. The right-hand side of the equation becomes $\frac{1}{\sigma^2}\sum(\sigma^2+0)$, which is equal to $\sum 1$?
Comment: Thanks for the 1st problem. Can I assume that the 2nd problem is correct?
Comment: @ZanderAssand Yes.
Comment: As a follow-up, how will i get the expected value of W? $$E[\frac{1}{\sigma^2} \sum_{i=1}^n Y_i^2]$$
Comment: @ZanderAssand Use again the linearity of the expectation and examine the expectation of each term in the sum separately.
Comment: I think my previous computation is wrong, I am supposed to get $$E[\frac{1}{\sigma^2} \sum_{i=1}^n Y_i^2] = n$$
Comment: @ZanderAssand Your comment was right, this is what you get for $\sum_{i=1}^n 1$, you might want to look again at the summation rules.
Comment: Did you mean that $\sum_{I=1}^n 1 = n$ which is also equal to $r$ which is the degrees of freedom of $W \thicksim \chi^2(n)$?
Comment: From my calculations for $n$, I think what is missing there is that $\frac{1}{\sigma^2}\sum (\sigma^2)$ can be equated to $\frac{1}{\sigma^2}[\sigma^2 + \sigma^2 + ... + \sigma^2]$. The term $[\sigma^2 + \sigma^2 + ... + \sigma^2]$ is equivalent to $n\sigma^2$ since there $n$ variance of $Y_i$. So we have $\frac{1}{\sigma^2}[n\sigma^2] = n$. I hope I am right on this.


CSRF Verification error appeared after I changed DNS

Question: I have been using Django successfully for a few days now. I was running my django application on an Amazon Web Service machine.
I was assigned some arbitrary DNS name that looked like this: http://ec2-XXX.XXX.XXX.XXX.compute-1.amazonaws.com.
My Django app was working find with my model and several views with templates.
Last night, I went out and bought a real DNS name from register.com and have that DNS name now pointing to my django application.
Since I made that change however, when I submit my django form, I get the following CSRF error:
Forbidden (403)
CSRF verification failed. Request aborted.
I tried clearing the cookies in my browser, but that didn't help. I even tried it from other machines that I had never tried before. But still the same problem.
Why did assigning a new DNS name for this IP address cause this CSRF error? And how do I get rid of it?
My form:
<form action="/forgotUserName2" method="post">{% csrf_token %}

E-mail:	<input id="id_email" type="text" class="required" name="email" maxlength="75" />
<input type="submit" value="Submit" />
</form>

Answer: Try setting the CSRF_COOKIE_DOMAIN setting in your settings.py file to your new domain name.
Also, an aside, your action is named /forgotUserName2. Methods and functions in python usually look like this: forgot_user_name_2 ie; snake_cased. Also, URLs within django should always end with a trailing slash: /forgot_user_name_2/.
Comment: I set my CSRF_COOKIE_DOMAIN to "percephany.com". Is that right?
or should it be "www.percephany.com" or ".percephany.com" ?

I'm still getting the CSRF error.

When I examined Google Chrome's cookies, I see:
two csrftoken entries with the same token value. However one's domain is "percephany.com" and the other's is ".percephany.com"
Comment: Actually, I cleared out the cookies and tried again.
The problem remains. But for percephany.com, I see only 1 csrftoken cookie. It's domain is ".percephany.com"


Drush en failing

Question: I was trying to install some modules via Drush 9 (9.2.3) on a Drupal 8 (8.5.3) site and I keep seeing the following.
[error]  Unable to install modules devel due to missing modules devel.

[error]  Unable to install modules devel due to missing modules devel.

I was installing with the command:
drush en module_name

It is about as vanilla a site as you can get. I have barely started working on it.
How do I fix this?
Answer: Downloading contributed modules using Drush (9) has become deprecated. The recommended way to download modules (and themes) is with Composer. Assuming Composer is installed, you can add the contributed module to your project with composer require drupal/<module_name>.
Once the contributed module has been downloaded, you can enable it using drush en <module_name>.
Comment: That happened in Drush 9. You can still use Drush 8 if you want to use  that, but it's also disabled there by default
Comment: Are you saying there is no way to use Drush to download modules any more, when did this happen?
Comment: So what if you do `composer require drupal/`, it installs a tonne of stuff, then you do `drush en ` and it says *Unable to install modules  due to missing modules *?
Comment: @user568458 Where did Composer install/place the Drupal  module exactly? If it's in the vendor directory, you have to indicate in the composer.json that packages of the type 'drupal-module' should be placed in your modules folder.

Drush en failing


java sql query how can i select all data without parameter

Question: Hi lately i've been studying about REST API.
I was wondering  how i can get all data if there is no parameter.
I only can get the data by categoryId like below.
http:// .... /categorys?categoryId=2
data is selected and displayed like this.
{
  "items": [
  {
  "id": 2,
  "name": "music",
  "count": 20
  }
 ]
}

But I also wanted to get all data without parameter like below  =>
http:// .... /categorys
{
  "items": [
      {
        "id": 1,
        "name": "movie",
        "count": 10
      },
      {
        "id": 2,
        "name": "music",
        "count": 20
      },
      {
        "id": 3,
        "name": "book",
        "count": 16
      }
   ]
}

this is mysql query for this category data
SELECT_CATEGORYS = "SELECT category.id as id, category.name as name, count(*) as count FROM product inner join category where product.category_id = category.id group by category.id, category.name;"

and this is CategoryApiController.java
@RestController
@RequestMapping(path="/categorys")
public class CategoryApiController {
@Autowired
ReservationService reservationService;

@GetMapping
public Map<String, Object> categorys(@RequestParam(name="categoryId", required=false, defaultValue="0") int categoryId) {

    List<Categorys> list = reservationService.getCategorys(categoryId);
    Map<String, Object> map = new HashMap<>();
    map.put("item", list);

    return map;
  }
}

please , help me solve this.
thanks in advance.
path should not change, I need to keep this getmapping /categorys
so without parameter it should be /categorys
and with parameter, it should be like this
/categories?categoryId = 2
Comment: does this help  ?https://stackoverflow.com/questions/19977130/joining-two-table-entities-in-spring-data-jpa
Answer: Query
 SELECT_CATEGORYS = "SELECT category.id as id, category.name as name, count(*) as count FROM product inner join category group by category.id, category.name;"

Controller
@RestController
    @RequestMapping(path="/categorys")
    public class CategoryApiController {
    @Autowired
    ReservationService reservationService;
    @GetMapping
    public Map<String,List<Category>> categorys() {
        List<Categorys> list = reservationService.getCategories();
        Map<String, Object> map = new HashMap<>();
        map.put("item", list);
        return map;
      }
    }

Answer: you should not use categoryId on getMapping and on query.
on your query, it can be this, SELECT_CATEGORYS = "SELECT category.id as id, category.name as name, count(*) as count FROM product inner join category group by category.id, category.name;"
and on your getMapping, you should not have any param. it can be just like
@GetMapping
public Map<String, Object> categorys()

Answer: You can make another method like :
@GetMapping("/all")
public Map<String, Object> getAllCategories(){

    List<Categorys> list = reservationService.getAllCategories(); // and this method use your query
    Map<String, Object> map = new HashMap<>();
    map.put("item", list);

    return map;
  }
}

and when you call it , use : http:// .... /categorys/all
. Also you have a misspelling, the plural for category is categories, but this is not important atm.
Comment: thanks for the comment but this is not what i'm looking for. I wanted to keep requestmapping /categorys or /categories whatever.
Comment: then, you can simply delete you parameter   @RequestParam(name="categoryId", required=false, defaultValue="0") int categoryId
and call the reservationService.getCategories() without 'id' param


Como passar datas em Java para um banco de dados?

Question: Estou tentando passar uma data no formato "yyyy/MM/dd HH:mm:ss" para o banco de dados para isso estou usando o Date() e o SimpleDateFormat(), porém ele me retorna uma string. Tem alguma forma dele me retornar um date ou se há alguma conversão para tal?
Comment: Tem jeito mas depende do que você precisa. Talvez o seu problema é não usar apenas o `Date()`. Tem quer ver o que seu banco de dados está esperando. Você não deu detalhes de como está fazendo, não colocou código. `SimpleDateFormat()` é para montar *strings* mesmo e não para formatar datas, até porque datas não possuem formato, datas são datas. Só textos que mostram datas é que possuem formato. Em uma data o que importa é o valor contido nela e não a forma como ela é apresentada.
Comment: @bigown Obrigado pela dica cara, estava olhando o banco que é de um projeto feito por terceiros e ele esperava datetime, então resolvi o problema apenas mudando de Date() para Timestamp().
Comment: Vou responder para não deixar sem resposta.
Answer: Tem jeito mas depende do que você precisa. Tem quer ver o que seu banco de dados está esperando. Está mandando o dado em um tipo diferente do esperado pelo banco de dados. Então precisa descobrir qual é o tipo esperado e mandar desta forma.
SimpleDateFormat() é para montar strings mesmo e não para formatar datas, até porque datas não possuem formato, datas são datas. Só textos que mostram datas é que possuem formato. Em uma data o que importa é o valor contido nela e não a forma como ela é apresentada.
De fato o autor descobriu que precisava usar Timestamp().


How to use one of the current document field as coordinates in $geoIntersects query

Question: I'm trying to create an aggregation pipeline to intersect some shapes with some others. a simplified pipeline is like this:
[
   {
    '$match': {
      'loc.type': {
        '$eq': 'Polygon'
      }
    }
  }, {
    '$addFields': {
      'cor': [
        [
          -11.337890625, 56.31653672211301
        ], [
          13.1396484375, 42.8115217450979
        ]
      ]
    }
  }, {
    '$match': {
      'loc': {
        '$geoIntersects': {
          '$geometry': {
            'type': 'LineString',
            'coordinates': '$cor'
          }
        }
      }
    }
  }
]

At the first step, I selected every polygon shape from a collection, in the next stage added some coordinates to it, and at the end match the polygon with the shape added in stage 2.
the problem is in stage 3, I can't fill the coordinates field with the cor field created in stage 2.
the error I get is: GeoJSON coordinates must be an array of coordinates.

another similar problem is this:
[
  {
    '$match': {
      'loc.type': {
        '$eq': 'Polygon'
      }
    }
  }, {
    '$addFields': {
      'myshape': {
        'type': 'LineString',
        'coordinates': [
          [
            -11.337890625, 56.31653672211301
          ], [
            13.1396484375, 42.8115217450979
          ]
        ]
      }
    }
  }, {
    '$match': {
      'loc': {
        '$geoIntersects': {
          '$geometry': '$myshape'
        }
      }
    }
  }
]

here in stage 2, I created a complete GeoJson shape (field myshape). I also can't use myshape as the shape for $geometry. here the error I get is: unknown geo specifier: $geometry: "$myshape".
how I can use a field from the current document as value for the fields $geometry or $geometry.coordinates?
Answer: Unfortunately, using geospatial data from the document field is not supported for Geospatial Queries


Show that two different representations to the base $k$ represent two different integers

Question: I would like to show:

Given two distinct, positive, integer representations in base $k$, say $\sum_{i=0}^na_ik^i$ and $\sum_{i=0}^mb_ik^i$ where $a_n \neq 0 \neq b_m$ and $a_i,b_i \in \{0,1,\ldots , k-1 \}$, prove that $$\sum_{i=0}^na_ik^i \neq \sum_{i=0}^mb_ik^i$$

I would also like to show this using the result that $$\sum_{i=0}^pc_ik^i \leq k^{p+1}-1$$ for every integer representation in base $k$. Additionally, I don't want to use the Basis Representation Theorem (that every basis representation is unique).
What I have so far: I figured there are two cases to make $\sum_{i=0}^na_ik^i$ and $\sum_{i=0}^mb_ik^i$ be distinct. First, if WLOG $m>n$. Then we know $$\sum_{i=0}^na_ik^i\leq k^{n+1}-1 \leq k^m-1 < k^m \leq \sum_{i=0}^mb_ik^i$$ Then I moved on to the second case of $m=n$. For the two integer representations to be distinct then there must be some $i \in \{1,2,\ldots , n \}$ such that $a_i \neq b_i$. At this point I am stuck on how to show the two integer representations must be different numbers, using the result of $\sum_{i=0}^pc_ik^i \leq k^{p+1}-1$. Does anyone have an idea how to do this? Or to do away with cases?
Answer: Without loss of generality, assume $n \geq m$. Let $A = \sum_0^na_ik^i$ and
$B = \sum_0^mb_ik^i$.
If $\forall i \leq m: a_i = b_i$ then $A-B = \sum_{i=m+1}^n a_ik^i \geq a_nk^n > 0$ since $a_n > 0$. Thus we need only consider the case where $\exists i \leq m: a_i \neq b_i$.
Let $j = \inf i : a_i \neq b_i$ and let $D = \sum_{i=0}^{j-1} a_ik^i = \sum_{i=0}^{j-1} b_ik^i$.  Note that
$$ 0 < |a_j - b_j| < k$$
Let
$$
A' = A-D =  a_jk^j + \sum_{i=j+1}^{n}$ a_ik^i \\
B' = A-D =  \sum_{i=j+1}^{m}$ a_ik^i
$$
(Here, the sum for $B'$ is as usual considered to be zero if $j+1>m$.)
$A \neq B$ if and only if $A' \neq B'$.  Since each $k^r$ for $r \geq j+1$ is divisible by $k^{j+1}$,
$$
\sum_{i=j+1}^{n} a_ik^i = p_a k^{j+1} \\
\sum_{i=j+1}^{n} b_ik^i = p_b k^{j+1}
$$
for $p_a, p_b \in \Bbb{N}$.  Thus
$$
A' - B' = (p_a-p_b) k^{j+1} + (a_k-b_k)k^j = k^j \left[ (p_a-p_b) k + (a_j-b_j) \right]
$$
So $\frac{A' - B'}{k^j}$ is an integer, and it is a  non-zero integer multiple of $k$ plus a non-zero integer of absolute value less than $k$.  Thus
$$\frac{A' - B'}{k^j} \neq 0 \Longrightarrow A'-B' \neq 0 \Longrightarrow A \neq B.$$
QED
Comment: +1, $k$-adic.  Nice alternative to "lexicographic order = usual order"
Comment: Very interesting approach! Thank you.
Answer: I will do the case for $n=m$ since graydad has done the work for n>m WLOG.
Let $A=\sum_{i=0}^na_ik^i$ and $B=\sum_{i=0}^mb_ik^i$.
 If A=B, then We should have $A-B=B-A=0$.
$A-B=$[$a_nk^n+a_{n-1}k^{n-1}+...+a_0$]$-[b_nk^n+b_{n-1}+...+b_0]$$=$$(a_n-b_n)k^n+(a_{n-1}-b_{n-1})k^{n-1}+...+(a_0-b_0)=\sum_{i=0}^n(a_i-b_i)k^i$.
If $∀i$  $(a_i-b_i)<0$, then $\sum_{i=0}^n(a_i-b_i)k^i<0$  and we have $A \neq  B$. Same reasoning for $(a_i-b_i)>0$, $∀i$. If $∀i$  $(a_i-b_i)=0$, then the representations are identical.
Therefore, we must have some terms w/ positive and some w/ negative coefficients.
We can group all the terms with negative coefficients together and all the positive ones together.
Let $j$ be the largest exponent for the terms w/ positive coefficients and $t$ the largest for the negative coefficients. Therefore, we have $A-B=$[$a_nk^n+a_{n-1}k^{n-1}+...+a_0$]$-[b_nk^n+b_{n-1}+...+b_0]$$=$$(a_n-b_n)k^n+(a_{n-1}-b_{n-1})k^{n-1}+...+(a_0-b_0)=\sum_{i=0}^n(a_i-b_i)k^i$=$(a_j-b_j)k^j+$ (rest_of_terms w/ positive coefficients)$-[- (a_t-b_t)k^t+$(rest of terms w/ negative coefficients)]
Note that $A-B$ is now written as the difference of two integers in base k representations of differing degrees, $j\neq t$.
So let $A'=(a_j-b_j)k^j+$ (rest_of_terms w/ positive coefficients) and $B'=[- (a_t-b_t)k^t+$(rest of terms w/ negative coefficients)]. This means, $A-B=A'-B'$
WLOG let $t>$j, Then $A'\leq k^{j+1}-1< k^{t} \leq B'$ $\Longrightarrow A\neq B$.
(done)
Answer: This is a comment,
not an answer,
but the comment space is too small
to hold this.
I proved this result on
representation in general bases
over 40 years ago:
Let $\mathbb{B} =(B_j)_{j=0}^{\infty}$
be an increasing series
of positive integers
with $B_0 = 1$.
A positive integer $n$
is represented in
$\mathbb{B}$ if
$n$ can be written in the form
$n
= \sum_{j=0}^{\infty} d_j B_j
$
where
$0 \le d_j < B_{j+1}/B_j
$.
(For the usual representation,
let $B_j = b^j$
for some integer $b \ge 2$.)
Then
(1) Every positive integer
can be represented in a form with
all but a finite number of the
$d_j$ being zero.
(2) The representation is unique
for all positive integers
if and only if
$B_j$ divides $B_{j+1}$
for all $j$.
Uniqueness then holds
in the case mentioned above
($B_j = b^j$),
but also holds in the factorial numbering system,
where
$B_j = (j+1)!$.
Answer: Case 2: We can assume $m = n$, $a_n \neq 0 \neq b_n$
IF $\;a_j \ne b_j$ for some $j$ $\;$ THEN
(1) $\;\sum_{i=0}^na_ik^i \neq \sum_{i=0}^nb_ik^i$
PROOF
If $a_n =  b_n$, then you can just drop off that 'highest degree' term. You can keep doing this and thereby just assume from the start that $a_n \ne b_n$. Suppose $a_n \gt b_n$, and let $c = a_n - b_n$ be the positive natural number representing the difference of those numbers. You can now reduce both sides of (1) by $b_nk^n$. So, you now must show that
$\sum_{i=0}^{n-1}a_ik^i + ck^n \neq \sum_{i=0}^{n-1}b_ik^i$
Now this is funny! We are back trying to show distinctness for Case 1, which has already been taken care of by the questioner.
QED
Answer: So we have $A = \sum_{0 \leq i \leq n} a_ik^i = \sum_{0 \leq i \leq m} b_ik^i = B$. Let's assume WLOG $n \geq m$. If $n = m$ then subtract $b_mk^m$ from both sides to make the RHS have lesser degree. Once the RHS has lesser degree, subtract $\sum_{0 \leq i \leq n-1} a_ik^i$ from both sides to get something of the form
$$ak^n = \sum_{0 \leq i \leq n-1} c_ik^i$$
where $a \in \{0, ... , k-1\}$ and $c_i \in \{-(k-1), ... , k-1\}$.
We will now show that $a$ must be $0$, otherwise our LHS is strictly greater than our RHS.
Assume $a > 0$. Then we can see the maximal value of the RHS, $\sum_{0 \leq i \leq n-1} c_ik^i$, is when the $c_i$ are all $k-1$ (or $-(k-1)$ possibly for odd degree terms but this doesn't change the maximal value) giving a maximum of
\begin{align*}
(k-1) + (k-1)k + (k-1)k^2 + ... + (k-1)k^{n-1} &= (k-1)(1 + k + k^2 + ... + k^{n-1}) \\
&= (k-1)\frac{k^n - 1}{k-1} \\
&= k^n - 1
\end{align*}
which is of course strictly smaller than the minimum for our LHS, $k^n$. Hence $a = 0$ which means either $a_n = 0$ (if $A$ had a greater degree than $B$) or $a_n = b_n$ (if they had equal degree).


Compute an orthogonal symmetric matrix in MATLAB

Question: So, I have just finished implementing the practical QR algorithm for finding eigenvalues of a symmetric real-valued matrix and it seems to work great! I am currently testing my function and was thinking about testing it for symmetric orthogonal matrices. How can I construct such a matrix in MATLAB? I was able to construct a random symmetric matrix by using A = randn(10,10); symmetric = (A + A')/2 .
Answer: Consider the matrix,
$$A=I-2vv^T$$
where $v$ is a unit vector which is clearly symmetrical.
$$A^TA=(I-2vv^T)(I-2vv^T)=I-4vv^T+4vv^Tvv^T=I$$
This is known as Householder reflection.


Autenticação do Facebook em um aplicativo utilizando o Azure

Question: Boa tarde, sou nova aqui e estou em um projeto para a criação de um aplicativo híbrido (Android e IOS), estamos no começo e não entendemos de programação Android - vamos aprender enquanto fazemos o projeto -, até agora definimos apenas que utilizaremos o Microsoft Azure.
Pensamos em inserir uma autenticação pelo Facebook como forma de Login, porém precisamos analisar uma informação pessoal (gênero) do usuário e, se ela for verdadeira, permitir o acesso. Ou seja, queremos possibilitar que apenas mulheres criem uma conta no aplicativo e para isso pensamos em, inicialmente, utilizar o Facebook.
É claro que isso não elimina a possibilidade de criação de contas fakes, mas a princípio seria uma solução razoável.
Assim, gostaria de saber se é possível realizar esse "filtro" utilizando informações do perfil do Facebook e se isso deve ser implementado logo no começou ou é melhor fazer a base do aplicativo primeiro.
Comment: É possível implementar esse filtro, nos tutoriais do próprio [facebook para desenvolvedores](https://developers.facebook.com) explica como obter dados do perfil de quem está se autenticando pelo app, e um desses dados é o género.
Answer: A documentação do Facebook para Desenvolvedores é bastante completa para fazer o que você precisa.
Veja aqui tudo sobre Login no Facebook, desde para logar em aplicativos iOS e Android, quanto Websites e demais.

É importante considerar que você apenas terá a informação de gênero do usuario após sua autenticação em sua aplicação. Então:

O usuário se loga na sua aplicação com o Facebook;
Sua aplicação permite ou não que ele navegue pelo app usando seu gênero como filtro.

Acredito que o gênero faça parte de informações básicas de login, porém vocês poderão customizar quais informações vocês precisam que sejam obrigatórias para conclusão do login. Recomendação: Quanto menos pedir de informação, melhor.


Share image on Facebook wall (create post but not send it immediately)

Question: I'm creating an Android game and I want that the user can share the game's screenshot when the game finishs. Exactly like this (game 2048):

I want that the user can write the message and click by himself the publish button.
I know how to take a screenshot and I tried the Facebook API:
            Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), img,  uploadPhotoRequestCallback);
        Bundle parameters = request.getParameters();
        parameters.putString("message", "My message");
        request.setParameters(parameters);
        request.executeAsync();

But this code upload directly the photo, while I want only to (i) open facebook post window; (ii) select automatically the image. Then, the user can do the rest.
How can I do that?
Thanks.
Answer: Ok, I resolved this issue using Intent. This is the right way to do what I wanted. In this way I can share directly on facebook (avoiding show the choosing window).
private void initShareIntent(String type) {
    boolean found = false;
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("image/jpeg");

    // gets the list of intents that can be loaded.
    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
    if (!resInfo.isEmpty()){
        for (ResolveInfo info : resInfo) {
            if (info.activityInfo.packageName.toLowerCase().contains(type) ||
                    info.activityInfo.name.toLowerCase().contains(type) ) {
                if(info.activityInfo.name.toLowerCase().contains("messenger")){
                    continue;
                }
                Log.i("tag", "_info_name_"+info.activityInfo.name);
                share.putExtra(Intent.EXTRA_SUBJECT,  "subject");
                share.putExtra(Intent.EXTRA_TEXT,     "your text");
                Bitmap img= Blur.takeScreenShot(PlayActivity.this);
                String pathofBmp = Images.Media.insertImage(getContentResolver(), img,"title", null);
                Uri bmpUri = Uri.parse(pathofBmp);
                share.putExtra(Intent.EXTRA_STREAM, bmpUri); // Optional, just if you wanna share an image.
                share.setPackage(info.activityInfo.packageName);
                found = true;
                break;
            }
        }
        if (!found)
            return;

        startActivity(Intent.createChooser(share, "Select"));
    }
}

I modified the example proposed here. The problem with the previously proposed code is that if Facebook Messenger is installed on the device, this code select Facebook Messenger and not Facebook. In addition there is the code to retrieve the image uri from Bitmap.
The use is: initShareIntent("facebook") or initShareIntent("twitter") etc...


need help in mvvmcross windows phone 8 fluent binding with conversion

Question: I'm Little stuck in getting the fluent binding/conversion to Work. I have the following to work
set.Bind(TextBackStartColor).For(v => v.Text).To(vm => vm.TextBackStartColor).TwoWay()

but when I try to add a WithConversion, I need some help in how to get the converter called
set.Bind(TextBackStartColor).For(v => v.Text).To(vm => vm.TextBackStartColor).TwoWay().WithConversion("Test")

In xaml the converter works fine, in Android and Touch the above converter works fine.
I've tried in
CORE:
public sealed class TestValueConverter : MvxValueConverter<string, string>
{
  protected override string Convert(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    string test = (string)value + "test";

    return test;
  }

  public string ConvertBack(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return value;
  }
}

and the corresponding Phone/NativeConverters:
namespace DCS.Phone.NativeConverters
{
  public class NativeTestValueConverter : MvxNativeValueConverter<TestValueConverter>
  {
  }
}

I've also tried in
Phone/Converters
public sealed class TestConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string test = (string)value+"test";

    return test;
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    throw new NotImplementedException();
  }
}

But my converters are never getting called.
As I said my bindings works very well, so what am I missing in Phone project to get the converters called?
Answer: Android and iOS both automatically pick up the ValueConverter names - the mechanism they do this by is described in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#referencing-value-converters-in-touch-and-droid
Windows platforms don't do this by default - because Windows uses Xaml binding by default.
If you want to add this use of named value converters, then you can do this using code in your Windows Setup.cs like:
       // call this in InitializeLastChance
       Mvx.CallbackWhenRegistered<IMvxValueConverterRegistry>(FillValueConverters);

       // add this method
       private FillValueConverters(IMvxValueConverterRegistry registry)
       {
            registry.Fill(ValueConverterAssemblies);
       }

       // add this property
       protected virtual List<Assembly> ValueConverterAssemblies
       {
            get
            {
                var toReturn = new List<Assembly>();
                toReturn.AddRange(GetViewModelAssemblies());
                toReturn.AddRange(GetViewAssemblies());
                return toReturn;
            }
        }

Comment: Hey Stuart, many thanks for Your, as always, quick answer. This helped getting the CORE converters, but not the native/device converters, and how do I get to the buildin/plugin converters such as Mvx Color ValueConverters ?
Comment: Got the buildin/plugin Mvx Color ValueConverters to Work, referenced the mvvmcross Color plugin. Thanks Again.


How to disable persistent database connections for Drupal 7 / PostgreSQL

Question: I have a Drupal 7.2 + CentOS 5.6/64 bit + PHP 5.3 + PostgreSQL 8.4.8 (servicing unix domain sockets only) web site which often goes down on peak times because of too many postmaster processes started.
On the advice from PostgreSQL mailing list I have installed pgbouncer at "port" 6432 with the following config:
[databases]
pref = host=/tmp user=pref password=XXX dbname=pref

[pgbouncer]
logfile = /var/log/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_port = 6432
unix_socket_dir = /tmp
auth_type = md5
auth_file = /var/lib/pgsql/data/global/pg_auth
pool_mode = transaction
server_check_delay = 10
max_client_conn = 200
default_pool_size = 16
log_connections = 0
log_disconnections = 0
log_pooler_errors = 1

And forced Drupal 7.2 to use it by changing  sites/default/settings.php to:
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'pref',
      'username' => 'pref',
      'password' => 'XXX',
      'host' => '/tmp',
      'port' => '6432',
      'driver' => 'pgsql',
      'prefix' => 'drupal_',
    ),
  ),
);

Here an excerpt from /var/log/pgbouncer.log during peak times:
2011-06-20 17:32:48.591 23883 LOG File descriptor limit: 1024 (H:1024), max_client_conn: 200, max fds possible: 230
2011-06-20 17:32:48.591 23883 LOG File descriptor limit: 1024 (H:1024), max_client_conn: 200, max fds possible: 230
2011-06-20 17:32:48.592 23886 LOG listening on unix:/tmp/.s.PGSQL.6432
2011-06-20 17:33:48.593 23886 LOG Stats: 36 req/s, in 3346 b/s, out 57238 b/s,query 74605 us
2011-06-20 17:34:48.593 23886 LOG Stats: 43 req/s, in 3167 b/s, out 54435 b/s,query 68969 us
2011-06-20 17:35:48.593 23886 LOG Stats: 25 req/s, in 3391 b/s, out 42060 b/s,query 95764 us
2011-06-20 17:36:48.593 23886 LOG Stats: 25 req/s, in 3370 b/s, out 103636 b/s,query 72986 us

Also I've been advised to disable persistent database connections and have done it for my own PHP scripts.
But I don't know how to do it for Drupal, what would be the best spot for that?
Thank you!
Alex
Answer: Drupal does not use persistent connections.  See https://drupal.org/node/1079892.  You may need to lower the number of web server processes (e.g. Apache MaxClients).
Comment: Thank you and I've also put pgsql.allow_persistent = Off into /etc/php.ini just to be sure
Answer: Persistent connections are not be the only issue for pgBouncer transactional mode. You need to make sure that Drupal doesn't use SET/RESET, WITH HOLD CURSOR, etc.
Actually, I see that Drupal issues SET NAMES 'UTF8', but maybe this is superfluous (so it doesn't break pooling).


How do I loop inside a file and create a new one following a template in Openwrt?

Question: I have a template for policy routing for OpenWRT and I have tons of IP's that I need to insert in this file.
Basically I have all ips I need in a file called bunchofips
And this is the template I need to follow:
config rule 'rule1'
    option dest_ip 'ipcomeshere'
    option proto 'all'
    option use_policy 'secondary'
    option sticky '1'
    option src_ip '192.168.1.1/24'

Basically where is written rule1 I need it to increase by 1 for each IP. So if I have 300 ips, the last one will be rule300. The ipcomeshere is where it should get from the file bunchofips, this file is like this:
126.96.36.199/20
126.96.36.199/22
184.108.40.206/22
188.8.131.52/24
126.96.36.199/18
[...]

So what kind of script could I have to make this new file with all this ips and to be able to run in a OpenWRT router? Is that even possible?
Thanks!
Answer: I don't know what format you want the output in (eg, single file, 300x files, pass as stdin to another process) so for the sake of this answer I'll just dump the output to a single file 'allmyconfigs'.
I'm also going to assume you want an entire line from 'bunchofips' to replace 'ipcomeshere', eg, replace 'ipcomeshere' with '126.96.36.199/20'.
For this answer we'll use a simple echo template with a couple variables to customize the output for each pass through the loop, eg:
> allmyconfigs                 # start with an empty file

counter=0

while read -r newip
do
    counter=$((counter+1))

    echo "config rule 'rule${counter}'
    option dest_ip '${newip}'
    option proto 'all'
    option use_policy 'secondary'
    option sticky '1'
    option src_ip '192.168.1.1/24'" >> allmyconfigs

done < bunchofips


From what value of $a$ the given series will be divergent?

Question: From what value of $a$ will the following series be divergent:
$$\sum_{n=0}^{\infty} \dfrac{a^{n}}{n!}$$
Comment: For none: that thing's always convergent for values in $\;\Bbb C\;$ .
Comment: Does $C$ represent set of real numbers or complex numbers?
Comment: @S Yup...but if you only want the reals it is just the very same argument mutatis mutandis.
Comment: I get it. Even though I was not after complex nums
Answer: Try D'Alembert's Ratio Test:
$$\lim_\limits{n\to\infty}\left|\frac{x_{n+1}}{x_n}\right|=\lim_\limits{n\to\infty}\left|\frac{\dfrac{a^{n+1}}{(n+1)!}}{\dfrac{a^{n}}{n!}}\right|$$
$$=\lim_\limits{n\to\infty}\left|\frac{a}{n+1}\right|=0<1$$
The series converges for all $a \in \mathbb{R}$.
Comment: @DonAntonio Ah yes! Thanks for pointing out.
Answer: Clearly the series converges for $\;a=0\;$ , and for $\;a\neq0\;$ we can use the $\;n\,-$th root test:
$$\lim_{n\to\infty}\sup\sqrt[n]{\frac{|a|^n}{n!}}=0\implies R=\infty$$
with $\;R=$ the convergence radius, so the series converges for all $\;a\in\Bbb C\;$ .
In fact, this is the series for $\;e^a\;$ ...
Answer: Let
$$u_n=\frac{a^n}{n!}.$$
Then
$$\left|\frac{u_{n+1}}{u_n} \right|=\left|\frac{a^na}{(n+1)n!}\cdot\frac{n!}{a^n}\right|=\frac{1}{n+1}|a|\to 0 \text{ as } n\to\infty$$
So, using the Ratio Test, the given series converges for all values of $a$. Therefore, no such value of $a$ the given series diverges.
Answer: This series is convergent for all $a \in \mathbb{R}$ and your sum is $e^a$, because $e^x=\displaystyle\sum_{n=0}^{\infty}\frac{x^n}{n!}$ for all $x \in \mathbb{R}$.


confused about geometric series closed formula

Question: I have found many definitions of geometric series, for a partial sum from 0 to n-1 $$\sum_{0}^{n-1} ar^{x} = a \frac{1-r^{k}}{1-r}.$$ But the context I need to use it in, requires the sum to be from 1 to n. Is there an easy way to rewrite the closed form for this?
Comment: Yes: replace a by a/r or by ar.
Answer: Answer #1: Multiply both sides by $r$ to change $a$ to $ar$, and then make the change of variables $y=x+1$ in the sum - that converts the left-hand side to what you want, while the right-hand side is multiplied by $r$.
Answer #2: It's easier to remember how geometric series identities are proved than to memorize many special cases. The denominator is always $1-r$, and to figure out what the numerator is, just multiply the series by $1-r$ and work out the resulting telescoping sum. For example,
$$
(1-r) \sum_{x=1}^n ar^x = (1-r)ar + (1-r)ar^2 + \cdots + (1-r)ar^n
$$
$$
{}= ar + (-ar^2+ar^2) + (-ar^3+ar^3) + \cdots + (-ar^n + ar^n) - ar^{n-1} = ar - ar^{n+1},
$$
and so $\sum_{x=1}^n ar^x = (ar - ar^{n+1})/(1-r) = ar \cdot (1-r^n)/(1-r)$.


How to modify path alias in Drupal 8

Question: Currently I'm on example.com/node/add page. Now I wish to add content in content type = article. What I want is, when accessing path /node/add/article, add content url should look like node/add/article?keyword='hello'
And this page still opens add node article page.
I tried changing alias at /admin/config/search/path/add
/node/add/article
to
node/add/article?keyword='hello'
But it didn't worked?
Comment: Requirement seems confusing but I guess adding a simple redirection programmatically or using a module is what you need.
Answer: One option would be to create a custom route. You might need to use a different name than /node/add/
So in a custom module add in your_module.routing.yml
article_add:
  path: /add/article/{{ keyword }}
  defaults:
    _form: '\Drupal\your_module\Form\AddArticle::AddArticleWithYourKeyword'
  requirements:
   _permission: 'administer site configuration'

And then create a Form in your_module/src/Form/AddArticle.php
<?php

namespace Drupal\your_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class AddArticle extends ControllerBase {
    public static function AddArticleWithYourKeyword($keyword) {
         //Here you can generate your form with your added keyword and return it as a render array
    }
}

This will allow you to grab a form and make edits to it, or generate an entirely custom one. In my example I made it so you pass the keyboard in the path itself not as a GET variable, but if you need you can just make the route /add/article/ and then check for GET variables inside your function.
UPDATE
Another method would be to implement the hook_form_alter function
function yourmodule_or_theme_form_node_form_alter(&$form, FormStateInterface $form_state) {
$request = \Drupal::request();
$keyword       = $request->get('keyword');
  if (in_array($form['#form_id'], ['node_article_edit_form'])) {
    $form['keyword'] = [
      '#type' => 'textfield',
      '#title' => 'keyword',
      '#default_value' => $keyword,
    ];
  }
}

Not 100% sure of the syntax but that's the general idea.
Comment: It's a very lengthy way. I think there must be an easy hack to just alter path alias patters.
Comment: Do you want to be able to do something with the keyword? You can also do a preprocess form hook and intercept the GET variable and add that value to the form before rendering it.
Comment: Thanks for your reply. Actually I have nothing to do with form, node/add/article form will remain unaffected, only I have to change its alias pattern, something like node/add/article?keyword=xyz.
Comment: I'm not sure I understand. Do you want node/add/article?keyword=xyz to go to the same page as node/add/article? Because that will already occur. Or do you need it so you have to put in the keyword to visit the form? Or do you want to change what page node/add/article?keyword=xyz leads to, and make it so node/add/article?keyword=xyz goes to a different page than node/add/article?
Comment: yes I want node/add/article?keyword=xyz to go to the same page as node/add/article
Comment: Is that not already happening? node/add/article?keyword=xyz should be going to node/add/article already. If that's not the case what is node/add/article?keyword=xyz bringing you instead?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/65260/discussion-between-sugandh-khanna-and-matt).
Comment: That isn't changing the alias pattern, that is just a query string. If the query string does not affect the node form in any way, what is the point of adding code? These are not aliases either - they are system routes.
Comment: @Kevin I was confused as well. It turns out what he needed was the link on the actual admin Add Content page to link to /node/add/article?keyword=xyz instead of it linking to /node/add/article

How to modify path alias in Drupal 8


Atualização manual da Versão PHP

Question: Desenvolvi scripts em PHP compatíveis com a versão mínima 5.3.7, e para minha infelicidade, a versão que está instalada no servidor Apache é 5.2.17.
Como posso manualmente subir a nova versão PHP via ftp para atualizar?
Pesquisei algumas coisas do tipo:

Pode ser feito através de um arquivo .htaccess, que deve ficar na pasta onde possuo meus scripts, informando ao servidor que naquela pasta será executa a versão especificada do PHP.
AddHandler php53-script .php .php5 .php56 .pht .phtm .phtml
suPHP_ConfigPath /home/user/public_html/quero_que_seja_executada_a_nova_versão_nesta_pasta

o problema disso é o arquivo php.ini, que não sei se posso indicar para ler o meu, e não o do servidor.

Pode ser feito criando um Apache Handler direto co cPanel
Há quem diga que não têm como, pois é exclusivamente feito no servidor na pasta bin do Apache

Alguém sabe como, ou pelo menos me ilumine, com alguma forma onde  posso fazer isso?
Comment: Minha sugestão está mais em mudar a hospedagem se possível, ou entrar em contato com o suporte para eles atualizarem.
Comment: Renan você terá que entrar em contato com o seu provedor de hospedagem. Não é possível subir o executável do PHP via FTP e rodar sua aplicação por ele até onde sei.
Comment: Vc ta usando que tipo de OS no servidor? Windows, Debian? Se o hospedag e do tipo "shared hosting" vc não pode. Vc pode somente se vc tem um servido "dedicado". Tem tambem uma outro pergunta: tem quasi nunca diferencia entre PHP 5.2 e 5.3. Que tipo de coisa vc faz, que não funciona sobre PHP5.2??
Comment: Nota: o PHP 5.3 já não é mais suportado e as versões mais novas tem um desempenho superior a 5.3. Recomendo a atualização para uma versão mais recente.
Comment: @Peter entre o 5.2 e 5.3 temos o suporte a namespaces. Só isso já acho o suficuente.
Comment: Se e isso, então: http://stackoverflow.com/questions/6473126/namespaces-in-php-5-2  Mas não sei se vai resolver.
Comment: Se o servidor não é seu, você não pode, se for uma hospedagem eu acho que o seu servidor deve ter algo semelhante ao Cpanel, lá você pode escolher a versão do PHP (geralmente tem mais de uma instalada), na hospedagem de um cliente eu tenho 5.2, 5.3, 5.4 e 5.5; eu alterno quando quiser.
Comment: é que eu realmente preciso dessa versão mais atual pois estou usando funções de hashing de senha, sem falar que me exibiu um erro:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/fenix/public_html/login/admin/index.php:4) in /home/fenix/public_html/login/admin/classes/Login.php on line 40
Answer: Se é possível ou não utilizar seu php.ini personalizado depende das configurações do apache.
Basta você colocar na raiz do seu site, se funcionar é por que é possível (:
O arquivo .htaccess já é limitado pela pasta onde ele esta. Então você não precisa da segunda linha do código que colou. No entanto mudar a versão só será possível caso seu serviço de hospedagem tenha a versão que você esta tentando usar disponível.
Quanto ao erro que você reportou nos comentários, é possível que o erro exista no seu ambiente de desenvolvimento, ele só aparece no ambiente de produção devido à diretiva error_reporting.
Você pode suprimir os erros usando uma função php mesmo:
error_reporting(E_ERROR);

No entanto é recomendado que você configure seu ambiente de desenvolvimento para mostrar todos os erros, e verifique e corrija os erros ao invés de simplesmente escodê-los.
Por exemplo o erro que você postou nos comentários é geralmente causado por espaço em branco e ou qualquer outro tipo de texto/html, funções como echo e print utilizadas antes da função header.
Se você tem arquivos .php que não contêm html/texto é indicado que você não feche a tag php.
Ex.:
<?php
   function util(){
     //fazalgo
   };
//fim do arquivo sem fechar php porque não tem html depois

Comment: obrigado a todos. realmente tive que entrar em contato com a hospedagem para eles fazerem tudo por lá.

Atualização manual da Versão PHP


How do musicians synchronize with the playback keyboards/ambience when live?

Question: Lots of times musicians especially in rock and metal bands, when performing live, they play over pre-recorded tracks that include keyboards/orchestras ambience or other effects. They always seem to be in perfect tempo with them. How do they synchronize? Do they use some kind of metronome in their earphones so that they will be in the same tempo as the tracks or is there something else?
I'm sure they are not just listening to the track and playing on top of it because sometimes it is playing in the middle of the song and if they have started at a different tempo they would have to change their tempo to fit in it.
Comment: The easiest solution is just record everything and mime to it, of course. Most of the audience won't notice!
Answer: The drummer usually has a click (and the track) in his (in-ear) monitor. The rest of the band can choose if they want the additional track in their monitors or not. As long as they can hear the drummer they'll be in sync with the track.
Answer: Yes, as Matt L. said - it's a "click track" sent to the drummer's headphones; the rest of the band simply hears the drums in most cases and follows that.
If you need to do this, a solution I came up with that worked great for us was this (keep in mind, this will only send a MONO signal to the PA system / Front-of-House mixer but that's normally OK since you probably don't want stereo in this case anyway (or people on the left side of the room won't hear stuff on the right speaker as well, and vice versa):
Record the 'background music' on ONLY the Left side.
Record the click track (a rim shot in my case) ONLY on the Right side.  (make sure you have an obvious 'count down' before the drummer should start playing).
Take the output of your playback device and send the Left side to the PA and the right side to the drummer.
We did this using a little MP3 player that the drummer controlled, running into a mini-mixer so that he had only the click in both sides of his headphones.
Buy a 'Y-Cable' that goes from mini-jack 1/8th inch (or whatever your playback device needs) to two 1/4" cables.  Put those in separate mixer channels on the mini-mixer.  The music on track 1 was sent out of the "FX Send" to the PA (it's volume fader was all the way down).  The click was sent to track 2 and the drummer just plugged his phones into the mixer (thus getting the click in both sides of his phones and having a volume control handy without hearing the music).
Hope this helps you or someone else out there!


What is more "Pythonic" - dict comprehsion with list generator, or an explicit for loop?

Question: Suppose I have a function with input 'raw_data'
raw_data consists of lines such as:
key1: str1
key2: str2
...

Where strx is of the form aa:bb:cc:dd... - that is a ':' separated string
There is a helper function which does something to the strings, converting them to values, let's call it get_value()
What would be the most pythonic way to return a dict?
to_dict(raw_data):
  list_data = raw_data.splitlines()
  return { key.replace(':',''): get_value(str) for key,str in (line.split() for line in list_data)}

or
to_dict(raw_data):
  list_data = raw_data.splitlines()
  mydict = {}
  for line in list_data:
    key,str = line.split()
    key = key.replace(':', '')
    mydict.update({ key: get_value(str)})
  return mydict

Or is there some much more pythonic way of doing this?
I'm aware this might seem opinion based question, but there seems to be a consensus about what is 'more pythonic' or 'less pythonic' way  of doing things, I just don't know what the consensus is in this case.
Comment: the dictionary case is the pythonic way to go.
Answer: How about:
{k:v for l in raw_data.splitlines() for (k,v) in [l.split(":")]}

Comment: You have your loops backwards.  They execute from left to right.
Comment: I'm sorry, forgot to mention the strings have ':'s in them, updated the question to reflect this
Comment: Thanks Patrick, yes you're quite right - have edited to correct accordingly - I also noticed I had to wrap the `l.split(":")` component in list brackets to avoid the `ValueError: not enough values to unpack (expected 2, got 1)` error I was getting when trying to fill (k,v) from the split contents. I'll confess, I'm not entirely sure why that's necessary, but it looks as though it is in this case.
Answer: Your first expression is more "Pythonic".  If you're worried about readablity, you can take the generator expression out onto its own line.
def to_dict(raw_data):
    data = (line.split(': ', 1) for line in raw_data.splitlines())
    return {key: get_value(st) for key, st in data}

line.split(': ', 1) will split line on only the first ": ", so "a: b: c" becomes ['a', 'b: c']
Comment: dict should be key: value, but otherwise this answer works great for me, thanks.
Answer: List Comprehension is really a handy and faster way to write for loops in Python in just a single line of code. The idea of comprehension is not just unique to lists in Python. Dictionaries, one of the commonly used data structures in data science, can also do comprehension. This is called dict comprehension or dictionary comprehension.
Remember that, in python a list is defined with square brackets [] and a dictionary is defined with curly braces {}. The same idea is carried over in defining dict comprehension as well. dict comprehension is defined with a similar syntax, but with a key:value pair in expression.


Simple Bayesian probability question

Question: Assume that I evaluate the probability that a murder suspect is guilty to 10%. Then I find a blood trace at the scene and only 1% of the population has this blood type. The suspect has this blood type and the test is accurate (say 100% accuracy for simplicity). What is now the probability that the suspect is guilty?
posterior = prior x likelihood / normalization = .1 x 1 / .01 = 10
What am I missing here?
Answer: Short answer: The denominator is missing a term. It's missing the "innocent and evidence" bit which is .009
Long answer:
You want to calculate the probability of guilty given that we have the evidence of the rare blood type. Assuming that if someone is guilty, we are always going to find his blood type as evidence then:
$P(Guilty|Evidence) = \frac{P(Evidence|Guilty)  P(Guilty)}{P(Evidence)}$
$P(Guilty|Evidence) = \frac{P(Evidence|Guilty)  P(Guilty)}{P(Guilty)P(Evidence|Guilty) + P(NotGuilty)P(Evidence|NotGuilty)}$
$P(Guilty|Evidence) = \frac{1 \times 0.10}{0.10 \times 1 + 0.90 \times  0.01}$
$P(Guilty|Evidence) = 0.917$
Comment: To answer your first question, the answer is yes. The probability above will always remain the same, no matter how many people are in the region. In the second part, you are imposing a new question and introducing additional information. The additional information is that there can be only one killer (it wasn't stated before) and the new question for modelling becomes P(he is the only killer | his blood type matches & n = n0). n0 can be 100 or 10000 but in the case of n0 = 100 your intuition will be completely right! the resulted probability will be higher compared to the case of n0 = 10000
Comment: Can P(Guilty|Evidence) in this scenario be constant? I cant get my head around it: I would expect P(G|E) to be big if there are very few people within the range of the crime (lets say 100 people, so there would be only 1 with the given blood-type) and i would expect it to be rather smale if there are lots of people in range?
Comment: Not sure I 100% understand what you mean by constant but strictly speaking, the only way to have P(Guilty|Evidence) constant is to never update it no matter how much more evidence you collect! Essentially, that would make the P(Guilty|Evidence)=P(Guilty) and in this example you'll always have the prior 10% probability. We basically make use of the Bayes' rule to incorporate data to our prior beliefs and update it if in the future we get more data
Comment: Thanks for your reply. Lets say scenario1 has 100 People in the region (we would expect 1 to have bloodtype b1) and scenario2 has 10000 people in the region (we would expect 100 to have bloodtype b1). Is it possible that for both scenarious P(Guilty|Evidence) is the same value? In scenario1 the person we are suspecting might be pretty much the only one with bloodtype b1, so i would expect the 10% to raise. In scenario2 he is just one of 100 with bloodtype b1, which shouldn't raise the 10% that much?
Answer: You're calculating the posterior probability of a particular suspect being guilty, not a random person from the general population being guilty. Therefore, the normalisation term is not the probability of someone in the general population having the blood type, it's the probability of the suspect having that blood type given the prior probability that they're guilty. Since they must have the blood type if they're guilty, this is equal to
$$\begin{align*}
\mathbb{P}(\textrm{suspect has blood type}) =& \mathbb{P}(\textrm{suspect guilty})\\
&+ \mathbb{P}(\textrm{suspect innocent}) \mathbb{P}(\textrm{suspect has blood type if innocent})\\
=& 0.1 + 0.9 \times 0.01\\
=& 0.109,
\end{align*}$$
which leads to a valid posterior probability.

Simple Bayesian probability question


Omega Theme, change content zone when sidebar had no content

Question: I'm using Omega as Base theme. In the content zone I have 2 regions:

'Content region' set as 9 columns
'Right column region' set as 3 columns

Is it possible to have a "flexible region"? I want to change the column count when the right column region is empty.
Answer: Yes, it is possible to change the column count for a region if another region is empty.

Go to the layout configuration of the Omega 3 Subtheme
Go to the zone that's the parent of the specific region
Set "Primary Region" to the region you want to give a flexible column count


P-value versus Exp(B) value in Cox regression analysis

Question: I performed Cox regression analysis for two Biomarkers.  Both were significant (p<0.05).
Biomarker 1 showed higher significance but lower Exp(B)=hazard ratio value than Biomarker 2 (see below).
Biomarker 1: HR=3.06; 95%CI=1.71-5.48; p<0.001 (sorry, SPSS doesn't show more than 3 decimals)
Biomarker 2: HR=6.05; 95%CI=1.67-21.86; p=0.006
Which of the two Biomarkers is a better (stronger) predictor? In other words: what counts more - the P-value or the Exp(B) value?
Comment: Are we talking continuous biomarkers or dichotomoizations (e.g. biomarker #1 > threshold X)? You may have the problem that one dichotomization is a stronger predictor, but another classifies more patients as at risk (so it depends all a bit on your criterion for better).

There may be considerable uncertainty around the size of the regression coefficient so simply comparing the regression coefficients is problematic for really concluding which is better. For the same reason comparing the random p-values is problematic.

Perhaps you could look at the C-index (including confidence intervals).
Comment: The biomarkers are dichotomic (low and high expression)
Comment: But I will look at the C-Index as well. Thanks!
Answer: The two statistics that you mention (p values and hazard ratios) ask different questions, so it is not surprising that they give different answers.
The p-value asks:

If, in the population from which this sample was randomly drawn, the
  null hypothesis was correct (i.e. B = 1), what is the probability of
  getting a test statistic (B) at least as extreme as the one we got in
  a sample the size of the one we have.

The hazard ratio asks:

How different are the hazards of dying for the two groups?

Opinions of p-values vary (to put it mildly!).  My own view is that the question they answer is rarely the one we want to ask.
Comment: If I understand correctly, you favor the hazard ratio over the p-value?
Perhaps it helps to have the exact values in this particular case (see below)
Comment: Biomarker 1: HR=3.06; 95%CI=1.71-5.48; p<0.001 (sorry, SPSS doesn't show more than 3 decimals)
Biomarker 2: HR=6.05; 95%CI=1.67-21.86; p=0.006
Comment: 1. Yes, I favor hazard ratios over p-values.  2. The wide CI on the second biomarker is a bit worrying and is the reason that it has a higher HR with a less sig. result.   3. both p are very sig., and I believe estimates of p values that are very low are not always that accurate (but I'm not sure of that)
Answer: Unfortunately, in terms of predictive power, you cannot tell from this output alone.
While the fact that Biomarker 2 has a larger estimated HR may lead you to believe it is better, this is incorrect reasoning. The reason for this is that this simple output alone tells you nothing about the distribution of Biomarker 2. To help think about this, consider if we measured the biomarker on a different scale, such that the new values were 10x the current values. Then the fit would be exactly the same, expect that the estimated log-hazard ratio would be 1/10 it's current estimate, despite having the exact same predictive power. So simply looking at estimated coefficients cannot tell you the predictive power of a given biomarker.
The most straight forward way to compare them is to look at an ROC curve.
In addition, is there any reason why you wouldn't use both biomarkers? Given that they were both significant in your model, it would suggest that you should get better predictions by using both biomarkers. But perhaps this is unreasonable due to costs of the two tests?
It's worth noting that @PeterFolm's answer above, I believe there is an unstated, but very important, assumption that the covariates are standardized (i.e. all have standard deviation 1). In that case, comparing regression effect sizes is more meaningful. In addition, it's important to note that just because the covariates are binary doesn't mean that they are standardized!


How can one solve this differential equation?

Question: We're give the following differential equation:
$$mx''(t)+kx(t)=f(t)$$where $m$ and $k$ are constants and $f(t)$ is a periodic function of period $2L$.
$\textbf{My attempt:}$
First, I solved the homogeneous differential equation
$$mx''(t)+kx(t)=0$$
and got the familiar solution
$$x_c(t)=A\cos\bigg(\sqrt{\dfrac{k}{m}}t\bigg)+B\sin\bigg(\sqrt{\dfrac{k}{m}}t\bigg)$$
Then I went to find the particular solution, and since the only given about $f(t)$ is its periodicity, it seemed I have to use Fourier series.
The Fourier expansion of $f(t)$ is
$$f(t)=\sum_{n=-\infty}^{+\infty}c_ne^{jn\dfrac{\pi}{L}t}$$
where $j\equiv\sqrt{-1}$ and $c_n$ is a function of $n$. Thus the particular solution has to be of the form
$$x_p(t)=\sum_{n=-\infty}^{+\infty}b_ne^{jn\dfrac{\pi}{L}t}$$
where $b_n$ is some other function of $n$.
Calculating the derivatives, then substituting in the equation and solving for $b_n$ I got
$$b_n=\dfrac{c_n}{k-m\Big(\dfrac{n\pi}{L}\Big)^2}.$$
This solution is okay as long as denominator is different from zero for all $n$. However, if $\sqrt{\dfrac{k}{m}}$ is a multiple of $\dfrac{\pi}{L}$, then there will be some $n$ that will set the denominator to zero, and the particular solution will cease to exist. How to solve the equation in this case?
I tried hard but I couldn't.
Comment: Then you'll have a _resonance solution_ looking like $t\cdot\cos t$ or something.
Comment: We only get this solution if $f(t)$ was sinusoidal, not any periodic function.
Comment: The general solution is $x(t)=\cos(\sqrt{\frac{k}{m}}t)x(0)+\sqrt{\frac{m}{k}}\sin(\sqrt{\frac{k}{m}}t) x'(0)+\frac{1}{\sqrt{mk}}\int_0^t{\sin\left(\sqrt{\frac{k}{m}}(t-s)\right)f(s)ds }$. You need the specific form of $f$ in order to calculate the integral.
Comment: @CTNT Great, can you refer me to the full solution please?
Comment: If $f$ is any periodic function, go expand it to Fourier series and do what you are already doing. All terms will be fine, except maybe one. I told you what to do with that one. Alternatively, do as **CTNT** says. It must end up the same.
Comment: This is a linear system of the form $\dot{y}=Ay+bf(t)$ with state vector $y=[x, x']^T$, $A=\left[\matrix{0 & 1\\-k/m & 0}\right]$ and $b=[0, 1/m]^T$. The solution of this system is $y(t)=e^{At}y(0)+\int_0^t{e^{A(t-s)}bf(s)ds}$. Replacing $e^{At}=\left[\matrix{\cos\left(\sqrt{\frac{k}{m}}t\right) & \sqrt{\frac{m}{k}}\sin\left(\sqrt{\frac{k}{m}}t\right) \\ - \sqrt{\frac{k}{m}}\sin\left(\sqrt{\frac{k}{m}}t\right)  &  \cos\left(\sqrt{\frac{k}{m}}t\right)}\right]$ the response of $x$ is obtained.
Answer: There is a solution for the case where $\sqrt{k/m}=N\pi/L$ for some integer $N$ iff $f$ is orthogonal in the $L^2$ sense to the homogeneous solutions $\sin(\sqrt{k/m}t)$, $\cos(\sqrt{k/m}t)$. You can see that this is necessary because $mx''+kx$ annihilates these elements. But it's also sufficient, which you can see by constructing the solution using the Fourier series.


How to recognize a geometric sequence while solving by unfolding?

Question: I have a problem with how this is written as a geometric sequence. I got this screenshot from my math book. $r$ should be $2$ and $a$ should be $1$.
$$S = \frac{1 - 2^{n-1}}{1 - 2}$$
How did they come up with $n$ as the power of $2$? And why is the sum being written backwards?
\begin{align*}
a_n & = 5 + 5(2) + 5(2^2) + 5(2^3) + \cdots + 5(2^{n - 1}) + 2^na_0\\
    & = 5(1 + 2 + 2^2 + \cdots + 2^{n - 1}) + 2^n(2)\\
    & = 5 \frac{2^n - 1}{2 - 1} + 2(2^n)
\end{align*}
Comment: Welcome to MathSE.  Please type your question rather than posting an image since images cannot be searched and users with screen readers may not be able to read them.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: The geometric series to which the formula is being applied is $5 + 5(2) + 5(2^2) + 5(2^3) + \cdots + 5(2^{n - 1})$.  The final term is based on information that you did not include in your question.
Comment: @N.F.Taussig I get that. Read my question please. How did they get 2^n instead of 2^(n-1)? And why is it 2-1 instead of 1-2 in the denominator?
Answer: The sum of the first $n$ terms of a geometric sequence with initial term $a_1$ and common ratio $r$ is
$$S = \sum_{k = 1}^{n} a_1r^{k - 1} = a_1 + a_1r + a_1r^2 + \cdots + a_1r^{n - 1} \tag{1}$$
If we multiply this sum by $r$, we obtain
$$rS = \sum_{k = 1}^{n} a_1r^k = a_1r + a_1r^2 + a_1r^3 + \cdots + a_1r^n \tag{2}$$
Subtracting equation 2 from equation 1 yields
\begin{alignat*}{6}
S - rS & = a_1 & + a_1r & + a_1r^2 & + \cdots & + a_1r^{n - 1} & \\
       & =     & - a_1r & - a_1r^2 & - \cdots & - a_1r^{n - 1} & - a_1r^n\\ \hline
S(1 - r) & = a_1 & & & & & - a_1r^n
\end{alignat*}
If $r \neq 1$, we may divide by $1 - r$ to obtain the formula for a geometric series
$$S = \frac{a_1 - a_1r^n}{1 - r} = a_1\frac{1 - r^n}{1 - r} \tag{3}$$
In your problem, the geometric series is
$$5 + 5(2) + 5(2^2) + 5(2^3) + \cdots + 5(2^{n - 1}) = \sum_{k = 1}^{n} 5(2^{k - 1})$$
so $a_1 = 5$ and $r = 2$.  Using the formula in equation 3, we obtain
$$S = 5 + 5(2) + 5(2^2) + 5(2^3) + \cdots + 5(2^{n - 1}) = 5 \cdot \frac{1 - 2^n}{1 - 2}$$
If we multiply the numerator and denominator of the fraction
$$\frac{1 - 2^n}{1 - 2}$$
by $-1$, we obtain
$$\frac{1 - 2^n}{1 - 2} \cdot \frac{-1}{-1} = \frac{-1 + 2^n}{-1 + 2} = \frac{2^n - 1}{2 - 1}$$
Therefore,
$$S = 5 + 5(2) + 5(2^2) + 5(2^3) + \cdots + 5(2^{n - 1}) =  5 \cdot \frac{1 - 2^n}{1 - 2} = 5 \cdot \frac{2^n - 1}{2 - 1}$$
as the author claims.
Comment: We are getting the geometric sum until (n-1), why are you writing the formula as if we are going all the way until n? Shouldn't it be 5 * (1-2^(n-1))/(1-2)
Comment: Your first equation indicates you're getting the sum until n but your last term is n-1
Comment: Notice that there are $n$ terms in the sum $5 + 5(2) + 5(3) + \cdots + 5(2^{n - 1})$.  The last term has exponent $n - 1$ since the formula for $a_k$ is $a_k = a_1r^{k - 1}$, so when we substitute $n$ for $k$, we obtain $a_1r^{n - 1}$. Our formula for $$S = \sum_{k = 1} a_1r^{k - 1} = a_1 + a_1r + a_1r^n + \cdots + a_1r^{n - 1}$$ is $$S = a_1\frac{1 - r^n}{1 - r}$$  Please compare equations 1 and 3.
Answer: Note that for $r\neq 1$, we have
$$1+r+...+r^{n-1}=\frac{(1+r+...+r^{n-1})(1-r)}{(1-r)}=\frac{1-r^n}{1-r}=\frac{r^n-1}{r-1}.$$
Yours is the case $r=2$. Convince yourself of the second equality by distributing and cancelling intermediate terms. The final equality is just multiplying top and bottom by $-1$.