Converter os argumentos da função para string

Question: Como converter os argumentos da função para string? Sem ter que digitar todos os argumentos
Tentei resolver da seguinte forma:
def teste(a, b, c, d, e='F9', f=1):
    for key, value in locals().items():
        key = str(value)
    message = ' '.join(['inicio', a, c, d, e, f, b])
    return message

t = teste('C6', 1, 2000, 'E4')
print(t)

Porém key no dicionário não é uma variável da função teste(), então o valor de value convertido para string não é passado para a variável.
A solução encontrada foi de converter para string todas as variáveis, digitando o nome de cada variável:
def teste(a, b, c, d, e='F9', f=1):
    message = ' '.join(str(x) for x in ['inicio', a, c, d, e, f, b])
    return message

t = teste('C6', 1, 2000, 'E4')
print(t)

Mas como realizar isso sem precisar digitar cada variável, como por exemplo com a utilização de locals()?
Comment: [Relacionada](https://pt.stackoverflow.com/q/23628/75104)
Answer: Se você não tem necessidade de distinguir entre os argumentos, você pode usar o recurso do * na declaração dos parâmetros de uma função - isso indica que a função indica um número variável de argumentos anônimos que já é passado para a função como uma tupla - e aí, é simples converter todos:
def teste(*args):
   return ' '.join(str(arg) for arg in args)

teste(1, 2, 3, 4, 5, 6)

Se alguns dos seus parâmetros precisam de nome, você pode usar ** para receber os parâmetros como um dicionário -
def teste(*args, **kw):
   return ' '.join(str(arg) for arg in (args + tuple(kw.values()) ) )

teste(1, 2, 3, 4, 5, 6, alo=7, mundo=8)

Se você precisa ter valores padrão nos parâmetros, como está no seu exemplo, aí não tem jeito, ou você vai ter que digitar os nomes por extenso, ou usar uma combinação de técnicas de introspecção como o que está tentando fazer para iterar sobre os nomes das variáveis. Não vejo como isso poderia ser uma boa prática - um nome de variável é importante e faz algo independente no seu programa, ou, se você fosse ter várias variáveis que vai tratar do mesmo jeito, é melhor colocar esses valores numa lista ou dicionário.
Se você precisar fazer isso em várias funções, seria bem errado ter que replicar essa lógica em todas - o ideal aí é usar um decorador que transforma os tipos dos parâmetros quando a função é chamada - e você já fornece tudo transformado em string para sua função.
O uso de um decorador inclusive permite que seus parâmetros tenham nome na função final (e o decorador consome argumentos genéricos usando "*" e "**"). Só não dá mesmo conta de argumentos padrão - esses não são passados para o decorador.
def tudo_string(func):
    def decorador(*args, **kwargs):
         args = [str(arg) for arg in args]
         kwargs = {key: str(value) for key, value in kwargs.items()}
         return func(*args, **kwargs)
    return decorador

@tudo_string
def teste(a, b, c, d, e='F9', f=1):
    # Todos os parâmetros serão recebidos já convertidos em string aqui,
    # exceto o valor padrão de f que é dado "dentro" do decorador.
    ...


What fractions can fill a $N$ by $N$ matrix given that their sum is always 2?

Question: My problem is the following: I have a matrix $N$ by $N$ in size. I want to fill it with fractions of $1$ of increasing denominator in relation to their distance from the center of the matrix. The central value is always $1$.
$N$ is always odd.
Example for $N = 3$:
1/12, 1/ 6, 1/12

1/ 6, 1   , 1/ 6

1/12, 1/ 6, 1/12

Proof:
$1/12 * 4 + 1/6 * 4 + 1 = 2$
But what would be the formulaic approach for a, say, $5*5$ matrix?
Comment: @KappaG3 Just to make sure I understand the question correctly, would the $5 \times 5$ matrix look something like [this pattern](http://pastebin.com/raw/V78ghBD4)?
Comment: Do all entries the same distance from the center have the same value?
Comment: Or perhaps not, considering that the square root of two would be involved. Consider b, for example.
Comment: what are the restrictions on the matrix? Symmetry? Arithmic sequence?
Comment: Ah, I'm sorry, but I don't speak math very well. The values inside the matrix have to be spread out according to their distance from the centre, and their sum (excluding the central value) must always equal 1.
Comment: Can $N$ be even?  If so, what counts as the "center"?
Comment: No, $N$ cannot be even. To give a concrete example, the matrix is strictly correlated to a list of neighbours in a cellular automata, so there is always a central value. Again, sorry if I'm being vague.
Comment: A simple edit, adding "where $N$ is odd" to the first sentence will help.  Also, in your example, the numerators are all $1$.  Is that important, or just happenstance?
Comment: Yes, I've edited the original question. Also yes, the numerators are all 1.
Comment: Yes, @NobleMushtak! You hit the nail on the head. I'm sure it's a fairly simple problem to solve, but my wording must be atrocious.
Comment: @martycohen exactly, like in a circle.
Answer: This is not an answer, just an attempt to nail down what the OP is looking for in the $N=5$ case.  It sounds like the OP wants a matrix of the form
$$\pmatrix{{1\over e}&{1\over d}&{1\over c}&{1\over d}&{1\over e}\\
{1\over d}&{1\over b}&{1\over a}&{1\over b}&{1\over d}\\
{1\over c}&{1\over a}&1&{1\over a}&{1\over c}\\
{1\over d}&{1\over b}&{1\over a}&{1\over b}&{1\over d}\\
{1\over e}&{1\over d}&{1\over c}&{1\over d}&{1\over e}\\}$$
with positive integers $a\lt b\lt c\lt d\lt e$ such that
$$1+{4\over a}+{4\over b}+{4\over c}+{8\over d}+{4\over e}=2$$
I'm making this community wiki. so if I've misinterpreted, feel free to edit.
Comment: I am using taxicab distance in my answer, so my matrix looks like:
$$\left[\begin{matrix}\frac 1 d \ \frac 1 c \ \frac 1 b \ \frac 1 c \ \frac 1 d \\ \frac 1 c \ \frac 1 b \ \frac 1 a \ \frac 1 b \ \frac 1 c \\ \frac 1 b \ \frac 1 a \ 1 \ \frac 1 a \ \frac 1 b \\ \frac 1 c \ \frac 1 b \ \frac 1 a \ \frac 1 b \ \frac 1 c \\ \frac 1 d \ \frac 1 c \ \frac 1 b \ \frac 1 c \ \frac 1 d\end{matrix}\right]$$
Comment: @KappaG3, if you mean Noble Mushtak's pattern instead of mine, please say so.  (Note, if you don't require the denominators to be *strictly* increasing, i.e., $a\le b\le c\le d\le e$, then Noble Mushtak's pattern is a subset of mine.)
Comment: Looks right to me! Thank you so much for putting into words what I could not.
Comment: To explain a little more: Each particle in my system has a value, which we may call "energy". Whenever a function is applied to this particle, it gains a certain amount of energy from its neighbours. The matrix represents the factors of this function for each neighbor. Closer neighbours have to concede more energy than distant neighbours, but the sum of these factors minus the central one (which isn't even considered, actually) must equal 1 because the particle must draw exactly 1 * f(...) energy from its neighbours.
Comment: No, I *think* that your pattern is what I'm looking for, because I'm assuming that Euclidean distance is what I need. However, I'm sure that both solutions would work once found - only slightly differently.
Comment: I swapped $b$ and $c$ because $c$ is closer to the origin than $b$.
Comment: @Rahul, nice point.  As it happens, it makes no difference for the equation that comes out of it.  BTW, by fiddling around, I found one solution:  $(a,b,c,d,e)=(6,18,54,288,432)$.
Answer: Let's say we have a $2n+1 \times 2n+1$ matrix $A$ with a $1$ in the center, which is $A_{n+1,n+1}$, and $\frac{1}{d\cdot \text{taxicab}(x,y,n+1,n+1)}$ for $A_{x,y}$ for any cell that is not the center. We want all of this to sum to $2$, so without the $1$ in the center, we want the elements to sum to $1$.
In Python, this means:
from fractions import Fraction
def taxicab(a,b,c,d): return abs(a-c)+abs(b-d)
# Set this to any non-negative integer you want:
n = 2
# We need to sum x,y from 1 to 2n+1, inclusive on both ends, which is range(1, 2n+2) in Python
sum([Fraction(1, d*taxicab(x,y,n+1,n+1)) for x in range(1, 2*n+2) for y in range(1, 2*n+2) if (x, y) != (n+1, n+1)]) == 1

All of the terms in the sum have a $\frac{1}{d}$ in them, so we can factor out that $\frac 1 d$ and then multiply both sides by $d$ to get $d$ on the right side. Now, switch both sides of the equation to get:
d = sum([Fraction(1, taxicab(x,y,n+1,n+1)) for x in range(1, 2*n+2) for y in range(1, 2*n+2) if (x, y) != (n+1, n+1)])

And then, we can print out the matrix:
# This prints out d:
print("d =", d)
# This prints out the matrix:
for x in range(1, 2*n+2):
    for y in range(1, 2*n+2):
        # Assume that it's the center and our element is 1:
        this_element = "1"
        # If it's not the center, then change the element accordingly:
        if (x, y) != (n+1, n+1):
            this_element = str(Fraction(1, d*taxicab(x,y,n+1,n+1)))
        print(this_element, end="")
        # For formatting:
        for i in range(10-len(this_element)): print(end=" ")
    # For formatting:
    print("")

For example, for $n=5$, we get $d=\frac{35}{3}$, giving us:
$$\left[\begin{matrix}\frac{3}{140} \ \frac{1}{35} \ \frac{3}{70} \ \frac{1}{35} \ \frac{3}{140} \\ \frac{1}{35} \ \frac{3}{70} \frac{3}{35} \ \frac{3}{70} \ \frac{1}{35} \\ \frac{3}{70} \ \frac{3}{35} \ 1 \ \frac{3}{35} \ \frac{3}{70} \\ \frac{1}{35} \ \frac{3}{70} \frac{3}{35} \ \frac{3}{70} \ \frac{1}{35} \\ \frac{3}{140} \ \frac{1}{35} \ \frac{3}{70} \ \frac{1}{35} \ \frac{3}{140}\end{matrix}\right]$$
Comment: Unfortunately, I am busy right now, so I can't make the algorithm now, but I will try to solve this problem when I have time and if I do, I will edit my answer to post the algorithm in this answer. However, if someone else comes up with an algorithm before I do, then I probably won't try to make my own algorithm.
Comment: @KappaG3 Do you want the answer to be in the form of $\frac 1 {d\cdot \text{taxicab}(x,y,0,0)}$, where $\text{taxicab}(x,y,0,0)=\lvert x \rvert+\lvert y \rvert$? That would make this a lot easier.
Comment: @NobleMushtak Yep, that'll do! I found some values earlier by doing a summation of `1 / taxicab(x, y, 0, 0)` and then dividing again by that value. However, I wouldn't know where $d$ came from without the summation.
Comment: @KappaG3 I have edited my answer with a Python script in it. That can find $d$ given $n$ where $2n+1$ is the side of the matrix. Is this sufficient for your purposes?
Comment: @BarryCipra Thank you again for the catch! My script also outputs $\frac 3 {70}$, so it is not a problem with my script, just with how I copied it down.
Comment: @NobleMushtak, glad to help.  I hope the OP will clarify what kind of answer they are looking for.  Your inversely-proportional-to-the-taxicab-distance interpretation is very nice, and certainly simpler than the egyptian-fractionesque interpretation I posted on the community wiki.


what does "layout-compatible with C" mean?

Question: It is said that stl vector is "layout-compatible with C".
Where can I find the definition of "layout-compatible with C"?
Answer: This means that, as long as the vector is not empty, <code>&vector.front()</code> will give you a pointer to a contiguous array of objects, which could be passed to a C API that expects such an array.
Answer: It means that the contents of the vector will be laid out in memory the same way they would be in a C array of the same type. That means that if you have a C function that expects to receive a pointer to an array of some type, you can use a vector and pass the function a pointer to the first element of the vector.


A geodesic which stop minimizing must self intersect?

Question: Let $M$ be a complete* Riemannian manifold.
Let $\gamma$ be a geodesic which stops minimizing at some point.
Is it true that $\gamma$ must be periodic or self-intersect? (in a transversal way)
I suspect it's false, but I could not find an example.

*For non complete manifolds it's certainly false (Look at $\mathbb{S}^2 \setminus \{p\}$)
Comment: A non-circular helix on a cylinder is not globally minimizing, but does not self-intersect. (This is, of course, John Ma's example lifted to a covering.)
Answer: Let $M =\{ (e^{it}, e^{is}) : s, t\in \mathbb R\}$ be the torus with Euclidean metric. Let
$$\gamma (t) = (e^{it}, e^{i\sqrt 2 t}).$$
This geodesic never intersect itself. Note also that every geodesics on a compact manifold must stops minimizing at some points.
Comment: You can take the above example with the product with $\mathbb R$. @AsafShachar
Comment: You mean the flat torus, right?
Comment: Yes ${}{}{}{}$ @AsafShachar
Comment: Thanks. Actually I knew about the dense curve on the Torus, but somehow I didn't think of it as a geodeisc. Do you have an example on a non-compact manifold?


Converting between different accuracy/error metrics

Question: I am trying to compare model accuracy between several different measurement metrics. For example, some citations use accuracy while other use error. That one is rather obvious, but there are lots of different metrics and I am not entirely sure how to compare some of them and not lose some of the individual metrics integrity. Or whether or not some can be compared at all. The list I have is:
Error Rate - Mean Absolute Error - Absolute Error - Log-Loss - Classification Accuracy - Root Mean Squared Error - Classification Error - F-Measure - Area Under Curve - Mean Test Error - Error Percentage - Misclassification Error - Test Error - Mean Test Error
So my question is how to effectively convert between these, and if no direct conversion is possible, to compare and rank in a meaningful and accurate way.
Answer: We sure have plenty of terms in this fields.
This wikipedia page might be a useful introduction.
The following term are used to measure accuracy in classification
They measure the probability that the classifier prediction is not the same as the concept.

Error Rate
Classification Accuracy
Error Percentage
Misclassification Error

In the following measures we measure the accuracy, just as above. We add additional information saying where we measure it. Usually measures are measured on the train set or the test set. Here the accuracy is measured on the test set.
 - Mean Test Error
 - Test Error
The measures bellow are used for regression problems. In such problems the concept is usually continues and we are interested by how much the predictor missed. For example in whether classification we will be interested in knowing if it is hot or not. In regression we will be interested in knowing how hot.
 - Absolute Error - $abs(\hat{y}-y)$ for a specific sample y
 - Mean Absolute Error, the mean of the above
 - Root Mean Squared Error the root of the Mean Squared Error
The rest are of very different nature and here are some explanations.

Log-Loss
F-Measure
The curve in "Area Under Curve" is the ROC curve

When measuring your classifiers you have different needs. These needs are answered by different measures. While if you have perfect prediction all usual measure gets their highest score, each one of them treats errors in a different way. That is way you cannot convert on into the other. For example, you might have two classifiers with the same accuracy but different F measure. For more explanation see here.


Using msgctl() function in the kernel space

Question: in order to obtain the number of messages in a SysV queue from its ID I have used the function msgctl() in user space without any problem (as shown below):
<code>    main(int argc, char *argv[])
    {
      int qid;
      struct msqid_ds qstatus;

      qid=(int)atoi(argv[1]);

      if(msgctl(qid,IPC_STAT,&qstatus)<0){
    perror("msgctl failed");
    exit(1);
      }

      printf("There are %d messages for queue with ID %d\n",qstatus.msg_qnum,qid);
    }
</code>
Now, I need to do the same thing in kernel space, but the code below doesn't work (the function return -1):
<code>    int get_num_from_id(int qid)
    {
    struct msqid_ds qstatus;

    sys_msgctl(qid,IPC_STAT,&qstatus);

    return qstatus.msg_qnum;
    }
</code>
Someone can help me to understand what I'm doing wrong...
Answer: I have solved the problem, it was the instruction "copy_to_user()" in the function "sys_msgctl()" of "msg.c": it obviously cannot work in kernel space correctly,  because the user space addressing is different; I have bypassed the problem by creating another function based on  "sys_msgctl()" that takes only "msqid" in input and returns the number of elements...  Exactly what I have need!
Thanks the same to everyone


How to solve this indefinite integral using integral substitution?

Question: So while working on some physics problem for differential equations,  I landed at this weird integral $$ \int \frac 1 {\sqrt{1-\left(\frac 2x\right)}}\,dx $$
So since there is a square root, I thought I could use trig substitution, but I couldn't find anything that works out. How can one solve this integral in a nice simple manner? If you can solve it in a different way, it is still fine. $Thank$ $you!$
This is the answer given to me by symbolab $$ 4\left(-\frac{1}{4\left(\sqrt{1-\frac{2}{x}}-1\right)}-\frac{1}{4\left(\sqrt{1-\frac{2}{x}}+1\right)}-\frac{1}{4}\ln \left|\sqrt{1-\frac{2}{x}}-1\right|+\frac{1}{4}\ln \left|\sqrt{1-\frac{2}{x}}+1\right|\right)+C $$
Answer: HINT:
Make the substitution $x=2\sec^2(\theta)$ and arrive at
$$4\int \sec^3(\theta)\,d\theta$$
Comment: Why did this receive a down vote?  Would the down voter care to state a reason?
Answer: $u=\sqrt{1-\frac{2}{x}} \implies u^2=1-\frac{2}{x} \implies 2u du=\frac{2}{x^2} dx \implies du=\frac{1}{x^2} \frac{1}{u} dx \implies du=\frac{1}{x^2} \frac{1}{\sqrt{1-\frac{2}{x}}} dx \text{ So now back to the integral } \int \frac{1}{\sqrt{1-\frac{2}{x}}}dx=\int \frac{x^2}{x^2 \sqrt{1-\frac{2}{x}}}dx \\ \text{ now putting in the sub } \int (\frac{2}{1-u^2})^2 du \text{ Note: I solve for }x^2 \text{ from my sub to plug in also }  \\ \text{ That is I solved } u^2=1-\frac{2}{x} \text{ for } x \text{ then squared result } \\ \text{  Then you can do partial fractions. } $
Answer: Adding to Dr. MV's hint,
$$\int\frac{1}{\sqrt{1-\frac2x}}\ \mathrm dx=\int\frac{\sqrt x}{\sqrt{x-2}}\ \mathrm dx$$
Using trigonometric substitution, we have
$$\sqrt x=\sqrt 2\sec\phi$$
Which implies that
$$x=2\sec^2\phi\Rightarrow \mathrm dx=4\tan\phi\sec^2\phi\ \mathrm d\phi$$
So now the integral becomes
$$\int\frac{4\sqrt 2\tan\phi\sec^3\phi}{\sqrt{2\sec^2\phi-2}}\ \mathrm d\phi$$
$$=4\int\frac{\tan\phi\sec^3\phi}{\sqrt{\sec^2\phi-1}}\ \mathrm d\phi$$
$$=4\int\frac{\tan\phi\sec^3\phi}{\sqrt{\tan^2\phi}}\ \mathrm d\phi$$
$$=4\int\sec^3\phi\ \mathrm d\phi$$
This integral has been answered numerous times. Study this to see how the following solution is derived.
$$2\sec\phi\tan\phi+2\ln\left|\sec\phi+\tan\phi\right|+C$$
Now let's get an answer in terms of $x$. Note that
$$\sqrt x=\sqrt 2\sec\phi\Rightarrow\phi=\mathrm{arcsec}\left(\frac{\sqrt x}{\sqrt 2}\right)$$
And
$$ \tan\left(\mathrm{arcsec}(x)\right)=\sqrt{x^2-1}$$
Therefore
$$\frac{2\sqrt x}{\sqrt 2}\tan\left(\mathrm{arcsec}\left(\frac{\sqrt x}{\sqrt 2}\right)\right)+2\ln\left|\frac{\sqrt x}{\sqrt 2}+\tan\left(\mathrm{arcsec}\left(\frac{\sqrt x}{\sqrt 2}\right)\right)\right|+C$$
$$=\sqrt{x^2-2x}+2\ln\left|\sqrt{x-2}+\sqrt x\right|+C$$
Comment: No its fine I know the rest. Thank you!
Comment: @Michael, glad I could help.
Answer: Some hints
First of all, simple, thing, just rewrite the integrand this way
$$\frac{1}{\sqrt{\frac{x-2}{x}}}$$
Then substitute
$$y = \frac{x-2}{x} ~~~~~~~ \text{d}y = \frac{1}{x} - \frac{x-2}{x^2}\ \text{d}x$$
You're now with
$$2\int \frac{1}{(1 + y^2)\sqrt{y}}\ \text{d}y$$
And for this one, use
$$z = \sqrt{y} ~~~~~~~ \text{d}z = \frac{1}{2\sqrt{y}}\ \text{d}y$$
and your integral is now:
$$4\int \frac{1}{(1 - z^2)^2}\ \text{d}z$$
which is easily solvable by partial fractions:
$$\frac{1}{(1 - s^2)^2} = \frac{1}{4(z+1)} + \frac{1}{4(z+1)^2} - \frac{1}{4(z-1)} + \frac{1}{4(z-1)^2}$$
Split and do the easy integrals.
Final Result
$$x\sqrt{\frac{x-2}{x}} - \ln\left(\sqrt{\frac{x-2}{x}} - 1\right) + \ln\left(\sqrt{\frac{x-2}{x}} + 1\right) + C$$
Comment: It seems to me that rewriting $1-\frac2x$ as $\frac{x-2}x$ complicates the problem rather than simplifying it. Among other things, isn't it easier to write $\text dy = \frac2{x^2}\ \text dx$ instead of $\text dy = \frac1x - \frac{x-2}x\ \text dx$?


Disable past dates in date_combo

Question: Is there a way to disable the past dates in the date pop-up while using the date combo form api? Specifically, I have a date type field in a content type, on which I want to do this.
Help appreciated...
Answer: Use hook_date_combo_process_alter(&$element, &$form_state, $context).
I have used it in commerce discount module: while adding discount.
Example :
<code>  $current_path = current_path();
  if ($current_path == "admin/commerce/store/discounts/add") {
   $element["value"]['#datepicker_options'] = array(
     'minDate' => 0,
   );
   $element["value2"]['#datepicker_options'] = array(
    'minDate' => 0,
   );
  }
</code>

Disable past dates in date_combo


Can Stochastic Integration be Further Generalized?

Question: Is the idea of stochastic integration to accept convergence towards the stochastic integrals in probability instead of almost surely (pathwise)?
I.e. to accept a weaker form of convergence for the Riemann sums in exchange for having a wider range of integrators?
(Since desired integrators, like Brownian motion, are almost surely of unbounded variation on any interval, convergence a.s. of the Riemann sums is impossible.)
Can the range of integrators be expanded even further beyond semimartingales if we ask only for convergence in distribution instead of convergence in probability?
(Since using Ito isometry we actually show convergence of the Riemann sums in L2, which implies their convergence in probability, I believe.)
Comment: Note that $L^1$-convergence implies convergence in probability, so there is no chance to generalize stochastic integration this way.
Comment: edited post to reflect that -- it is a good point
Answer: There exist different notions of stochastic integrals, some which apply integrators which are not semimartingales. In these cases, some regularity is usually lost. One primary example is integration with respect to fractional Brownian motion. A fractional Brownian motion $B_H$ with Hurst index $H$ satisfying $0<H<1$ is a continuous-time process with continuous paths and finite-dimensional distributions which are Gaussian. For $H = 1/2$, $B_H$ is a Brownian motion and thus a semimartingale. For $H\neq 1/2$, $B_H$ is not a semimartingale. There is a considerable litterature on stochastic integration with respect to fractional processes, fractional Brownian motion in particular. See for example the book "Stochastic Calculus for Fractional Brownian Motion and Applications" by Biagini et al.
So the overall answer to the question "Can stochastic integration be further generalized?" is certainly yes.
As regards the question "Is the idea of stochastic integration to accept convergence towards the stochastic integrals in probability instead of almost surely (pathwise)?", there's probably not a simple yes or no answer to this. This is a theory which was developed piecewise with various objectives in mind. To some degree, it is probably fair to say that the answer is yes. Once you note that Riemann sums for the integral $\int_0^t H_s dB_s$ do not converge almost surely even in simple cases, it is natural to ask whether a sensible integral can be defined if a weaker notion of convergence is applied. However, other concerns are present as well. For example, the Ito stochastic integral takes care to ensure that stochastic integrals with respect to local martingales also are local martingales. Meanwhile, the Fisk-Stratonovich stochastic integral takes care to ensure that the conventional chain rule holds. Overall, it is most fair to say that the main issue confronted by stochastic integration theory is that various types of conventional regularity of integrals do not present themselves naturally for pathwisely defined integrals, and much theory is devoted to investigate how this issue can be alleviated.
Finally, regarding your question "Can the range of integrators be expanded even further beyond semimartingales if we ask only for convergence in distribution instead of convergence in probability?", this really depends on what you expect of your integral. A way of making this concrete is to ask the question "do the Riemann sum converge more often for non-semimartingales when only requiring weak convergence instead of convergence in probability?" I don't really know the answer to this question. An issue with using weak convergence is that it's a notion of convergence which only depends on distributions, in the sense that the convergence of $(X_n)$ to $X$ only depends on the marginal distributions of $X_1,X_2,\ldots$ and $X$, and not on the joint distributions $(X_1,X),(X_2,X),\ldots$ (in contrast to convergence in probability which depends on $X_1 - X, X_2 - X, \ldots$, and thus uses the joint distributions). This is an issue because of the following. Assume that you are in the case where e.g.
$$
\sum_{k=1}^n H_{t_{k-1}}(X_{t_k} - X_{t_{k-1}}) \to Y,
$$
where the convergence is weak, and $0 \le t_0 < \cdots t_n = t$. Thus, $Y$ is a candidate for the "weak" stochastic integral of $H$ with respect to $X$. Here, $X$ might be some non-semimartingale process, such that the above could be an interesting extension. Now assume that $Y$ happens to be, say, Gaussian with mean zero. In this case, $Y$ and $-Y$ has the same distribution, and thus we would also have
$$
\sum_{k=1}^n H_{t_{k-1}}(X_{t_k} - X_{t_{k-1}}) \to -Y,
$$
where the convergence again is weak. Thus, both $Y$ and $-Y$ are candidates to be the "weak" stochastic integral. This is likely to be an unfortunate property of any notion of stochastic integral based on weak convergence of Riemann sums. Therefore, it's probably not likely to yield a fruitful theory of stochastic integration in this rough form, some modifications or a different idea is required.
Comment: This is an amazing answer which addresses all of my questions with elegant arguments -- I really appreciate it/thank you so much! Sorry about the slow response -- I hadn't logged in for a while.


How to sort drush status messages in test scripts?

Question: I'm using drush to run test scripts agains my drupal 7 installation. Simply calling:
$ drush scr path/to/myScript.php

My script is using drupal_set_message() to output status of my test scripts.
My problem is the output is sorted by importance, like that:
Test 1339 failed.                [error]
Test 1338 failed.                [error]
Something strange happened!      [warning]
Test 1337 successful.            [status]
Script starting.                 [notice]
Script finished after 1234ms.    [notice]

Is there any way to sort the output of the messages by the time they get called in my script, it would look much more logical like that:
Script starting.                 [notice]
Test 1337 successful.            [status]
Test 1338 failed.                [error]
Something strange happened!      [warning]
Test 1339 failed.                [error]
Script finished after 1234ms.    [notice]

Is that possible somehow? Is drupal_set_message() the wrong approach? Any suggestions?
Answer: You can log your debugging messages in database using watchdog
 and you will find the logged message in order at "admin/reports/dtblog"
Updated:
Check the document page, as for [status] , watchdog has $severity parameter to set the status for your message.Following values can be set as status for the logged message.
WATCHDOG_EMERGENCY: Emergency, system is unusable.
WATCHDOG_ALERT: Alert, action must be taken immediately.
WATCHDOG_CRITICAL: Critical conditions.
WATCHDOG_ERROR: Error conditions.
WATCHDOG_WARNING: Warning conditions.
WATCHDOG_NOTICE: (default) Normal but significant conditions.
WATCHDOG_INFO: Informational messages.
WATCHDOG_DEBUG: Debug-level messages.

As a simple example, check this
 watchdog('your_script_name', '!message', array('!message' => "something_happened"), WATCHDOG_ERROR);

the above will log message when called keeping severity as "error".
Comment: Good alternative, indeed, but there is no `[status]`, isn't it? Debug, Info and Notice are only displayed in verbose mode.
Comment: please check the updated answer.
Comment: Yeah, I've seen the severity levels. `[debug]` is only shown with `--debug` and both `[info]` & `[notice]` are shown with `--verbose` options set. I'm looking for the normal green drupal `[status]` without passing any verbose or debug options but that seems not to exist in `watchdog()` due to some strange RCF declarations. But thanks anyways for your reply, I think I can live with that.


Why is my flex div not showing children in a row - and CSS is not applied?

Question: I have a reactjs app using a flexbox div container that holds a few images inside of child divs.  Though I set the className on the outer div and the style includes display: flex, and flexDirection: row, the divs are displaying vertically.  I have added a bunch of other styles to try to test whether my styles are applied at all and it appears they are not applied at all.  If I rename the style const name, flexStyle, to something else, such as abc, I get an error from the div line that the flexStyle is not found so I know the style constant is scoped properly.
I have a minimal code sandbox instance of the code at https://codesandbox.io/s/silly-cannon-b1yhr
Any ideas why my styles are not applied?
Answer: ClassName is for adding actual classes like in pure html class ="". See docs here. For inline styles you should use style (docs) prop like so

   ....

Comment: Thanks for the docs references.  I copied code that I wrote that works successfully using className so the references help to figure out the difference.


SVG image errors occur while rendering in flutter

Question: It shows the error message like this.
The following assertion was thrown while parsing AssetBundlePictureKey(bundle: PlatformAssetBundle#9940f(), name: "assets/icons/academy.svg", colorFilter: null, theme: SvgTheme(currentColor: null, fontSize: 14.0, xHeight: 7.0)) in _getDefinitionPaint:
Failed to find definition for url(#pattern0)
This library only supports  and xlink:href references that are defined ahead of their references.
This error can be caused when the desired definition is defined after the element referring to it (e.g. at the end of the file), or defined in another file.
This error is treated as non-fatal, but your SVG file will likely not render as intended
My SVG file containing images image.svg
<svg width="69" height="69" viewBox="0 0 69 69" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="16" y="19" width="37" height="31" fill="url(#pattern0)"/>
<defs>
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_42_579" transform="translate(0 -0.030613) scale(0.00221729 0.00264645)"/>
</pattern>
<image id="image0_42_579" width="451" height="401" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcMAAAGRCAYAAAAZwNgiAAAgAElEQVR4Aex9B3iV1Zb2NzN35s7cf+7c+8/8c1VARUSaIgiIBRAVRdELtotdJCfoVa9iA6lJvvTek5Oek957L6T33nsjvRACXDcN74r1xD7gX3BPuDfeIe+3s55LfEwQEAUX5/+1kjN9Wr/KbAAAAAElFTkSuQmCC"/>
</defs>
</svg>

And image.svg is displayed in display.dart as
class Display extends StatelessWidget {
  const Display({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('icons')),
      body: Column(
        children: [
          SvgPicture.asset(
            'assets/images/image.svg',
            height: 400.0,
            width: 300.0,
            allowDrawingOutsideViewBox: true,
          ),
        ],
      ),
    );
  }
}

Comment: double click on your svg from project explorer and see if svg opens or it show "Image not loaded"
Answer: please check your SVG before using it
please go through the link
https://www.svgviewer.dev/
Your image has some issues
Answer: My Suggestion is First download the Svg image in file formate then add the package flutter_svg: ^1.0.3 in pubspec.yaml
add the Svg image in assets folder.
Then use it in the project
final String assetName = 'assets/image.svg';
final Widget svg = SvgPicture.asset(
  assetName,
  semanticsLabel: 'Acme Logo'
);

Comment: rly? I suppose they've done it and faced with following error before asking a question
Answer: If you are getting this kind of error.
url(#paint0_linear_8372_53236) not found

Then just find the content in svg code by opening it in any svg editor(vs code or any online tool)
And move the definition to top wherever it get called.


Query URL containing term name instead of term ID on Views Exposed Filters

Question: I've got a View with an Exposed Filter that shows Taxonomy Terms that are used to filter the content that's going to be displayed as the result.
It's a View that shows recipes based on the filters chosen by the user (Type of Recipe, Type of Meat).
When I submit the form, I get the following URL:
/recipes-view?type-of-recipe=all&type-of-meat=22

The last parameter shows the number 22, which is the Term ID for the value chosen. The URL has to contain the Term Name instead of the Term ID.
Can I change it via hook_views_query_alter() or is it needed to create a custom handler for that?
Thanks in advance.
Comment: http://drupal.stackexchange.com/questions/9332/drupal-7-views-contextual-filters-taxonomy-name **just follow the above link and check.**
Comment: @Sidharth your comment is linking to QA on contextual filters, OP is trying to change a Exposed Filter Query string
Answer: There's no need to do this in code. You basically need to:

Add relationship to taxonomy term via entity reference field (it would probably also work with term reference)
Add exposed filter using this relationship (search for field Taxonomy Term: Term)

It works fine and you get URL, such as:
recipes-view?tid=vejuu

If you want to have an URL key type-of-meat, you can set it in More drop-down in you exposed filter configuration. The field name is Filter Identifier
I experienced problems with using features trying to prevent duplicates created by joining taxonomy terms.
Comment: Can you provide more details on how to add the taxonomy term via entity reference field?


Circle Problem With Many Solutions

Question: During my last year in high school, I encountered this problem:
Find the equation for a circle which have point P(-1, 2) lying on its curve, no more info
One thing you should keep in mind is that this problem has no (standard) solution, because there are many many circles that pass through (-1,2).
You can guarantee that your answer is always true
I solved it, and here is the solution:
$\\$
Let's assume a point $P^\prime: (x^\prime, y^\prime)$ that's directly facing P(-1,2), so when we connect the two points we a get diameter
Center of this circle is point C:(h, k)
substitute P coordinates in the general form of circle equation:
$$
(x-h)^2+(y-k)^2=r^2\ put \ x=-1, \ y = 2\\ \Big((-1)-h\Big)^2+\Big(2-k\Big)^2 = 1+2h+h^2+4-4h+k^2=r^2 \\ h^2+k^2+2h-4k+(5-r^2)=0 \Rightarrow eq.(1) \\ Line \ PP^\prime:\\
\frac {y-2}{x-(-1)} = {y^\prime-2}{x^\prime-(-1)} \ \Rightarrow (y-2)(x^\prime+1) = (x+1)(y^\prime-2) \\
yx^\prime+y-2x^\prime-2=xy^\prime-2x+y^\prime-2 \\
yx^\prime+y-2x^\prime-xy^\prime+2x-y^\prime = y(x^\prime+1)+x(-y^\prime+2)=0 \\
put \ x = h, \ y = k \ in \ line \ PP^\prime \ equation:\\
k(x^\prime+1)+h(-y^\prime+2)+(-2x^\prime-y^\prime) \ \Rightarrow eq.(2) \\
Since \ (1) = 0 \ and \ (2) = 0, \ then \ (1)=(2) \ numerically,\ they \ equal \ the \ same \ value \\
h^2+k^2+2h-4k+(5-r^2)=k(x^\prime+1)+h(-y^\prime+2)+(-2x^\prime-y^\prime) \\
\text{Using} \ \text{coefficients} \ \text{equality}: \\
x^\prime + 1= \text{k's} \ \text{coefficient} \ in \ eq.(1) = -4 \ \Rightarrow \Bigg(x^\prime=-5\Bigg) \\
-y^\prime +2 = \text{h's} \ \text{coefficient} \ in \ eq.(1) = 2 \ \Rightarrow \Bigg(y^\prime = 0\Bigg) \\
h=\frac {-5+(-1)}2=\frac {-6}2=-3 \\ k=\frac {0+2}2 = \frac 22 = 1 \\
Center \ C:(-3, 1) \\
r= distance \ CP=\sqrt {(-1-(-3))^2+(2-1)^2} = \sqrt {4+1} = \sqrt 5 \\
substitute \ h, k \ values \ in \ general \ from \ of \ circle \ equation:\\
(x+3)^2+(y-1)^2=x^2+6x+9+y^2-2y+1=x^2+y^2+6x-2y+10=5 \ \Rightarrow \
2y+1=x^2+y^2+6x-2y+5=0
$$
what do you say about this solution? what about yours?
Answer: Why is that a brain teaser? There are so many circles with point $(-1,2)$ on it. Take center in origin and by applying Pythagorean theorem it follows $x^2+y^2=5$.
Answer: You seem to be over complicating the problem. And in the end, you only find the equation of one circle that passes through point $P$. Notice that if $C = (a,b)$ is any point in the plane with $C \neq P$ there is a circle that is centered in $C$ and passes through $P$. Its equation is
$$
(x - a)^2 + (y-b)^2 = (a - (-1))^2 + (b - 2)^2,
$$
since the distance of a generic point $(x, y)$ lying on the circumference must be at the same distance from $C$ that $P$ is.
Comment: you are right, I really complicated it, using your idea I can do it faster

Circle Problem With Many Solutions


If $f(x)$ is a polynomial with real coefficients such that $f(x)\geq f'(x)$ for all $x$, then $f(x)\geq 0$ for all $x$

Question:
Let $f(x)$ be a polynomial with real coefficients such that $ f(x)  \ge  f'(x) $ for all $ x \in \mathbb {R}$, show that $ f(x) \ge 0 $ for all $x \in \mathbb{R}$
Comment: Hint: Try contradiction. What happens if $f(x)$ is negative for some $x$?
Answer: The case $f(x)=c$ is trivial. Let $f(x)$ have positive degree. Now, note that if $f(x)$ has negative leading coefficient, then $f(x)<f'(x)$ as $x \to \infty$ since the degree of $f(x)$ is greater. This is a contradiction, giving us the leading coefficient to be positive and thus, $ \lim_{x \to \infty} f(x) = \infty$.
Knowing that $ \lim_{x \to \infty} f(x) = \infty$, observe that if we ever have $f(x)<0 \implies f'(x)<0$. But then the function would decrease even further. This creates a loop where $f(x)$ can't increase anymore. This would give $\lim_{x \to \infty} f(x) = - \infty$ which is a contradiction.
Thus, $f(x) \geqslant 0$ over reals.
Comment: +1, quite clever


When adding Content: has taxonomy term id contextual filter to view and check specify validation criteria box, why don't I see validation options?

Question: My request is closest to these two questions:
Filter by multiple taxonomies in URL
Views contextual filters taxonomy name
I have a view which is a page and displays node titles in a table format after the user selects a state, school year, school division, and school using exposed filters. And since each resultset can have dozens of nodes (nodes about that school for that school year) in it, the results are pages of links to 10 nodes at at time. I have exposed filters for state, school year, school division, and school. The view works fine, but the urls for each page of 10 node titles pertaining to an individual school looks like this:
http://www.mydomain.com/schools?field_state_tid=123&field_school_year_tid=456&field_school_division_tid=789&field_school_tid=999&page=1
when I would prefer it look like this where instead of term_ids I have terms in the url:
http://www.mydomain.com/schools/arkansas/2012-2013/little-rock/clinton-elementary/page1
I have created state, school year, school division, and school taxonomies and each node is tagged appropriately with 1 term from each taxonomy.
But when I try to follow the instructions in the above mentioned questions, I get stuck at the part where it says to "specify validation criteria".
I check that box, but I have no options - the options are unavailable.
In the second question referenced above there is a part that says:
"Make sure Specify validation criteria is checked and you should be presented with more options."
[emphasis added]
That is exactly my problem - I should be presented with more options, but I am not.
Can anybody tell me why I am not presented with more options?
Am I doing something else wrong?
Thanks in advance.
Answer: Duh, in case anyone else runs in to this problem:
This really boiled down to after adding a contextual filter, if I clicked any of the checkboxes under the heading "When the filter value IS in the URL or a default is provided":
Override title
Override breadcrumb
Specify validation criteria
I did not see any of the options for any of those checkboxes appear after checking it.
Turns out I didn't have the most up to date version of the chaos tools module.
When I updated to chaos tools 7.x-1.3 (sometimes referred to as ctools) problem fixed.


Pegar último ID ou data inserida em uma tabela do Mysql

Question: Tenho um historico de conversas que ficam registrados na tabela sql "conversa" e quero pegar quem foi a ultima pessoa que inseriu uma mensagem na conversa para saber se foi o usuario que escreveu por ultimo ou se foi o admin (id 28).
Tem alguma forma de fazer um SELECT com uma regra para saber qual a ultima data ou úlitmo id?
id|idusuario|idconversa|  mensagem  |data
1 | 700     |    2     | mensagem 1 |2018-05-24 10:20:21
2 | 28      |    2     | mensagem 2 |2018-05-24 10:30:21

Montei o seguinte:
SELECT idusuario
FROM conversa
GROUP BY idconversa

Aí quando retornar o ultimo id que inseriu a conversa vou fazer um if para dizer se foi o admin ou o usuario (essa parte já está ok);
Comment: Tá fazendo com PHP?
Comment: Isso, to fazendo em PHP
Answer: A ideia é que você traga tudo de uma vez? O código abaixo traz a data mais atual, agrupando pelo id da conversa e do usuário:
SELECT idconversa, idusuario, max(data)
FROM conversa
GROUP BY idconversa, idusuario

Caso queira apenas de uma conversa específica, você não precisaria retornar o idconversa nem agrupar por esse campo, ficando assim:
SELECT idusuario
FROM conversa
WHERE idconversa = 2 --aqui ficaria o parâmetro de entrada (id da conversa pesquisada)
ORDER BY data desc
LIMIT 1

Comment: Boa! deu certo, o max(data) resolveu, obrigado!
Comment: isso, a ideia é trazer todas as conversas agrupadas, com a data e idusuario da ultima linha adicionada. Fiz desse jeito, mas ele está trazendo a primeira linha e não a ultima... :/
Comment: @LeandroMarzullo dá uma sacada se resolveu, alterei a resposta
Answer: Voce vai ordernar de forma decrescente.
SELECT idusuario
FROM conversa
GROUP BY idconversa
ORDER BY ID DESC
LIMIT 1;

Comment: fiz isso, mas ele trouxe o id 1, e não o ultimo
Answer: Os SQLs abaixo foram feitos para Oracle, mas podem ser adaptados para MySQ.
--tabela preenchida
select id, idusuario, idconversa, mensagem, to_char(data, 'dd/mm/yyy hh24:mi:ss') from tb_conversa;
    ID  IDUSUARIO IDCONVERSA MENSAGEM             TO_CHAR(DATA,'DD/M

     1        700          2 m1                   24/05/018 10:49:51
     2         28          2 m2                   24/05/018 14:50:25
     3         30          2 m3                   24/05/018 12:50:51
     4          1          1 m4                   24/05/018 12:51:54
     5        700          1 m5                   24/05/018 12:52:11
     6         28          1 m6                   24/05/018 14:52:28

--pegando as datas máximas por conversa
select idconversa, max(to_char(data, 'dd/mm/yyy hh24:mi:ss')) data_max
from tb_conversa
group by idconversa;
IDCONVERSA DATA_MAX

     1 24/05/018 14:52:28
     2 24/05/018 14:50:25

--trazendo as linhas que atende a data máxima, por conversa
select t1.*
from tb_conversa t1,
(
select idconversa, max(to_char(data, 'dd/mm/yyy hh24:mi:ss')) data_max
from tb_conversa
group by idconversa
) t2
where t1.idconversa = t2.idconversa and to_char(t1.data, 'dd/mm/yyy hh24:mi:ss') like t2.data_max;
    ID  IDUSUARIO IDCONVERSA MENSAGEM             DATA

     6         28          1 m6                   24/05/18
     2         28          2 m2                   24/05/18

Desculpa a formatação, sou novo no StackOverFlow.


How can one handle very large numbers such as ${1,000,000 \choose 500,000}$ using binomial formula and very tiny numbers such as $0.5^{1,000,000}$?

Question: For a problem such as what is the probability of getting exactly $500,000$ heads out of $1,000,000$ (1 million) fair coin flips, we get one huge valued number and one tiny valued number as intermediate results, both of which are not able to be computed with many online tools such as combination calculators and other online calculators.
I think the correct answer to this is ${1,000,000 \choose 500,000}$ * $0.5^{1,000,000}$.
So my question is, if someone wanted to know this approximate probability in decimal form, how would they compute it?  Is there any "shortcut"?  For example, we know that ${1,000,000 \choose 500,000}$ is $1,000,000 * 999,999 * ... 500,001$ / $500,000$! so we know we can keep the intermediate or accumulated result from becoming super large or super small and thus "blowing up".  We also know that there are $500,000$ terms that make up the numerator and ditto for the denominator, however there are $1,000,000$ powers of $0.5$ we need to multiply by so we can further "simplify" (or manipulate) that to be $500,000$ powers of $0.5^2$ which is $0.25 ^ {500,000}$.  So to me it would make sense for a combination calculator to know these "tricks" and use them to it's advantage so the result can actually be computed.  I see so many online combination calculators that cannot compute this expression.  Instead it tells me $infinity$ or Nan (not a number).  What it really means is their utility just blew a chunk and they are putting the "blame" on me that I did something wrong.
So for example, if I made a combination calculator for this problem, The first subterm, (out of $500,000$ of them), I would get would be ($1,000,000$ / $500,000$) * $0.25$ = $0.5$.  The 2nd subterm would be $999,999$ / $499,999$ * $0.25$ = $0.500000500001000002000004000008$ and so on. The last ($500,000$th) subterm would be $500,001$ / $1$ * $0.25$ = $125,000.25$. At that point I would have the final answer since I'd be accumulating the intermediate results.
I also get a similar problem when trying to compute $0.5 ^ {1,000,000}$ so it seems like someone needs to write a better combination calculator to handle problems like this.
Comment: http://en.wikipedia.org/wiki/Stirling's_approximation
Comment: http://en.wikipedia.org/wiki/Central_limit_theorem
Comment: They don't do what you did because of [truncation error](http://en.wikipedia.org/wiki/Truncation_error). The makers of W|A certainly didn't cut corners. There are many reasons why not to compute large binomial coefficients directly, the least of which is that such numbers are almost always irrelevant in practice. I find your commentary to be presumptuous.
Comment: Wow those methods are very mathematical.  Why can't they just use a method like mine where they prevent the subterms from getting excessively large or small by combining terms like I did and keeping them reasonable?  I wonder why so many online calculators "blow up" for something like $1$ million choose $500$K.  Perhaps they are trying to compute the numerator first without ever dividing terms from the denominator such as $1$M / $500$K.  I guess they "cut some corners" thinking people wont generally ask it for terms like that.
Comment: By the way, Wolfram Alpha "complains" when I ask it to compute $100,000,000 \choose 50,000,000$.
Comment: You think that nobody would ever want to model $100$ million coin flips looking for $50$ million heads?  There are way more than $100$ million people on the Earth so $100$M is not a very big number.
Comment: @David If your interest is in exact values, there exist tools to handle such calculations in many cases, but don't expect them to be free, easy, or fast.  That is unrealistic.  As I have shown you in my answer, modeling does not require exact calculations to get a functional and meaningful answer.
Comment: I agree approximations are all that is needed many times rather than an exact value when dealing with very large (and/or very small) numbers as long as the error is within acceptable limits.
Comment: @ErickWong: I only needed about 10 decimal places for the final answer which is about $0.00079788$ or about $1$ in $1253$ so I changed my original question to state I was looking for an approximate answer, not an exact one.  Thanks for pointing out that an exact answer is not necessary.
Comment: I'm not sure if this is a question about math so much as it is about why free online tools don't expend extra effort to handle numbers that users almost never care about.
Comment: @David So is your question specifically about exact values or isn't it? I meant that there is almost no context where you would need the exact value of $C(100000000,50000000)$, a number with millions of digits.
Answer: With such a large number of trials and with $p = 0.5$, a normal approximation to the binomial distribution would also work.  if $X \sim \mathrm{Binomial}(n = 10^6, p = 0.5)$, then $$\Pr[X = n/2] = \Pr\left[\frac{X - np}{\sqrt{np(1-p)}} = \frac{n/2 - np}{\sqrt{np(1-p)}}\right] \approx \Pr[-1/\sqrt{n} \le Z \le 1/\sqrt{n}]$$ using continuity correction, where $Z \sim \mathrm{Normal}(0,1)$.  Thus we have $$\Pr[X = n/2] \approx 2\Phi(1/\sqrt{n}) - 1$$ and for $n = 10^6$, this is about $0.000797884$.  In fact, this approximation is good to about $10^{-10}$.
Comment: This approximation is "not too shabby" either.  Kudos.
Answer: Even the final results in the problems you quote are very small.  In that case, it is often more useful to report the log of the answer.  For that purpose, Stirling's approximation is your friend:  it says $n! \approx \frac{n^n}{e^n}\sqrt{2 \pi n}$ or as logs $\log n! \approx n \log n - n +\frac 12\log(2 \pi n)$  It is very accurate.  Actually Wolfram Alpha has no trouble with $1000000 \choose 500000$, reporting about $7.9E301026$ (it gives many more places.)  Multiplying by $2^{-1000000}$ gives a very reasonable 0.00079788....
Comment: It is interesting to me that even though $500,000$ heads is what is expected in $1,000,000$ fair coin tosses, the actual probability of that happening seems to be only about $8$% of $1$% which is very low.  Also, I checked many online calculators but I must have missed the one that actually works.  What tool did you use to compute $0.5 ^ {1,000,000}$?
Comment: @David: [Wolfram Alpha](http://www.wolframalpha.com/input/?i=%281000000+choose+500000%29%2F2%5E1000000) again.
Comment: Wow that Wolfram Alpha is much better than some of those other online combination calculators and other calculators.  Even my windows calculator cannot handle $0.5 ^ {1,000,000}$
Comment: @David The reason for your observation is analogous to the following situation:  if I give you a fair coin and you toss is 10 times, the probability of getting exactly 5 heads and 5 tails is not actually that high--natural variation implies you could get 6 heads and 4 tails, or 4 heads and 6 tails.  With a large number of trials--$10^6$ in this case--you could get 499,999 heads and 500,001 tails.  Also, what if you flip the coin an **odd** number of times?  The expected value isn't even an integer in such a case.
Comment: Yes but with only $10$ coin flips, looking for exactly $5$ heads, the probability is close to $25$% which is MUCH higher than $8$% of $1$% like in the $1$M flip looking for $500$K situation. Obviously the more trials, the more likely it is to not get the exact amount you are looking for since it is MUCH easier to be $1$ (or more) "off" with a large number of trials vs. a small number. I noticed the same pattern with digits of pi, when the powers are low such as $10 ^ 2$ digits, it is easier for a digit to appear exactly 10 times (the digit 4 actually does). Also $9999$ zeros out of $100,000$.
Comment: FYI, Wolfram Alpha blows up on $100,000,000 \choose 50,000,000$ so it too has limits.
Comment: Actually I got Wolfram Alpha to work for ${100,000,000 \choose 50,000,000}$ once but then I couldn't get it to evaluate it again so that was very strange.  Why would it work one time only and then fail on all the other attempts?  I got it to work once by "creeping up" on those large numbers slowly like ${20,000,000 \choose 10,000,000}$ then ${40,000,000 \choose 20,000,000}$ .... Here is the message I get: Wolfram|Alpha doesn't know how to interpret your input.
Answer: In addition to the other answers, the binomial number of the form
$ {2n \choose n}$ can be approximated asympotically (using the Stirling approximation) by $ \frac{4^n}{\sqrt{\pi n}}$. so
$$ {2n \choose n} 2^{-2n}\approx \frac{1}{\sqrt{\pi n}} $$
which for $n=500000$ gives $0.0007978836\cdots$
Comment: Wow that is pretty darn accurate considering it is an approximation.
Comment: If you can explain why the square root and $\pi$ are in there, I am tempted to give you the checkmark for the most useful answer since it is the most compact formula to get the right answer (or very close to it).
Comment: @David:  They come from Stirling's approximation.  Note there are two factorials in the denominator and only one in the numerator.
Comment: @David The great thing about Stirling's approximation is that, even its most basic form, the relative error in $\log n!$ is $O(1/n)$, so for really large $n$ the approximation is superb.
Comment: I agree the approximation is "spot on" for my example but what if I didn't use ${2n \choose n}$ would I then not be able to use the approximation?  For example, if I had ${5n \choose n}$ instead.
Answer: In this answer an elementary proof is given that
$$
\frac{4^n}{\sqrt{\pi(n+\frac13)}}\le\binom{2n}{n}\le\frac{4^n}{\sqrt{\pi(n+\frac14)}}
$$
so, with $n=500000$, this becomes
$$
\frac1{\sqrt{\pi(500000+\frac13)}}\le\binom{1000000}{500000}2^{-1000000}\le\frac1{\sqrt{\pi(500000+\frac14)}}
$$
That is,
$$
0.0007978842948\le\binom{1000000}{500000}2^{-1000000}\le0.0007978843613
$$
This shows why the approximation in leonbloy's answer is so good.


Data Binding using INotifyPropertyChanged (.Net)

Question: I'm trying to find a good way to implement MVP in classic Winforms, and a couple of solutions I've come accros (e.g. http://codebetter.com/blogs/jeremy.miller/archive/2007/05/25/build-you-own-cab-part-3-the-supervising-controller-pattern.aspx) talk about using data binding between the model and the view.  I've never used data binding before, so I thought I'd give it a try.
The trouble is, I can't find out how to do simple binding (e.g. a string in my model class to a textbox on the form) using INotifyPropertyChanged, as suggested in the above article.  I thought I had it worked out (this is in the form, where 'model' is an instance of my model class):
<code>txtModelName.DataBindings.Add(new Binding("Text", model, "Name"));
</code>
However, I soon realised that this didn't use INotifyPropertyChanged at all - it works fine whether I implement that interface on my model or not.  Not a problem in itself, but it doesn't work the way I want it to, the main problem being that it's 2-way binding (I only want to bind from the object to the form).
I'm assuming that either there's a different way of binding using INotifyPropertyChanged, or that binding done as above can be set to only work in one direction - can anyone help out here, or point me towards a decent example?
I'm using .Net 3.5 with classic winforms, not WPF.
Thanks
Answer: As it turns out, the situation above was a bit of a red herring.  What was happening was that I was binding from a textbox to the model, and from the model to another textbox.  If I updated the model directly, it wouldn't work without implementing INotifyPropertyChanged.
As for the 2-way binding, I think you just have to live with that if you're using this method.  If you don't want that, just bite the bullet and use the 'Passive View' style of MVP.


Uniform convergence of convex continuous functions in $\mathbb{R}^3$

Question: Let $f_n\colon \mathbb{R}^3\to\mathbb{R}$ be continuous convex non-decreasing functions for all $n\in\mathbb{N}$ and $f_n\to f$ pointwise. I want to prove that the convergence is uniform in $\mathbb{R}^3$.
At first I wanted to use Dini's theorem but $\mathbb{R}^3$ is not compact. I understand that convexity is the key property here. Are there any other well known theorems that use convexity, in order to get rid of compactness?
Answer: The result is not true. Consider the following example in one dimension, that can be easily adapted to 3-dimensional space:
$$
f_n(x)=\frac1n\,e^x.
$$
Each $f_n$ is increasing, convex and continuous. $f_n$ converges pointwise but not uniformly to $0$.


How to fix "global name --- is not defined error "

Question: I created two classes, one for a node object and the other for a BST (binary search tree object). For the binary search tree, I have implemented two methods, one for inserting a given value (new_val) into the correct position in the tree and the other for searching the BST for a node with the given value. To implement these functions, I have created helper functions (i.e. insertRecursive and searchRecursive), which work recursively to attain the function goals. For some reason, when I run the code, I am getting the error "NameError: global name 'insert_Recursive' is not defined" and I am unsure why. Any advice on how to solve the issue would be much appreciated.
class Node(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BST(object):
    def __init__(self, root):
        self.root = Node(root)

def insert(self, new_val):
    self.insert_Recursive(self.root, new_val)

def insert_Recursive(self, start, new_val):
    if start != None:
        if (new_val > start.value):
            insert_Recursive(start.right, new_val)
        else:
            insert_Recursive(start.left, new_val)
    else:
        start.value = new_val

def search(self, find_val):
    return searchRecursive(self.root, find_val)

def searchRecursive(self, start, find_val):
    if start != None:
        if (find_val == start.value):
            return True
        elif(find_val > start.value):
            searchRecursive(start.right, find_val)
        else:
            searchRecursive(start.left, find_val)
    else:
        return False

tree = BST(4)
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
print tree.search(4)
print tree.search(6)

Comment: Everything from `insert` down to `searchRecursive` needs to be indented to be part of `BST`.
Comment: I don't know why but on my online code editor its formatted correctly with the right indentations, but when I transferred it into stack overflow, the indentations got messed. Thanks for the response though!
Answer:  if (new_val > start.value):
            insert_Recursive(start.right, new_val)

Should be
if (new_val > start.value):
            self.insert_Recursive(start.right, new_val)


Rules: use a View's result as a condition?

Question: How can I use the results of a view as a condition in a rule?
I have rule that fires off a daily digest email with contents from a view (using Views Rules). The view simply returns nodes that have a specific field value. When the view doesn't return any nodes, the rule still fires off what is essentially an empty email. I want to prevent this. I need a condition like "View has no results" (negated)… but I don't see anything like that. What's the workaround?
Answer: Even though your own answer is indeed a way to solve your question, it doesn't say that for this to work, it requires the Conditional Rules module to be enabled (without that, you cannot add a Rules Condition as an extra rules Action).
An alternative solution to solve your question, is to use the Views Bulk Operations (VBO) module to transform your view into a VBO view, so that you can use a Rules Condition "Check number of results returned by a VBO View" in which you can perfectly construct the Rules Condition you're looking for.
Have a look at "this answer" for an illustration of how this specific Rules Condition is used.
PS: I'm assuming this question is about D7.
Answer: I was eventually able to pull this off by adding a condition to the Actions section, as opposed to the (more logical) Conditions section. Here's what I did:

Added a conditional to the Actions section
Added an if to the conditional
Added the Data value is empty condition and negated it
The Data to check is one of the fields from my view, in my case <code>[created:0]</code>
Added the action (in my case, Send mail to all users of a role) and nested it under this new condition

While this does seem to work, it feels like more of a workaround than a solution. But, hey, if it works, it works. Anyway, I'm open to more direct approaches if they're out there.


tables package for Python 3.9.1?

Question: This is my first question on here. Thank you very much in advance for your support.
I'm using Python 3.9.1 on a 64-bit Windows 10 machine and I've been trying to install the tables package by pip install tables but I always got the following error:
pip install tables
Collecting tables
  Using cached tables-3.6.1.tar.gz (4.6 MB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\acer\appdata\local\programs\python\python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Acer\\AppData\\Local\\Temp\\pip-install-u9bkjlwp\\tables_8a3121807beb4fde8d73782dff1f349e\\setup.py'"'"'; __file__='"'"'C:\\Users\\Acer\\AppData\\Local\\Temp\\pip-install-u9bkjlwp\\tables_8a3121807beb4fde8d73782dff1f349e\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Acer\AppData\Local\Temp\pip-pip-egg-info-9_t31x9b'
         cwd: C:\Users\Acer\AppData\Local\Temp\pip-install-u9bkjlwp\tables_8a3121807beb4fde8d73782dff1f349e\
    Complete output (17 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Acer\AppData\Local\Temp\pip-install-u9bkjlwp\tables_8a3121807beb4fde8d73782dff1f349e\setup.py", line 634, in <module>
        libdir = compiler.has_function(package.target_function,
      File "c:\users\acer\appdata\local\programs\python\python39\lib\distutils\ccompiler.py", line 792, in has_function
        objects = self.compile([fname], include_dirs=include_dirs)
      File "c:\users\acer\appdata\local\programs\python\python39\lib\distutils\_msvccompiler.py", line 323, in compile
        self.initialize()
      File "c:\users\acer\appdata\local\programs\python\python39\lib\distutils\_msvccompiler.py", line 220, in initialize
        vc_env = _get_vc_env(plat_spec)
      File "c:\users\acer\appdata\local\programs\python\python39\lib\site-packages\setuptools\msvc.py", line 313, in msvc14_get_vc_env
        return _msvc14_get_vc_env(plat_spec)
      File "c:\users\acer\appdata\local\programs\python\python39\lib\site-packages\setuptools\msvc.py", line 267, in _msvc14_get_vc_env
        raise distutils.errors.DistutilsPlatformError(
    distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
    * Using Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)]
    * USE_PKGCONFIG: False
    ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/2b/32/847ee3f521aae6a0be380d923a736162d698586f444df1ac24b98c65025c/tables-3.6.1.tar.gz#sha256=49a972b8a7c27a8a173aeb05f67acb45fe608b64cd8e9fa667c0962a60b71b49 (from https://pypi.org/simple/tables/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

I don't understand the error message but I suspect that it has to do with my Python version.
I did install all the prerequisite packages suggested on the tables' homepage but I still got the error while installing the tables package.
I also tried to install with .whl file, too but there was no file with cp39 in its name (which led me to the conclusion that there's no compatible version for Python 3.9 yet, but I might be wrong.)
Is there a way to install tables with Python 3.9.1? Thank you very much.
Comment: You can get a pre-built version of PyTables for Python 3.9 from Christoph Gohlke's [Unofficial Windows Binaries for Python Extension Packages](https://www.lfd.uci.edu/~gohlke/pythonlibs/) website.
Comment: @SURYATEJA . Thank you for your suggestion. I tried installing the Microsoft Visual C++ following the link suggested in the error message. I still got another error message. This time it doesn't say about missing Microsoft Visual C++, though.
Comment: @martineau I tried following your suggestion and it worked. I can now import tables in my codes. Thank you.
Comment: It says You need to have "Microsoft Visual C++ 14.0 or greater" and it also gave u the link on where to find that. Please install it and check and try again.
Answer: I've downloaded and installed the tables-3.6.1-cp39-cp39-win_amd64.whl from this unofficial Windows binaries archive
Installed it with pip install tables-3.6.1-cp39-cp39-win_amd64.whl
update
The package was removed from the above link. I've found another source:
pypi.bartbroe.re/tables/

tables package for Python 3.9.1?


Category of Trees as sub-category of Category of Graphs

Question: A tree (like a binary search tree) is a direct graph with some limitations (no cycles, connected). How can I express the category of trees as "sub-category" of a graphs? There is a way? I'm not sure the term "sub-category" is correct.
Comment: What do you mean by "express"? You can just say that $\mathcal{T}$ is a category with objects being trees and morphisms being homomorphisms of trees (graphs -- it's a full subcategory of the category $\mathcal{G}$ of graphs).
Comment: "define" is better than "express"
Comment: So I wrote you an answer. What do you need more?
Answer: I think the term you're looking for is "full subcategory". If you have a category $C$, and a set $d$ of objects in $C$, then the full subcategory of $C$ defined by $d$ is the category $D$ whose objects are the elements of $d$, and whose morphisms are all the morphisms of $C$ whose domain and codomain are in $d$. Thus, you can simply say:
"Define the category Tree as the full subcategory of Gph whose objects are trees."
Comment: @DamianSobota: you could make that a full answer rather than a comment.
Comment: That's exactly what I said in a comment.
Answer: Defining what a tree is is a subtle thing and depends on what you want to use the trees for. Let us assume that you are interested in the notion of an "undirected, rooted, finite non-planar tree". The definition 'a connected undirected graph with no cycles, and with a chosen leaf as root' captures that notion and gives rise to a category of trees as the full subcategory of the category of undirected graphs spanned by these trees. However, the definition 'a contractible 1-dimensional compact connected and simply connected space with a chosen boundary point' also captures the the same notion and thus gives rise to another category of trees, the  full subcategory of the category of topological spaces spanned by those trees.
Another possibile definition is 'a finite poset with a smallest element and such that for every element the down-set determined by it is linearly ordered'. It too captures the same notion of "tree" as above and yields yet another category of trees, the full subcategory of the category of posets spanned by those trees. There is also the dendroidal category $\Omega$ whose objects are trees and can be defined in at least three different ways.
More possible definitions can be found in http://ncatlab.org/nlab/show/tree.
The point is that all of these categories are radically different. In particular the notion of subtree is highly sensitive to which of these categories you consider.
All this just goes to show that much care is needed with such formulations, even if you wish your trees form a subcategory of graphs, depending on your choice of axiomatization of the tree concept you might get very different categories.


How to write the fucntion that transfrom the columns of my dataframe to a single column?

Question: I have a dataframe like this:
A =   ID Material1 Materia2 Material3
      14   0        0        0
      24   1        0        0
      12   1        1        0
      25   0        0        2

I want to have all information in one column like this:
A =   ID  Materials
      14   Nan
      24   Material1
      12   Material1
      12   Material2
      25   Material3
      25   Material3

can anyone help write a function please !
Answer: Use DataFrame.melt with repeat rows by counts with Index.repeat and DataFrame.loc:
df1 = df.melt('ID', var_name='Materials')
df1 = df1.loc[df1.index.repeat(df1['value'])].drop('value', axis=1).reset_index(drop=True)
print (df1)
   ID  Materials
0  24  Material1
1  12  Material1
2  12   Materia2
3  25  Material3
4  25  Material3

EDIT: For add only 0 Materials with missing values use DataFrame.merge with left join by original df['ID'] in one column DataFrame withoiut duplications by DataFrame.drop_duplicates:
df1 = df.melt('ID', var_name='Materials')

df0 = df[['ID']].drop_duplicates()
print (df0)
   ID
0  14
1  24
2  12
3  25

df2 = df1.loc[df1.index.repeat(df1['value'])].drop('value', axis=1).reset_index(drop=True)

df2 = df0.merge(df2, on='ID', how='left')
print (df2)
   ID  Materials
0  14        NaN
1  24  Material1
2  12  Material1
3  12   Materia2
4  25  Material3
5  25  Material3

Comment: It worked fine , but how can i save the lines that have no materials , cauz now i only have ID with at least one material ? i Just edited my question


How to download a URL in JavaScript (Nodejs)?

Question: I used this link to make an original link into a download link:
https://milanaryal.com/2015/direct-linking-to-your-files-on-dropbox-google-drive-and-onedrive/
Now how do I actually use that download link to download the file in JavaScript? I want to do something like:
link = 'https://drive.google.com/uc?export=download&id=FILE_ID';
let x = download(link); //now x is the download file

I looked it up and it seems like there are ways of doing this with HTML/jQuery, but I am not using those because I am working on the server side with Nodejs. I am doing this download thing because I want to check if the file is a pdf or text, parse the text, and then search through it using Elasticsearch.
Answer: It's easiest to use a module such as Request to do a HTTP get from a node script.
For example:
var request = require('request');

request.get('https://drive.google.com/uc?export=download&id=FILE_ID',
   function(err, res, body){
        if(err) return console.log(err);
        console.log(body);
});

Once the file has downloaded, the callback function is run with the downloaded file in the body variable
Answer: If you only want to download the file, open it, search for data and delete it, you can easily edit this code snippet: https://stackoverflow.com/a/11944984/642977


Expected value - No consecutive heads sequence

Question:
Problem: Suppose that you flip a coin $n$ times and it turns out that
no consecutive heads appear in the sequence. Let $E(n)$ be the
expected number of heads that appear given this information. Find $
 \lim_{n\to\infty} \frac{E(n)}{n}$. The answer is in the form of$\frac{a}{b+\sqrt{c}}$ for integers a,b,c with minimal c.

My approach:
Any sequence of n coins having exactly k heads (none consecutive) will be of the form T...THT...THT...THT...T
Let $x_1$ be the number of T's before the first H. Similarly define $x_i$ for i = $2,3,...,k+1$
Here, $\quad x_1$ and $x_{k+1}$ can be $0,1,... $ $\quad$ but $\quad$ $\forall$ i = $2,..,k\quad$ $ x_i = 1,2,...\quad$ (since we want no consecutive heads)
In order to use the multinomial approach, define new variables $y_i = x_i-1 $ for these $k-1$ variables.
Now, the number of ways to get such a sequence with k heads (no consecutive) = number of sol of the equation:

$x_1 + y_2+y_3+...+y_k+x_{k+1} = n - k,$ where all variables $\in 0, 1,..$

After getting the general term for the above, taking the summation over k and dividing by total number of possible outcomes and taking the limit of n.
$$\lim_{n\to\infty}\frac{E(n)}n = \frac1n \left( \frac{\sum_{k=0}^{k=(n+1)/2} k\cdot {{n-k+1} \choose {k}}}{\sum_{k=0}^{k=(n+1)/2} {{n-k+1} \choose {k}}} \right) $$
I can't seem to simplify the numerator. I've tried everything. Is this the correct approach? Is there a better one? Either way how do I find the above limit?
Comment: Good sequences of length $n$ either start with $T$ or $HT$ and are then followed by shorter good sequences, so you can work recursively.
Comment: The denominator resembles sum of shallow diagonal of the Pascal's so I suspect it's a Fibonacci number. BTW, you meant limit on n instead of x.
Answer: Let $S_n$ be a random variable modeling the number of Heads in a sequence of $n$ tosses.
You're looking for
$E[S_n| \text{no }HH]$.
Conditioning on the outcome of the first toss,
$$
\begin{aligned}
E[S_n| \text{no }HH]
&=
P(X_1=H|\text{no }HH)E[S_n| \text{no }HH, X_1=H] +
P(X_1=T|\text{no }HH)E[S_n| \text{no }HH, X_1=T]
\\&=
P(X_1=H|\text{no }HH)E[S_n| \text{no }HH, X_1=H]+
P(X_1=T|\text{no }HH)E[S_{n-1}| \text{no }HH].
\end{aligned}
$$
Given that $X_1=T$, the possible heads only appear at a rank $\geq 2$, hence you're essentially switching to an experiment with $n-1$ tosses instead of $n$, thus $E[S_n| \text{no }HH, X_1=T] = E[S_{n-1}| \text{no }HH]$.
Conditioning on the second toss and similar arguments yield
$$E[S_n| \text{no }HH, X_1=H] = 1+E[S_{n-2}| \text{no }HH].$$
Leting $e_n=E[S_n| \text{no }HH] $ and $r_n =P(X_1=H|\text{no }HH)$, we have obtained the relation
$$e_n = r_n(1+e_{n-2}) + (1-r_n) e_{n-1},$$
with initial values $e_1=\frac 12$ and $e_2=\frac 23$.

Define additionally $p_n = E[\text{no }HH|X_1=H]$ and $q_n=E[\text{no }HH|X_1=T]$. Conditioning on the second toss, we have
$$p_n = \frac 12 q_{n-1}$$
and
$$q_n = \frac 14 q_{n-2}  +\frac 12 q_{n-1},$$
with initial values $q_1=q_2=1$.
Therefore, $$q_n =\frac{2 \left(\frac{\sqrt{5}}{4}+\frac{1}{4}\right)^n}{\sqrt{5}+1}+\frac{6 \left(\frac{\sqrt{5}}{4}+\frac{1}{4}\right)^n}{\sqrt{5} \left(\sqrt{5}+1\right)}+\frac{4 \left(\frac{1}{4}-\frac{\sqrt{5}}{4}\right)^n}{\sqrt{5} \left(\sqrt{5}+1\right)}$$
and we get a closed form for $p_n$.
By Bayes formula, $$r_n=\frac{p_n}{p_n+q_n}=\frac{\left(\sqrt{5}+5\right) 4^n \left(\left(\frac{1}{4} \left(\sqrt{5}+1\right)\right)^n-\left(\frac{1}{4} \left(1-\sqrt{5}\right)\right)^n\right)}{\left(\sqrt{5}-5\right) (-1)^n \left(\sqrt{5}-1\right)^n+2 \left(2 \sqrt{5}+5\right) \left(\sqrt{5}+1\right)^n}.$$

Recall that the recurrence relation is
$$e_n = r_n(1+e_{n-2}) + (1-r_n) e_{n-1},$$
with initial values $e_1=\frac 12$ and $e_2=\frac 23$.
It seems unlikely that it can be solved in closed form.
However, $r_n$ converges quickly to $\frac{3-\sqrt{5}}{2}$.
An "approximate" recurrence relation is then
$$\hat e_n = \frac{3-\sqrt{5}}{2}(1+\hat e_{n-2}) + (1-\frac{3-\sqrt{5}}{2}) \hat e_{n-1},$$
which has a closed form and we have
$$\lim_n \frac{\hat e_n}{n} = \frac{5-\sqrt{5}}{10} = \frac 2{5+\sqrt 5}.$$
Comment: Is your formula correct?  For $n=3$, the good sequences are $TTT, TTH, THT, HTT, HTH$.  Thus the probability that you get $(0,1,2)$ heads is $ \left(\frac 15,\frac 35,\frac 15\right)$ so the expected number is $0\times \frac 15+1\times \frac 35+2\times \frac 15=1$, no?  But of course you get $e_3=1+\frac 1{36}+\frac 1{18}=\frac {13}{12}$.
Comment: @lulu It seems I made a mistake in stating that $\{X_1=H\}$ and $\{\text{no }HH\}$ are independent. What do you think ?
Comment: I didn't look at your computation, just the result.  The recursive method I sketched in the comments is easy enough, though I doubt it leads to a pleasant closed form.  The answer will, I think,  be a fraction with numerator  from [A001629](https://oeis.org/A001629) and of course the denominators are the Fibonacci numbers.
Comment: @lulu I've corrected my recurrence relation. It is now $$e_n = r_n(1+e_{n-2}) + (1-r_n) e_{n-1}$$ where $r_n$ is given above. With $n=3$ I get the correct result $e_3=r_3(1+\frac 12) + (1-r_3)\frac 23 = 1$.
Comment: @DevanshAgarwal Is the result $\frac 2{5+\sqrt 5}$ given by the approximate recurrence relation correct ?
Comment: Note that $r_n$ is easily expressed as a ratio of Fibonacci numbers, since the number of good strings of length $n$ is a Fibonacci number.  Anyway, this formula looks good.  (+1)
Comment: @GabrielRomon Yes it is correct.


How do I debug problems during Azure Store offer upgrade?

Question: I'm having troubles debugging "upgrade" of my offer in Azure Store. I've "purchased" the offering, then I click "Upgrade", select a more expensive plan and click the "Proceed" arrow I see the following error message:

We cannot provide a billing estimate at this time. Please try again later. If this error persists, contact support with the following information.
  (Subscription could not be found for the provided subscription id (DM - ActivityId={GuidHere}

On my service side I see that there's a GET to /storebase/subscriptions/sub-id-here/cloudservices/service-name-here to which my service returns an XML reply together with HTTP 200.
That's all the data I have.
How do I find why the upgrade process fails?
Answer: The answer is there's no way to actually debug something because there's no way to access Azure Store logs and no way to find what happens behind the scene when the user goes from one Azure Store purchase step to another. All the developer can do is contact support.


Dependent variable with negative values

Question: Using a questionnaire, I quantitatively obtain the value of a symptom in a patient (that is, an ordinal variable). I apply this questionnaire twice, these occasions are separated by a period of one year. By subtracting these two values (the one found initially and after one year) I obtain a third variable that I will use as a dependent variable (this variable will show how the symptom has progressed). I have other variables that I will use as independent variables (age, sex, race). The problem is that sometimes by subtracting the two values I get a negative result (this results because in some patients the symptom worsens and in others it improves). My goal is to measure which independent variables influence symptom progression.
What type of test can I use? or what transformation can i do to the dependent variable? or Can I run a regression analysis with negative values on the dependent variable?
Thanks in advance
Answer: First off, I'd say that the formulation of your dependent variable is one approach to doing this, and the inclusion of negative values should not affect the results necessarily. It really depends on your research question. If the question is whether these factors led to an improvement or not, you could create a binary dependent variable (0 for not improved or 1 for improved).
You would typically not use a test for this type of question, but use some type of multivariate regression. However, with the limited data you have (two data points), the results are likely to be spurious.
Comment: I am currently designing the research, in fact I could add more data points, for example I could evaluate the patient every two months and in this way I could obtain the difference in score between each evaluation and the base evaluation ; in the latter case, could I run an ordinal regression or do you suggest another? It is very difficult for me to convert the dependent variable into dichotomous.
Comment: Converting the variable to a dichotomous format would not be too difficult. You would take the difference and then might right some code that says if Y is positive, code it as 1, and 0 if negative or no change. Again, it really depends on the question you'd like to ask.
Comment: My question is: Does race, sex or age significantly influence the worsening of disease symptom?

Dependent variable with negative values


Can i combine the Visual Basic project web site pages in Visual C# project and make them single project?

Question: I have two web projects one from C#.net and another from vb.net. Means while creating project i selected project as Visual Basic & Visual C#. Can i combine the Visual Basic project web site pages in Visual C# project and make them single project?
thanks
Comment: @Samuel Liew: yes. I added visual basic web project files in the Visual C# web site project. But it is showing me errors as Error `It may be inaccessible due to its protection level.`
Comment: You cannot mix in one project.  Apply the *public* keyword where necessary.
Answer: The project is set to compile using a specific compiler... c# or vb which do you want... so you have to separate the c# into its own project... and the vb in it own project.  There is one caveat.  You CAN put aspx pages that are C# and vb in the same project if you don't use code behind pages because they are compiled on the fly... just in time... ;-)


AngularJS - ng-click not working in simple Popup

Question: as my question the problem is with ng-click there is my code:

S'inscrire

Se connecter


Do I have to uninstall oracle unmanaged dataAccess (Oracle.DataAccess) before installing managed ManagedDataAccess (Oracle.ManagedDataAccess)

Question: I am planning to move from oracle unmanaged data access client to managed data access client. Right now I have ODP.Net installed on my machine which contains the DLL - Oracle.DataAccess.dll. But I am planning to move to oracle's recently released Managed data access client which contains the assembly Oracle.ManagedDataAccess.dll. Do I have to un-install the previously installed ODP.Net (unmanaged one) and then install the managed client? I have seen the installation instructions but I am not sure if this step will be required. Any help will be highly appreciated.
Answer: New Oracle.ManagedDataAccess.dll is a magnificent thing. Just do this:1. Delete existing reference to Oracle.DataAccess from your project and add a new Oracle.ManagedDataAccess.dll from the downloaded folder: odp.net\managed\common\Oracle.ManagedDataAccess.dll.
2. Set it's property Copy Local = True so it will be deployed along with your project.
3. Don't forget to add a new "using" line to your code: using Oracle.ManagedDataAccess.Client;
4. You can change the project platform target to AnyCPU now and it will work !

There's no need to install anything more, no other clients, this is some kind of oracle's packed crossplatform (64-bit and 32-bit) dll client which worked perfectly for me after all those spended hours before figuring out which dll-s (oci.dll, orannzsbb11.dll, oraociei11.dll, OraOps11w.dll) need to go in with the project for 64-bit machine and 32-bit machine fo my application to work...
Comment: It appears to be a good solution unless you're using Oracle's Membership/Profile/Roles, etc. providers.  Those use Oracle.Web.dll, which wants to revert back to the old unmanaged Oracle.DataAccess.dll.  This was a frustrating find.
Answer: To work with managed data access driver you just need Oracle.ManagedDataAccess.dll, no oracle client required.
So you can leave your unmanaged client installed (if you are planning yo use it), or uninstall it, it is up to you.


Como implementar PKCS#7 (componentes->class,biblioteca, dll, plugins e outros) em uma aplicação web MVC5

Question: Estou tentando implementar PKCS#7 em uma aplicação web mvc5 encontrei algumas soluções para aplicação desktop, nunca adicionei soluções desktop(class,dll,reference etc) em uma aplicação web, talvez seja a solução.
Alguém já trabalhou ou sabe qual a melhor forma de trabalhar com PKCS#7?
Segue abaixo um exemplo com PKCS#1 que mais se mostrou correto:
`   /*
              Representa o acesso ao Store. O construtor dela exige que se estipule qual parte da estrutura deve ser acessada. Use as definições na classe StoreName para identificar, por exemplo, os certificados particulares ("My") ou as Autoridades Certificadoras ("CA"). Pode optar também por informar apenas a localização, através da classe StoreLocation (somente os meus certicados ou todos os certificados presentes no computador).
             */
        X509Store store = new X509Store("My", StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadWrite);

        //Lista todos certificados encontrados
        List<X509Certificate2> certificado =  new List<X509Certificate2>();
        foreach (X509Certificate2 mCert in store.Certificates)
        {
            //adiciono todos certificados
            certificado.Add(mCert);
        }
        //no meu caso vou pegar a posição 1 para fim de treste msm
        X509Certificate2 certificate = certificado[1];

        /**
         * 2 chaves
         */
        //publickey desabilitado para fim de teste
        //string publicKey = certificate.GetPublicKeyString();
        //privatekEy
        //AsymmetricAlgorithm privateKey = certificate.PrivateKey;

        //privatekEy
        RSACryptoServiceProvider privateKey
                                  = certificate.PrivateKey as RSACryptoServiceProvider;
        //poderia ser um pdf, imagem, doc etc
        byte[] buffer = Encoding.Default.GetBytes("uHulll ... !");

        //aqui ele solicita PIn do cartão
        byte[] signature = privateKey.SignData(buffer, new SHA1Managed());

        //publickey
        RSACryptoServiceProvider publicKey
                    = certificate.PublicKey.Key as RSACryptoServiceProvider;

        //aqui me parece que faz a liga da senha com as duas chaves publicas/privada e retorna true ou false
        bool verify = publicKey.VerifyData
                                (buffer, new SHA1Managed(), signature);

        if (verify)
        {
            //sucesso

            byte[] hash = SHA1Managed.Create().ComputeHash(buffer);
            //pkcs#1 or no
            RSAPKCS1SignatureFormatter formatter
                                = new RSAPKCS1SignatureFormatter(certificate.PrivateKey);
            formatter.SetHashAlgorithm("SHA1");
            signature = formatter.CreateSignature(hash);
        }`

Answer: Uma vez fiz uma aplicação que recebe certificados digitais do tipo X509 (que implementam o PKCS#7) e posso colocar aqui alguns códigos de sugestão. Alguns são meus e alguns arrumei pela Internet há algum tempo atrás.
CryptoHelper
///
/// Provides methods for performing commonly-used cryptographic tasks
///
public static class CryptoHelper
{
    ///
    /// Generates a cryptographic signature for a given message
    ///
    /// <param name="message">The message to sign</param>
    /// <param name="signingCertificate">The certificate to sign the message with</param>
    /// <param name="encryptionCertificate">An optional encryption certificate to include along with the signature</param>
    /// <returns>The signature for the specified message</returns>
    internal static byte[] GetSignature(string message, X509Certificate2 signingCertificate, X509Certificate2 encryptionCertificate)
    {
        byte[] messageBytes = Encoding.ASCII.GetBytes(message);

        SignedCms signedCms = new SignedCms(new ContentInfo(messageBytes), true);

        CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);
        cmsSigner.IncludeOption = X509IncludeOption.WholeChain;

        if (encryptionCertificate != null)
        {
            cmsSigner.Certificates.Add(encryptionCertificate);
        }

        Pkcs9SigningTime signingTime = new Pkcs9SigningTime();
        cmsSigner.SignedAttributes.Add(signingTime);

        signedCms.ComputeSignature(cmsSigner, false);

        return signedCms.Encode();
    }

    ///
    /// Encrypts a message
    ///
    /// <param name="message">The message to encrypt</param>
    /// <param name="encryptionCertificates">A list of certificates to encrypt the message with</param>
    /// <returns>The encrypted message</returns>
    internal static byte[] EncryptMessage(string message, X509Certificate2Collection encryptionCertificates)
    {
        byte[] messageBytes = Encoding.ASCII.GetBytes(message);

        EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(messageBytes));

        CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificates);

        envelopedCms.Encrypt(recipients);

        return envelopedCms.Encode();
    }

    ///
    /// Finds a certificates in the user's local store based on its serial number
    ///
    /// <param name="serialNumber">The serial number of the certificate to retrieve</param>
    /// <returns>The requested certificate, or null if the certificate is not found</returns>
    public static X509Certificate2 FindCertificate(string serialNumber)
    {
        X509Store localStore = new X509Store(StoreName.My);

        localStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        try
        {
            X509Certificate2Collection matches = localStore.Certificates.Find(
                X509FindType.FindBySerialNumber,
                serialNumber,
                true);

            if (matches.Count > 0)
            {
                return matches[0];
            }
            else
            {
                return null;
            }
        }
        finally
        {
            localStore.Close();
        }

    }

    ///
    /// Finds a certificate in the user's local store based on its subject and usage flags
    ///
    /// <param name="subjectDistinguishedName">The subject distinguished name of the certificate</param>
    /// <param name="usage">The minimum usage flags the certificate must contain</param>
    /// <returns>The requested certificate, or null if the certificate is not found</returns>
    public static X509Certificate2 FindCertificate(string subjectDistinguishedName, X509KeyUsageFlags usage)
    {
        X509Store localStore = new X509Store(StoreName.My);

        localStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        try
        {
            X509Certificate2Collection matches = localStore.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName,
                subjectDistinguishedName,
                true);

            if (matches.Count > 0)
            {
                foreach (X509Certificate2 cert in matches)
                {
                    foreach (X509Extension extension in cert.Extensions)
                    {
                        X509KeyUsageExtension usageExtension = extension as X509KeyUsageExtension;

                        if (usageExtension != null)
                        {
                            bool matchesUsageRequirements = ((usage & usageExtension.KeyUsages) == usage);

                            if (matchesUsageRequirements)
                            {
                                return cert;
                            }
                        }
                    }
                }

                return null;
            }
            else
            {
                return null;
            }
        }
        finally
        {
            localStore.Close();
        }
    }
}

O método abaixo criptografa um e-mail:
    public static void SendCryptographedEmail(ScheduledEmail email, String certificatesDirectory, String attachmentsDirectory, bool attachmentsByLink = true)
    {
        var message = new SecureMailMessage();

        // Look up your signing cert by serial number in your cert store
        // X509Certificate2 signingCert = CryptoHelper.FindCertificate("1B37D3");
        var signingCert = new X509Certificate2(certificatesDirectory + "\\" + email.User.CertificatePath, email.User.CertificatePassword);
        // Look up your encryption cert the same way
        // X509Certificate2 encryptionCert = CryptoHelper.FindCertificate("22C590");
        var encryptionCert = new X509Certificate2(certificatesDirectory + "\\" + email.User.CertificatePath, email.User.CertificatePassword);

        // Load the recipient's encryption cert from a file.
        var recipientCert = new X509Certificate2(certificatesDirectory + "\\" + email.User.CertificatePath, email.User.CertificatePassword);

        message.From = new SecureMailAddress
            (email.User.Email, email.User.Name, encryptionCert, signingCert);
        message.To.Add(new SecureMailAddress
            (email.Recipient, email.Recipient, recipientCert));

        message.Subject = email.Subject;
        message.IsBodyHtml = true;
        message.IsSigned = true;
        message.IsEncrypted = true;
        var messageBody = email.Message;

        if (attachmentsByLink)
        {
            messageBody += "
Anexos
";

            foreach (var scheduledEmailAttachment in email.ScheduledEmailAttachments)
            {
                messageBody += "
" +
                               scheduledEmailAttachment.FileName + "
";
            }
        }
        else
        {
            foreach (var scheduledEmailAttachment in email.ScheduledEmailAttachments)
            {
                byte[] fileBytes =
                    File.ReadAllBytes(Path.Combine(attachmentsDirectory, scheduledEmailAttachment.FileName));

                message.Attachments.Add(
                    new SecureAttachment(fileBytes,
                        new SecureContentType(scheduledEmailAttachment.MimeType.ToValue()))
                    );
            }
        }

        messageBody += "";
        message.Body = messageBody;

        // Instantiate a good old-fashioned SmtpClient to send your message
        var client = new System.Net.Mail.SmtpClient(email.User.ConfigSMTP.FirstOrDefault().Server, (int)email.User.ConfigSMTP.FirstOrDefault().Port)
        {
            Credentials = new NetworkCredential(email.User.ConfigSMTP.FirstOrDefault().Username, email.User.ConfigSMTP.FirstOrDefault().Password)
        };

        // If your SMTP server requires you to authenticate, you need to specify your
        // username and password here.

        client.Send(message);
    }

ScheduledEmail é um Model MVC, mas não precisa ser:
public class ScheduledEmail
{
    [Key]
    public Guid ScheduledEmailId { get; set; }
    public Guid UserId { get; set; }

    [EmailAddress]
    [Required(ErrorMessage = "É necessário um Destinatário")]
    public string Recipient { get; set; }
    public string Subject { get; set; }
    [Required(ErrorMessage = "É necessário um conteúdo para a mensagem")]
    public string Message { get; set; }
    [Required(ErrorMessage = "É necessário uma data de agendamento para a mensagem")]
    // [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm}", ApplyFormatInEditMode = true)]
    public DateTime ScheduleDate { get; set; }
    public DateTime? SendDate { get; set; }
    public string Sending { get; set; }

    [NotMapped]
    [Display(Name = "Files", ResourceType = typeof(Resources.Language))]
    public IEnumerable<HttpPostedFileBase> Files { get; set; }

    [Display(Name = "LastModified", ResourceType = typeof(Resources.Language))]
    public DateTime LastModified { get; set; }
    [Display(Name = "CreatedOn", ResourceType = typeof(Resources.Language))]
    public DateTime CreatedOn { get; set; }

    public virtual ICollection<ScheduledEmailAttachment> ScheduledEmailAttachments { get; set; }
    public virtual User User { get; set; }
}

Artigos de Base

An S/MIME Library for Sending Signed and Encrypted E-mail
Comment: Você não teve problema com a class SignedCms? eu adicionei `using System.Security.Cryptography.Pkcs;` mas não rolou.
Comment: Adicionou `System.Security` nas referências do projeto?
Comment: Sucesso! era isso, o estranho é que a X509 funcionava `using System.Security.Cryptography.X509Certificates` .
Comment: Beleza. Coloquei mais um link que tem todos os fontes. Não ia caber tudo na resposta.


Norm inequality

Question: While trying to compute a quotient space, the next problem has come to my attention:

Let $x=(x_j)_j$ and $y=(y_j)_j$ be two complex convergent sequences such that $x-y=(x_j-y_j)_j$, is a constant sequence.
  $$
\text{Note that $x-y$ is a constant sequence if and only if $x_j-x_{j+1}= y_j-y_{j+1}$ for each $j \in \mathbb{N}$.}
$$
  Consider the sequence $z=(y_j-y_{j+1})_j$. What is the order relation between $$
\| x \|_\infty = \sup_{j \in \mathbb{N}} | x_j | \ \ \text{ and } \ \ \| z \|_\infty= \sup_{j \in \mathbb{N}} | y_j - y_{j+1}| \ \ \text{ ?}
$$

My guess is that $\| x \|_\infty \geq \| z \|_\infty$. However, I can not prove it, so I am starting to think I may be wrong and no order relation can be obtained. My guess is not random, I have come up whit a few examples where it actually holds like the next ones:
$$
x=(1,1/2,1/3, \cdots ) \\
y=(1/2, 0 , -1/6 , \cdots)
$$
Clearly $x-y = (1/2, 1/2, 1/2, \cdots)$ and if $z=(y_j-y_{j+1})_j$ then
$$
\| x \|_\infty=1 \geq 1/2=\| z \|_\infty
$$
Another example is obtained from the one above by changing $x$ and $y$ roles, that is since $y-x =(-1/2, - 1/2, - 1/2, \cdots)$, if now $z=(x_j-x_{j+1})_j$ then
$$
\|y\|_\infty = 1/2 = \| z \|_\infty
$$
So, my question here is could someone help me on how to prove that my guess is correct or give a counterexample when $\|x\|_\infty < \| z \|_\infty$ ? I would appreciate it very much. Also if you think more details of the original problem can help let me know so I can make an edit.
Comment: $x = y = (1,-1,0,0,\dotsc)$.
Comment: The idea is that y is a translation x; y does not really play any role in your question. Just look x and the difference $x_{j+1}-x_j$. You want to make the difference "big" while keeping x "small".
Answer: Assuming I understand the question correctly, I believe it is false.
Consider $x=(50, -50, 50, -50, 0, 0, 0, 0, ...)$ and $y=(40, -60, 40, -60, -10, -10, -10,...)$.  Then $x-y=(10, 10, ...)$ and is constant.  $z=(-100, -100, -100, -70, -20, -20, -20, ...)$ so $\Vert z\Vert_{\infty} = 100$ and $\Vert x\Vert_{\infty} = 50$.
Comment: Thanks a lot. I will soon post a question about the original problem, Its a long one and my proof depended a lot on my guess here being correct, so its wrong. I hope I come up with something new soon. Thanks again.
Comment: This is the original problem:
http://math.stackexchange.com/questions/1281099/compute-quotient-space-isometry-part
who gave birth to the question you answered above, I hope you can take a look and let me know if you come up with something.
Answer: Here is the counterexample:
Let $x=(-1,1,0,0,0,...)$ and $x=y$. Then $z=(2,-1,0,0,0,...)$ and $||x||_\infty=1$, while $||z||_\infty=2$.
The idea is not very different from Travis' answer.
Comment: This is a good answer too (like @DanielFischer's comment).  More elegant than my solution.  (I got to thinking to get a big difference I needed "big" numbers... it is un-necessarily large; it's just what I came up with while very quickly experimenting).
Comment: @IoannisSouldatos  This is the original problem:
http://math.stackexchange.com/questions/1281099/compute-quotient-space-isometry-part
who gave birth to the question you answered above, I hope you can take a look and let me know if you come up with something.

Norm inequality