Showing that a map, $R:\mathbb{R}^n\rightarrow\mathbb{R}^n$ can be represented by an orthogonal matrix.

Question: Note: This is a homework question.
After pages of attempts and failures, here I am. First, I will present the question then state what I have tried.
The question:
Let $u$ be a non-zero vector in $\mathbb{R}^n$. Let $L = \mbox{Span}\{u\}$. Define a map, $R:\mathbb{R}^n\rightarrow\mathbb{R}^n$ by
$$R(x) = 2proj_Lx - x$$
for $x\in\mathbb{R}^n$.
Show that $R$ can be represented by an orthogonal matrix $Q$, state what the matrix is and show that it is orthogonal. (This matrix $Q$ will involve the vector $u$ and the identity matrix $I$.)
Attempted solution:
Since $u$ is the basis for $L$, we can rewrite $proj_Lx$ as $proj_ux$. Then, since this seems like a problem dealing with a reflection over $L$, I used the following reflection matrix:
$$\begin{bmatrix} cos(\theta)&sin(\theta)\\ sin(\theta)&-cos(\theta)\\ \end{bmatrix}$$
Where:
$cos(\theta) = \frac{x\cdot proj_ux}{\left|\left|x\right|\right|\,\left|\left|proj_ux\right|\right|}u = \frac{x\cdot\frac{<u,x>}{<u,u>}u}{\left|\left|x\right|\right|\,\left|\left|\frac{<u,x>}{<u,u>}u\right|\right|} = \frac{x}{\left|\left|x\right|\right|}\cdot\frac{<u,x>u}{\left|\left|<u,x>u\right|\right|}$
$sin(\theta) = \sqrt{\left(\frac{x\cdot proj_ux}{\left|\left|x\right|\right|\,\left|\left|proj_ux\right|\right|}u\right)^2-1} = \sqrt{\left(\frac{x\cdot\frac{<u,x>}{<u,u>}u}{\left|\left|x\right|\right|\,\left|\left|\frac{<u,x>}{<u,u>}u\right|\right|}\right)^2-1} = \sqrt{\left(\frac{x}{\left|\left|x\right|\right|}\cdot\frac{<u,x>u}{\left|\left|<u,x>u\right|\right|}\right)^2-1}$
However, once I get here, I get a bit lost in how I might be able to continue, especially since the problem states that $Q$ will involve the identity matrix $I$. I feel there should be a better way of approaching this but I certainly can't come up with anything.
Thank you for any help you may be able to provide.
Comment: The mapping $x\mapsto x- 2proj_L(x)$ is the reflection with respect to the hyperplane that has $u$ as its normal vector (see e.g. [here](http://math.stackexchange.com/a/65525/11619)). Reflections preserve angles and lengths, so are represented by an orthogonal matrix. This mapping is a negated version, and thus orthogonal as a compositum of two orthogonals.
Answer: Assume $x \in \mathbb{R}^{n}\setminus\{0\}$. Let $l$ be the line $\{ t x : t \in\mathbb{R}\}$. The closest point projection of $y$ onto the line $l$ is the unique point $\alpha x$ (where $\alpha \in\mathbb{R}$) such that $(y-\alpha x)\perp x$. Using inner-product $(\cdot,\cdot)$, this gives $\alpha(x,x)=(y,x)$, and
$$
            Py = \frac{(y,x)}{(x,x)}x.
$$
The vector from $y$ to the projection $Py$ onto the line $l$ is orthogonal to the line. So $(y-Py)\perp Py$, which gives the orthogonal decomposition $y=(y-Py)+Py$. So, by the Pythagorean Theorem,
$$
\begin{align}
       \|y\|^{2}  & = \|(y-Py)+Py\|^{2} \\
                  & = \|y-Py\|^{2}+\|Py\|^{2} \\
                  & = \|(Py-y)+Py\|^{2}=\|(2P-I)y\|^{2}.
\end{align}
$$
Your operator is $A=2P-I$, and the above shows that this operator is isometric and, therefore, has an orthogonal matrix representation. This operator is $I$ on the one-dimensional space spanned by $x$ and is $-I$ on the vectors which are orthogonal to $x$.
You can write $A=UDU$ where $U$ is orthogonal and $D$ is the diagonal matrix with a $1$ in the upper left corner and $-1$'s on the rest of the diagonal, provided you choose the first column of $U$ to be the representation of $x$, and the remaining columns of $U$ to be representations of an orthonormal basis of vectors which are orthogonal to $x$.
Comment: @ T.A.E. , I give you $x=[1,2,5,7]^T$. Can you obtain $A$ in few seconds ? If not, have a look on my post below. The most important fact is that the matrix $A$ does not depend on the chosen orthonormal basis of the orthogonal of $x$.
Comment: @loupblanc : For any orthogonal projection $P$--regardless of the dimension of the range of $P$--the above argument above shows $A=2P-I$ is orthogonal. On the range of $P$, one has $P=I$ and, so, $A=I$; on the orthogonal complement of the range of $P$, one has $P=0$ and hence $A=-I$. You shouldn't be surprised that the representation of the identity operator on a subspace does not vary with how you choose a basis for the subspace. The most important thing for the splitting is choosing an orthonormal basis where a basis element is either in the range of $P$ or in its orthogonal complement.
Comment: @ T.A.E. I agree with you on the first part of your comment. It is the reason because you method is not good. In particular, there is absolutely no choice  of orthonormal basis to do. Read my post below.
Answer: I am not sure how you are defining your $proj$ but chose a basis that starts with $u$
and has the other elements orthogonal to $u$.
Then the matrix in this basis is
$$\begin{pmatrix}
1&0&0\\
0&-1&0\\
0&0&-1\\
\end{pmatrix}$$
Comment: This matrix is not orthogonal, and you also seem to assume that $n=3$.
Comment: @SantiagoCanez n=3 is just ease of writting.
Comment: @SantiagoCanez O I see what you mean, its just a typo, NOW its orthogonal.
Comment: Thank you Rene but I'm not sure how you came up with the matrix, nor how I would generalize it to $\mathbb{R}^n$.
Comment: In higher dimensions there are just more $-1$'s. Proj fixes the first element $u$ and maps all the other elements of the basis to zero, you can now calulate how your function operates.
Comment: Hello Rene, thanks again but I'm afraid I'm completely lost on this still and have absolutely no idea how to go about it. I'm sure I'm missing something somewhat trivial. Any extra help would be really appreciated.
Answer: Let $y=R(x)$ and $y=2p(x)-x$. Then $(x+y)/2=p(x)$ and $R$ is the orthogonal symmetry with respect to $u$ (in the direction of $orthog(u)$). Finally $R\in O(n)$ and $\det(R)=(-1)^{n-1}$ (because $R=id$ on $span(u)$ and is $-id$ on $orthog(u)$).
EDIT 1: if you want an explicit form: Let $u=[u_1,\cdots,u_n]^T$ where $u$ is assumed to be a unitary vector. Then $R=2P-I$ where $P=[p_{i,j}]$ with $p_{i,j}=u_iu_j$. Note that $R$ is a symmetric matrix.
EDIT 2: for instance , let $u=[1,2,5,7]^T$. Then $R=2P-I$ where $P=\dfrac{1}{||u||^2}\begin{pmatrix}1&2&5&7\\2&4&10&14\\5&10&25&35\\7&14&35&49\end{pmatrix}$.
Answer: Let $M$ be the orthogonal complement of the one-dimensional subspace $L$. Then ${\rm dim}(M)=n-1$.
Any $x\in{\mathbb R}^n$ can be decomposed in a unique way as $x=x'+x''$ with $x'\in L$, $x''\in M$. Furthermore one has
$$R(x')=2{\rm proj}_L(x') -x'=2x'-x'={\rm id}(x')\qquad(x'\in L)$$
and
$$R(x'')=2{\rm proj}_L(x'') -x''=0-x''=-{\rm id}(x'')\qquad(x''\in M)\ .$$
With respect to an orthonormal basis of ${\mathbb R}^n$ with $e_1\in L$ and $e_k\in M$ $\>(2\leq k\leq n)$ the map $R$ therefore has the matrix $D:={\rm diag}(1,-1,-1,\ldots, -1)$, which is certainly orthogonal. With respect to the standard basis of ${\mathbb R}^n$  the matrix of $R$ is then given by
$$[R]=T'\>D\>T\ ,$$
whereby the standard coordinates of the vectors $e_i$ are written in the columns of $T$. Since $T$ is also an orthogonal matrix so is $[R]$.
Answer: Just restating Jyrki's comment as an answer with a memorable name: this is a reflection in the (hyper-)plane and its matrix is the (negative) Householder matrix which is easily orthogonal.


Joint conditional density of two iid exponential random variables conditioned on their sum

Question: I have the following question:
Suppose $X_1, X_2$ iid $\sim f_X(x)=\theta e^{-\theta x}1\{x\ge 0\}$ and $S=X_1+X_2$. What is $f_{X_1,X_2}(x_1,x_2|S=s)$?
The solution from our exercise class to this problem was $$f_{X_1,X_2}(x_1,x_2|S=s)=\dfrac{f_{X_1,X_2,S}(x_1,x_2,s)}{f_S(s)}=\dfrac{\theta^2 e^{-\theta s}}{\theta^2 s e^{-\theta s}}= \dfrac{1}{s} \quad \text{,where} \quad s=x_1+x_2$$
However, to me it is not clear how to understand this "where $s=x_1+x_2$". Shouldn't it rather be something like:
$$f_{X_1,X_2}(x_1,x_2|S=s)= \dfrac{\delta(s=x_1+x_2)}{s}$$
where $\delta$ is a dirac delta function? Or how can we otherwise recover $f_{X_1,X_2}(x_1,x_2)$ from $f_{X_1,X_2,S}(x_1,x_2,s)$ by integrating out $s$?
Comment: 1) Please add the tag [tag:self-study]. 2) some hints: You are conditioning on $s=S=X_1+X_2$ so no need for the delta function. 3) Use that $X_1+X_2=S$ has a gamma distribution (with shape parameter 2) and the known result that $X_1/S$ has a beta distribution with params 1,1; that is, it is uniform, so $X_1$ given $S=s$ is uniform on $(0,s)$
Comment: Well, yes, you can write it that way, if you want. But what is wrong with just saying that $s=x_1+x_2$?
Comment: The dominating measure is the Lebesgue measure on the line $x_1+x_2=s$.
Comment: Thanks for your answer. Isn't that exactly what you get with the delta function that $X_1|S=s$ has uniform distribution on $(0,s)$? I also don't see how $f_{X_1,X_2}(x_1,x_2|S=s)$ is integrating to $1$ (in $x_1,x_2$) otherwise, as it is only nonzero on a set of L-measure zero right?
Comment: Well I don't understand how this can be a density. What is the dominating measure?
Answer: One way of thinking about your problem is connecting it to the Poisson process. Start a (homogeneous) Poisson process at time zero. Then $X_1$ is the waiting time to the first event (point), and $S=X_1+X_2$ is the waiting time to the second event. So we know there is exactly one event in the interval $(0,S)$, and the result follows from the uniform distribution of the event, given the endpoint of the interval.
You can add the algebra.


Looking for explanation of Erlang code book

Question: Can someone please explain this line by line?
Many many thanks.
run() ->
        Pid = spawn(fun ping/0),
        Pid ! self(),
        receive
                pong -> ok
        end.
ping() ->
        receive
                From -> From ! pong
        end.

Answer: Line by line:
run() ->

Declare the function run/0
    Pid = spawn(fun ping/0),

Spawns new process with initialization function ping/0 and store its pid to variable Pid
    Pid ! self(),

Sends message containing the pid of current process (result of self/0 call) to the process which pid is stored in variable Pid
    receive

Waits for a message (or amount of time if there is after clause)
        pong -> ok

If there is a received message pong, return value ok
    end.

End of receive clause and dot also means there is end of function run/0
ping() ->

Declares the function ping/0
    receive

Waits for a message ...
        From -> From ! pong

When receiving anything, store it in variable From and then send message pong to the process determined by value in From (pid of process executing run/0 function in this case)
    end.

End of receive and also ping/0 function
Comment: What does -> mean exactly?
Comment: `->` is just delimiter. It typically delimits head and tail of some sort of clause. It delimits function head form body, case pattern head from its body, receive pattern form its body, `if` condition from its body and so.


React: Action vs modifying state variable

Question: When is modifying a state variable in a react class component acceptable, and when is it proper to call on an action to change a state variable?
What is the best practice? Would changing a state variable in a react class component go against Flux convention?
Comment: See the React docs on props vs state: http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html
Answer: There is no correct answer to this question, because it is contextual and depends a lot on your code in general. However, from personal experience I would urge you to refrain from utilizing state variables. It may be acceptable in components without children, but it is still easy to end up having a lot of logic in your component that does not concern itself strictly with presentation (read: rendering).
My opinion: keep your state and data in stores, let the components be incredibly stupid and only deal with rendering and executing actions. This approach makes the app easier to test and ensures readability.
Answer: I would consider using component state in cases where the data in question is localized and tightly coupled to the component, meaning that it is only relevant to the component itself and unlikely to be needed by any other parts of the application in the future. Of course you can't anticipate everything, so when in doubt it's probably better to consider it 'application state' and put it in a Store.
Form inputs are one case where this might apply. For example, the transient state of the input fields of a typical user registration or login form is unlikely to ever become relevant to other parts of the application. The data is only used in rendering the component itself and in making the API call that submits the data, so it's natural to think of the state of the form as part of the form and use the component state to store it.
A counterexample would be an input for a dynamic search that filters a list in a separate component, where the list should start responding as soon as the user begins typing. Here the transient state of the input should be considered application state and kept in a Store where other components can access it.
Answer: You should only ever use actions to write to a store, so if you have state that is a direct representation of what is in a store, then you should only use an action to update it.  There are a lot of options out there but https://github.com/HubSpot/general-store comes with a mixin that lets u bind store data directly to state.
so in your component you could do something like:
mixins: [
    GeneralStore.StoreDependencyMixin({
      user: UserStore.get()
    })
]

and that would bind whatever data lives in that store into state, when the store is updated so will your components state.  There are also many cases where components have some bit of local state like:
getInitialState: ->
  modalOpen: false

openModal: ->
  @setState
    modalOpen: true

I have run into some situations where I want to take the data in a store out of sync so that I could keep track of changes and possibly do a reset and list the changes to the model before a user saves and the way i did that is by jsut duplicating the store model in state and mutating that directly, then on save use an action to hit a save endpoint, then pass the newly saved model into the store which would update both the local(out of sync) copy and the main source of truth from the store itself.
Comment: In your second scenario, I wonder if a component shouldn't just have its store or its tightly bound state stored in the single store, for example var store = { .... , myControlBar : { modalOpen: false}, ... }.   At best this keeps things simple and someone later on will know where to find all state.


Question about limit of cosimplicial diagram associated with a sheaf

Question: Let $F$ be a presheaf of sets on the usual topological site. Let $\left\{U_i\rightarrow U\right\}$ be covering of $U$. On the second page of Hypercovers and Simplicial Presheaves the authors write the equalizer of $$\prod_iFU_i\rightrightarrows\prod_{i,j}FU_{ij}$$
is in fact the limit of the entire cosimplicial diagram (degeneracy maps omitted)
$$\prod_iFU_i\rightrightarrows\prod_{i,j}FU_{ij}\substack{\longrightarrow \\ \longrightarrow \\ \longrightarrow}\prod_{ijk}F(U_{ijk})\substack{\longrightarrow \\ \longrightarrow \\ \longrightarrow \\ \longrightarrow}\cdots$$
I'm trying to work this out using the concrete description of limits in the category of set, but I'm confused and stuck at the very beginning. I would like some guidance in this verification as well as geometric explanations of why we can truncate above level 1 and ignore degeneracy maps.
Answer: Here's a very concrete argument. A limit of the cosimplicial object is an $X$ which comes a priori with maps to each of the cosimplicial levels, but since $0$ is weakly initial in $\Delta$, only needs to be given a map $f:X\to \prod FU_i$, from which the other maps are determined. Now $f$ is equalized by the two face maps, so $f$ factors through the equalizer $Y$ of the truncated diagram above. On the other hand, try to define a cone with tip $Y$ over the whole cosimplicial diagram starting with $g_0=g:Y\to \prod FU_i$ using, say, the zeroth face maps $d_0^i$. So we get maps $g_i$ to each level of the cosimplicial diagram. We need to show each face map composes with $g_i$ to get $g_{i+1}$. This happens by a double induction on $k$ and $i$ because of the cosimplicial identity
$d_k^i \circ d_{k-1}^{i-1}=d_{k-1}^i\circ d_{k-1}^{i-1}$. Now the degeneracy maps are handled because $s^i_kg^i=s^i_kd^{i-1}_kg^{i-1}=g^{i-1}$, using the cosimplicial identities again and the cone over the face maps. Thus $g$ induces a cone of $Y$ over the cosimplicial diagram, yielding a factorization of $g$ through $f$. These two factorization so combine in the usual way to show $g$ displays $Y$ as a limit of the whole cosimplicial diagram.
All this was pure algebra of simplicial sets. Geometrically, the point is simply that the restriction of a section over $A$ to $A\cap B\cap C$ is the restriction of its restriction to $A\cap B$ or $A\cap C$, so if you have some sections which are consistent on twofold intersections, these last restrictions agree with the restriction of that over $B$ to $A\cap B, C$ to $A\cap C$ etc, so they're guaranteed to agree on threefold and higher intersections. In (higher) stack theory, the story no longer goes through: you choose isomorphisms between sections over twofold intersections, which must commute when restricted to threefold intersections, so you need a diagram truncated one level higher (or for higher stacks, you might need the entire diagram.)
Comment: Where, in the formal argument, did you use the $\mathsf{Set}$ is a 1-category, i.e where would this proof fail for, say, stacks?
Comment: @arrow I assume that $X$ and $Y$ are strictly limits; in sheaf terms, that the sections over $A$ and $B$ are to be exactly equal when restricted to an intersection. A stack only asks for isomorphisms between these restrictions, so $X$ and $Y$ would no longer be strict limits, rather pseudolimits or homotopy limits, depending on the framework.


Changing background color of canvas

Question: On canvas, I have a rectangle that has white as default color and I want to change its color by using a color picker that stores the color in a textbox. If user types in a color name, value or the input color picker it should change.
I don't understand why my code doesn't work at all. Could you help me?

const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth - 60;
canvas.height = 400;

let context = canvas.getContext("2d");

let start_background_color = "white";

context.clearRect(0, 0, window.innerWidth, window.innerHeight);
context.fillStyle = start_background_color;
context.fillRect(0, 0, window.innerWidth, window.innerHeight);

function change_background_color() {
  let color = document.getElementById('colorInputColor').value;
  //document.body.style.backgroundColor = color;
  context.fillStyle = color;
  context.fillRect(0, 0, window.innerWidth, window.innerHeight);
  document.getElementById('colorInputText').value = color;
}
<input type="text" id="colorInputText">
<input type="color" class="color-picker" id="colorInputColor">
<input type="button" id="colorButton" value="Click to Change Color" onclick="change_background_color">
<canvas id="canvas"></canvas>
Answer: when calling the function change_background_color you have to use parentheseis too like this
<input type="button" id="colorButton" value="Click to Change Color" onclick="change_background_color()">

Changing background color of canvas


Find $\lim_{n \rightarrow \infty} P(n[Y_n]=k)$

Question: Suppose $X_1,X_2,...,X_n$ is a random sample from $U(0,\theta)$ for some unknown $\theta>0$.Let $Y_n$ be the minimum of $X_1,X_2,..,X_n$.
Find $\lim_{n \rightarrow \infty} P(n[Y_n]=k)$ for $k=0,1,2,...$ where $[x]$ denotes the largest integer less than or equal to $x$.
My approach:
We first write down the pdf of $Y_{n}$:
$f(y)=\frac{n}{\theta}(1-\frac{y}{\theta})^{n-1}$
Now, let $Z=[Y_n]$
$P(Z=z)=P([Y_n]=z)=P(z \le Y_n < z+1)=\int_{z}^{z+1} \frac{n}{\theta}(1-\frac{y}{\theta})^{n-1} dy=(1-\frac{z}{\theta})^n-(1-\frac{z+1}{\theta})^n$
Now, plugging in $\frac{k}{n}$ for $z$,we have $P(Z=\frac{k}{n})=(1-\frac{k}{n \theta})^n-(1-\frac{k+n}{n \theta})^n$ , but I cannot find the limit .
Perhaps, I have made a mistake somewhere. Please help!!
Answer: Consider $k>0$, if $n>k$, then $\frac{k}{n} \notin \mathbb{Z}$, hence
$$P\left( n[Y_n]=k\right)=P\left( [Y_n]=\frac{k}{n}\right)=0$$
Hence if $k>0$,  $\lim_{n \to \infty}P(n[Y_n]=k)=0.$
Now consider the case where $k=0$.
Let's first consider the CDF of $Y_n$. Let $y \in (0, \theta),$
\begin{align}
P(Y_n \le y) &= 1-P(Y_n > y) \\
&= 1-P\left( \min(X_1, \ldots, X_n) > y\right) \\
&= 1- \prod_{i=1}^n P(X_i > y) \\
&= 1- \left( \frac{\theta-y}{\theta}\right)^n
\end{align}
That is
$$P(Y_n \le y ) =\begin{cases}  0 & , y \le 0  \\1-\left( \frac{\theta-y}{\theta}\right)^n & ,0 < y < \theta\\
1 &, y \ge \theta\end{cases}$$
Then
\begin{align}
P (n [Y_n] = 0) &= P([Y_n]=0) \\
&=P(0 \le Y_n < 1)\\
&= P(Y_n \le 1) \\
&= \begin{cases} 1-\left( \frac{\theta-1}{\theta}\right)^n & \theta > 1\\
1 &  \theta \le 1\end{cases}
\end{align}
Hence $$\lim_{n \to \infty}P (n [Y_n] = 0) = 1$$


How should I explain this code type checking in Typescript

Question: I'm confused, whether I can use Everyday Types to explain this problem?
interface IUser {
  name: string;
  age: number;
}

function fn(user: IUser): void {}

const user = { name: 'bob', age: 18, height: 188 };
fn({ name: 'bob', age: 18, height: 188 }); // error!
fn(user); // no error

Comment: See https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks
Comment: @ShivamSingla Thank you!
Answer: The error comes from Typescript telling you that you are creating a new object there with data that is not needed.
When you use an already created object that fulfils your interface but has another values, it could be a child class or another interface that extends your interface, so having extra items there is the wanted behaviour.
On the other hand, creating a new object on the fly with extra parameters is a sign that you think fn needs a different kind of object to work properly.
Comment: Thank you reply, I get  some useful information.


Validating Personalized Pagerank Matrix computation in R

Question: My question is with reference to this paper here
This is an excerpt from the paper

From the similarity of the two equations we can see that if ppr_alpha_u is added up it will be equal to pr_alpha
However while trying to execute this in R my results do not seem to comply
I am providing the code below
graph <- graph.formula(A -+ B, A -+ C, A -+ D,
                   B -+ A, B -+ D,
                   C -+ A,
                   D -+ C, D -+ B)

The global page rank is given by
> page_rank(graph,vids=V(graph),directed=T,damping = .8)
$vector
        A         B         C         D
0.3214286 0.2261905 0.2261905 0.2261905

$value
[1] 1

$options
NULL

The personalized page ranks are given by
> page_rank(graph,vids=V(graph),directed=T,damping=.8,personalized = c(1,0,0,0))
$vector
        A         B         C         D
0.4285714 0.1904762 0.1904762 0.1904762

$value
[1] 1

$options
NULL

> page_rank(graph,vids=V(graph),directed=T,damping=.8,personalized = c(0,1,0,0))
$vector
        A         B         C         D
0.2693878 0.3578231 0.1578231 0.2149660

$value
[1] 1

$options
NULL

> page_rank(graph,vids=V(graph),directed=T,damping=.8,personalized = c(0,0,1,0))
$vector
        A         B         C         D
0.3428571 0.1523810 0.3523810 0.1523810

$value
[1] 1

$options
NULL

> page_rank(graph,vids=V(graph),directed=T,damping=.8,personalized = c(0,0,0,1))
$vector
        A         B         C         D
0.2448980 0.2040816 0.2040816 0.3469388

$value
[1] 1

$options
NULL

We see from the vectors of personalized pagerank that they are not adding upto the global pagerank.
Any help in understanding why this is happening will be greatly appreciated.
Answer: You just have to normalize the results, keeping in mind that all Page Rank vectors add up to 1, both the "normal" and the "personalized" Page Ranks.
vpr <- page.rank(g, vids=V(g),
                 directed=T,damping=0.80)$vector

v1 <- page.rank(g, vids=V(g),
                directed=T, damping=.8,
                personalized = c(1,0,0,0))$vector

v2 <- page.rank(g, vids=V(g),
                directed=T, damping=.8,
                personalized = c(0,1,0,0))$vector

v3 <- page.rank(g, vids=V(g),
                directed=T, damping=.8,
                personalized = c(0,0,1,0))$vector

v4 <- page.rank(g, vids=V(g),
                directed=T, damping=.8,
                personalized = c(0,0,0,1))$vector

And the results,
> vpr
        A         B         C         D
0.3214286 0.2261905 0.2261905 0.2261905
> (v1 + v2 + v3 + v4) / 4
        A         B         C         D
0.3214286 0.2261905 0.2261905 0.2261905
> v1
        A         B         C         D
0.4285714 0.1904762 0.1904762 0.1904762
> v2
        A         B         C         D
0.2693878 0.3578231 0.1578231 0.2149660
> v3
        A         B         C         D
0.3428571 0.1523810 0.3523810 0.1523810
> v4
        A         B         C         D
0.2448980 0.2040816 0.2040816 0.3469388

Hope it helps.
Comment: You're more than welcome!


Center position of an orthogonal rectangle that has a side or corner touching a circumference

Question: I need to find how distant the center of an orthogonal rectangle is from the center of a circle, given a specific angle.
The dimensions of the rectangle are proportional to the circle radius, so they use a 0-1 range, where 1 is the radius of the circle. The objective is to get the position of the center of that rectangle, knowing its size, so that when an angle is given one of its corner (or sides) is exactly on the circumference.
To clarify, here are three image examples.
Here is a rectangle that touches the circle on one of its sides:

The same rectangle, with a different angle, now touching the circle at one of its corners:

Another rectangle, with the same angle as the last, showing a different position for its center:

The above is just an example, the final purpose is to get an arbitrary function, no matter the angle: I'm actually trying to put a given text as close as possible to the circle. The bounding rectangle of the text is known (its size is proportional to the circle radius), and I need to know where that rectangle can be placed in order to make it as close as possible to the circle.
Note that I don't need the position in the circumference at a given angle (I know I can use sine/cosine for that). I specifically need the position of the rectangle with its center placed in the line that goes from the center of the circle, with the given angle.
What I cannot understand is how to find the geometry of the rectangle, getting its center is obviously a consequence (or, maybe, getting the geometry is, once the center is found?).
I have limited math knowledge, I've tried to use my basic trigonometry skills, but I failed.
My initial intuition was to just place the rectangle at one of its sides for orthogonal angles and then use the law of sines, along with the tangent of the circumcircle of the rectangle, for other cases, but then I realized that, depending on the ratio between the rectangle size (thus, its diagonals) and the radius, there are cases where the contact point is still on one side of the rectangle, not on its corners. Still, I wasn't able to get the logical link between any of them.
Expanding the first image example, I realize that I cannot rely on the circumcircle:

I'd still settle for a corner based solution, though, as this may suffice, even if not optimal like the following:

Due to the limited knowledge noted above, I'm also not well versed in math symbols, so while I'd appreciate any answer (and then try to find my way to understand standard syntax), I'd also be grateful for logical explanations of those answers.
Answer: I see that your problem is not so much a mere geometrically driven one, it rather is more about programming some geometric display (of given visual elements).
However I cannot understand, why you try to refer with the angle directly to the rectangle's midpoint. The geometric relevant point should be the contact point, i.e. the respective corner instead.
Thus, assuming the circle itself is origin centered, that contact point $P$ ought have coordinates
$$P\left(r\cdot\cos(\varphi );\ r\cdot\sin(\varphi )\right)$$
If your program however asks for the rectangle's midpoint $M$ instead, that one then could be given as
$$M\left(r\cdot\cos(\varphi )+\frac w2\cdot\text{sgn}(\cos(\varphi ));\ r\cdot\sin(\varphi )+\frac h2\cdot\text{sgn}(\sin(\varphi ))\right)$$
where
$$\begin{array}{cl}
r & \text{radius of circle}\\
w & \text{width of rectangle}\\
h & \text{height of rectangle}\\
\text{sgn} & \text{signum function, returning just the sign value}\ \in \{+1, -1\}
\end{array}$$
--- rk
Comment: Thank you, I initially thought that your proposal was correct, but after thinking about it it's not what I was asking. Both `P` and `M` return the position for a rectangle that touches the circumference *at* the given angle, but that wasn't my question: I need to find the position of a rectangle that has *its center* passing through the line that starts at the center of the circle and has the given angle (sorry for my terminology). If you look at my images, the dotted black line refers to the angle and intersects the center of the rectangle, and its contact point is at a different position.
Comment: I've update my question, I hope it's more clear now.
Answer:
$\mathrm{Fig.\space 1}$ shows vertex $A$ of the rectangle $ABCD$ having measurements $2\lambda r\times 2\mu r$ touching a circle of radius $r$, the center of which is located at the origin $O$ of $xy-$coordinate system. The center of the rectangle is at $M$. It is given that the line $OM$ joining the centers of the circle and the rectangle makes an angle $\phi$ with the $x-$axis. Our aim is to determine the length $OM$ in terms the known variables $r, \lambda, \mu$, and $\phi$. Although OP has stated the condition $0\lt \lambda ,\mu\le 0.5$ in his problem statement, we are going to ignore it because we found that the derived formulae are valid as long as  $\lambda ,\mu\gt 0$.
To facilitate the derivation of the sought formula, we have drawn a line parallel to $OM$ thorough the vertex $A$ to intersect the $y-$axis and the vertical line $MN$, which passes through $M$, at $G$ and $F$ respectively. This makes $\measuredangle FAE = \phi$. We also drop a perpendicular to the line $GF$ from the origin $O$ and its foot is $H$. With that we have $\measuredangle HOG = \phi$. Finally, we draw the radius $OA$ and let $OG=c$.
By considering the right-angled triangle $AEF$, we obtain,
$$FE=AE\tan\left(\phi\right)= \lambda r\tan\left(\phi\right)\quad\text{and}\tag{1}$$
$$AF=AE\sec\left(\phi\right)= \lambda r\sec\left(\phi\right).\qquad\quad\tag{2}$$
It follows from (1) that
$$MF=ME-FE=\mu r-\lambda r\tan\left(\phi\right). \tag{3}$$
Since $OGFM$ is a parallelogram, using (3), we can write,
$$c=OG=MF=\mu r-\lambda r\tan\left(\phi\right). \tag{4}$$
We also have,
$$OM=GF=GH+HA+AF. \tag{5}$$
$\triangle GHO$ is a right-angled triangle.
$${\large{\therefore}} \enspace GH=c\sin\left(\phi\right)\quad\text{and}\tag{6}.$$
$$OH= c\cos\left(\phi\right).\quad\tag{7}$$
$\triangle OHA$ is also a right-angled triangle. After applying Pythagoras's theorem, we can substitute the value of $OH$ from (7) to obtain,
$$HA=\sqrt{OA^2-OH^2}=\sqrt{r^2- c\cos\left(\phi\right)^2}.\tag{8}$$
Finally, substitution of values from (6), (7), and (2) in (5) gives the following formula.
$$OM=GF=GH+HA+AF= c\sin\left(\phi\right)+ \sqrt{r^2- c\cos\left(\phi\right)^2}+\lambda r\sec\left(\phi\right)$$
Using (3), $c$ can be eliminated from this formula and further simplifications leads to,
$$OM=r\left(\mu\sin\left(\phi\right)+\lambda\cos\left(\phi\right)+\sqrt{1-\Big(\mu\cos\left(\phi\right)-\lambda\sin\left(\phi\right)\Big)^2}\right).$$
When using this formula, OP should be careful to select the correct value for the angle $\phi$ depending on the orientation of the line that joins the two centers. As shown in $\mathrm{Fig.\space 2}$, $\phi$ is the angle between this line and the $x-$axis and must be always less than or equal to  $90^o$.

Deriving the formula for the case, in which a side of the rectangle touches the circle, is very easy. So we are not going to describe it in detail. Instead, we leave you with the $\mathrm{Fig.\space 3}$, which, we hope, helps you to analyse this case.

$\underline{\text{Added at the request of OP}}$:

Unlike the case described in detail above, there are only four possible scenarios in this case. As shown in $\mathrm{Fig.\space 4}$, any given rectangle can touch a circle only at $P$, $Q$, $U$, or $V$. The distance between the two centers, when the point of touching is at either $P$ or $U$, is given by,
$$OM=r\left(1+\lambda\right)\sec\left(\phi\right).$$
In a similar vein, when the point of touching is at either $Q$ or $V$, this distance is given by,
$$OM=r\left(1+\mu\right)\csc\left(\phi\right).$$
Here too, the angle $\phi$ between $OM$ and the $x-$axis is always less than or equal to $90^o$.
Comment: Thank you so much. I've analysed your explanation and I'm about at 90% of completely understanding it ;-) I want to really get its logic, so I'll do some sketches on my own. That said, it works perfectly fine when the sides do not touch the circle, so I tried to find out how to get those exceptions (I know it may seem elementary, but it's not immediate to me). The solution I found out was to check if $OM·\sin(\phi)<\mu r$ (then use $(1 + \lambda)/\cos(\phi)$) or if $OM·\cos(\phi)<\lambda r$ (therefore, $(1 + \mu)/\sin(\phi)$). It seems to work, but I'm not 100% sure. What do you think?


Python Selenium: No such file or directory when loading Firefox Profile

Question: I'm trying to load a FirefoxProfile with selenium in Python, in order to make use of a persistent login cookie.
profile = webdriver.FirefoxProfile(profile_directory='~/.mozilla/firefox/gu16idx8.default/')
driver = webdriver.Firefox(profile)

The frist line above throws this error:
FileNotFoundError: [Errno 2] No such file or directory: '~/.mozilla/firefox/gu16idx8.default/'

Even though the file does exist (verified with cd ~/.mozilla/firefox/gu16idx8.default/)
Any thoughts?
Answer: Try with os.path.expanduser
profile = webdriver.FirefoxProfile(os.path.expanduser("~/.mozilla/firefox/gu16idx8.default/"))
driver = webdriver.Firefox(profile)


Resposta inesperada ao capturar texto de um TextView

Question: Tenho que testar um certo TextView para ver se ele está preenchido no onCreate() da activity e caso ele esteja preenchido, tenho de trocar a imagem de um ImageButton. Estou usando o seguinte código para isso:
if (txt_photo_path.getText().toString() != null) {
        btnenviarfoto.setImageResource(R.drawable.enviarfotochecked);
        }

No entanto, o código esta rodando sempre. Decidi testar para ver o porque de o TextView sempre estar preenchido, usando o seguinte, dentro do if:
Log.w("txt_photo_path", txt_photo_path.getText().toString());

O que recebo no meu log está abaixo
09-05 12:56:53.161  14726-14726/com.ufscar.ufscar.df100fogo W/txt_photo_path﹕ [ 09-05 12:56:53.381   576:  591 I/ActivityManager ]

Por que está acontecendo isso? Como saber se o TextView está realmente vazio ou não?
Comment: `txt_photo_path.getText().toString().isEmpty()` ou `txt_photo_path.getText().toString().length() == 0` ou `txt_photo_path.getText().toString().equals("")` é melhor, nunca use comparador `==` com `String`, tome cuidado com a diferença entre `String` no `String Pool` e instâncias dela.
Comment: `txt_photo_path.getText().toString() != ""` por defeito o `TextView` está sempre preenchido com a string vazia "".
Comment: Usei `(!txt_photo_path.getText().toString().isEmpty())` e funcionou. Obrigado a todos.
Comment: O @Walkim tem razão, esqueci-me do `.equals("")`. então pode utilizar assim: `if (!txt_photo_path.getText().toString().equals("")) {` com o ponto de exclamação atrás que quer dizer *NOT equals*.
Comment: @Wakim formula uma resposta!
Answer: Aparentemente o TextView sempre esta preenchido com uma string vazia (""). Bastou trocar
if (txt_photo_path.getText().toString() != null)

por
if (!txt_photo_path.getText().toString().isEmpty())

que funcionou perfeitamente.


How to fully evaluate a multiclass classification problem?

Question: When you have a multiclass classification problem, what is the right way to evaluate it's performance?
What I usually do is to display the confusion matrix and the classification_report() offered by the scikit-learn python library.
However I wonder why nobody ever calculates the Precision vs. Recall and the ROC curves. Should they be calculated as well?
I found the following example which calculates them but when I try to reverse-engineer the problem to calculate for example the precision and recall of each class I do not get the same results as the ones from the classification_report() (as you can see here).
QUESTION: Would you be able to provide an example to have a full analysis of the performance of a multiclass classification problem?
Answer: Precision and recall are not straightforward to define and calculate in the multiclass situation, and I would argue that they can be badly misleading even in the two-class situation, since every criticism against accuracy applies equally to precision and recall. (People do disagree with me here.)
The generalization to the ROC to multiple classes is even less clear than for precision and recall.
I would always use a model that gives me predicted class membership probabilities, not hard 0-1 classifications. There is a difference between predicted probabilities of 0.98-0.01-0.01 and 0.4-0.3-0.3, even if the most likely class is the first one in both cases.
Probabilistic predictions can be evaluated using proper scoring rules. Two very common proper scoring rules that can be used in multiclass situations are the Brier and the log score.


Remembering Radio Button choices in jQuery Quiz

Question: lately I've been folowing JavaScript is Sexy tutorial and I've tried making quiz challenge.
So far I got: total score counter, results table, previous question options.
But I want to remember users input, so i'm storing his answers in an answer array.
Now here's the question: how can I check the radio button with the user answer when he uses a previousQuestion button?In other words, i want to remember user answer(the radio button he clicked) when he go back on a quiz.
Plus,to avoid cheating, if user chooses a correct answer and go use a PreviousQuestion and mark the same answer he will get score up again.How can i prevent this?
Here's the code http://jsfiddle.net/janjanjan/35jxn2j4/6/
var totalScore = 0,
questionNumber = 0,

allQuestions = [{
    question: "Who is Prime Minister of the United Kingdom?",
    choices: ["Tony Blair", "Gordon Brown", "Winston Churchill", "David Cameron"],
    correctAnswer: "David Cameron",
    answer: [""]
},
{
    question: "What is the capital city of Spain?",
    choices: ["Barcelona", "London", "Madrid", "Lisbon"],
    correctAnswer: "Madrid",
    answer: [""]
},
{
    question: "How many strings does a guitar have?",
    choices: ["Three", "Four", "Five", "Six"],
    correctAnswer: "Six",
    answer: [""]
},
{
    question: "What year did MTV launch?",
    choices: ["1980", "1992", "1984", "1979"],
    correctAnswer: "1984",
    answer: [""]
}
];

var questionDiv = $('#questionDiv');
var mainContent = $('#mainContent');
var answerDiv = $('#answerDiv');

var fadeOut = 'fadeOut';
var fadeIn = 'fadeIn';
var html = 'html';

function correctGuess(i) {

totalScore ++;
questionNumber ++;

var text = "Correct!";

var updatePage = ['
' +
    '
' + text + '
' +
    '
Total Score: ' + totalScore + '

'
];

mainContent[html](updatePage);

$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');

$('#nextButton').on('click',function() {
    if (questionNumber == allQuestions.length && totalScore <= 4 ){
    results()
    }

    else {question(questionNumber)}

})

};

var incorrectGuess = function(i) {
totalScore --;
questionNumber ++;

var text = "Wrong!";

 var updatePage = ['
' +
    '
' + text + '
' +
    '
Total Score: ' + totalScore + '

'
];

 mainContent[html](updatePage);

$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');

$('#nextButton').on('click',function() {
    if (questionNumber == allQuestions.length && totalScore <= 4 ){
    results()
    }

    else {question(questionNumber)}

});

};

function results () {

var answerDiv = $('#answerDiv');

if (totalScore == allQuestions.length )  {

    var text1 = "Congratulations,all good!";

      var result = ['
' + text1 + '
' + '
Total Score: ' +             totalScore + '
' + '<button id="restartButton">Play Again</button>'];

    answerDiv.html(result);

    $('#restartButton').on("click",function() {
        questionNumber = 0;
        totalScore = 0;
        question(questionNumber);})
}
else if (totalScore >= allQuestions.length / allQuestions.length && allQuestions.length - 1 )  {

    $('#answerDiv').empty();
    $('#answerDiv').append('
Nice score!');
    $('#answerDiv').append('
Total Score: ' + totalScore + '
' );
    $('#answerDiv').append('<button id="restartButton">Play Again</button>');
    $('#restartButton').on("click",function() {
        questionNumber = 0;
        totalScore = 0;
        question(questionNumber);})
}
else    {

    var text1 = 'Well,better luck next time...';

    var result = ['
' + text1 + '
' + '
Total Score: ' + totalScore + '
' + '<button id="restartButton">Play Again</button>'];

    answerDiv.html(result);

    $('#restartButton').on('click',function() {
        questionNumber = 0;
        totalScore = 0;
        question(questionNumber);})
 }

 }

function question(i) {

 var questionDiv = $('#questionDiv');

$('#questionDiv').fadeOut("slow");
mainContent.html('
' +
    '
Question ' + (i + 1) + '
' +
    '
' + allQuestions[i].question + '
' +
                 '<input type="radio" id="one" name="questionChoices" value="' + allQuestions[i].choices[0] + '">' + allQuestions[i].choices[0] + '</input>' +
    '<input type="radio" name="questionChoices" value="' + allQuestions[i].choices[1] + '" >' + allQuestions[i].choices[1] + '</input>' +
    '<input type="radio" name="questionChoices" value="' + allQuestions[i].choices[2] + '">' + allQuestions[i].choices[2] + '</input>' +
    '<input type="radio" name="questionChoices" value="' + allQuestions[i].choices[3] + '">' + allQuestions[i].choices[3] + '</input>' +
    '<button id="submitButton">Answer</button>' + '<button id="previousQuestion">previousQuestion</button>'
    + 'score ' + totalScore + 'question ' + questionNumber + '
'
);
$('#questionDiv').fadeIn("slow");

$('#previousQuestion').on('click', function() {

    if(questionNumber <= 0) {
        $('#previousQuestion').disable();//użyć nowszej metody JQ
    }
   else {
        questionNumber --;
        question(questionNumber)
    }

});

$('#submitButton').on('click', function() {

 var answerIndex = $('input:radio[name=questionChoices]:checked').index();
 var answer = $('input:radio[name=questionChoices]:checked').val();

console.log(answerIndex);
console.log(answer);

 allQuestions[i].answer.splice(0,1,answer);
 allQuestions[i].answer.splice(1,1,answerIndex);

console.log(allQuestions[i].answer);

    if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer && i < 4) {
         correctGuess();
    } else {
        incorrectGuess();
    }
});
};

question(questionNumber);

Comment: When I take ths, it says every answer is wrong. .
for every question.
Comment: Hey Man,thanks for help :) I've updated the JSFiddle link,now it's working as it should.

Furthermore I've figured out remembering users answers.  Hopefully i will also add a anticheating feature. I'll post a link when I'm done If you want :)
Answer: I didn't read through everything, so most of it will have to be edited to fit the exact variables.
Removing:
 var updatePage = ['
' +
    '
' + text + '
' +
    '
Total Score: ' + totalScore + '

'
];

 mainContent[html](updatePage);

$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');

and:
var text = "Correct!";
var updatePage = ['
' +
    '
' + text + '
' +
    '
Total Score: ' + totalScore + '

'
];

mainContent[html](updatePage);

$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');

and replacing them with just showing the problem should solve the problem of cheating, when they use the previous question button, you could check the raido button by adding:
$('#lastButton').on('click',function() {
    //The function to go the last question
    var questionAnswerButton1 = document.getElementById("radobutton1");
    var questionAnswerButton2 = document.getElementById("radobutton2");
    var questionAnswerButton3 = document.getElementById("radobutton3");
    var questionAnswerButton4 = document.getElementById("radobutton4");
    if(questionAnswerButton1.checked === true) {
        questionAnswer[question] = allquestions[1].choices[1];
    }
    else if(/*ETC.*/) {
        /bla bla bla
    }
}


C# api eager loading using .Find()

Question: Visual Studio created this code for me:
    // GET: api/building/5
    [ResponseType(typeof(building))]
    public IHttpActionResult Getbuilding(int id)
    {
        building building = db.buildings.Find(id);

        if (building == null)
        {
            return NotFound();
        }

        return Ok(building);
    }

Each building can have a number images. Those images live in the table buildingimages that looks like this:
| id | building_id | image   |
------------------------------
| 0  |   76        | bob.jpg |

How can I load the related images along with the building, given the above code?
I've looked around, but none of the examples look exactly like my generated code. I suspect I'm just not using the right keywords and that the answer is blindingly simple.
Answer: Is that building class generated by EntityFramework?  If so you should have added a foreign key for building_id column on the buildingimages.  Thus EntityFramework would create a collection in the building class for images.

C# api eager loading using .Find()


How do I programmatically remove a block?

Question: I have a custom module that is intended to be deployed as a pure web view, with no styling whatsoever beyond what I created in the .twig file.
I installed the Stark theme and in my local instance I went to Admin > Structure > Block layout to manually remove all the active blocks.
However, this module will be deployed and I will have to have it programmatically remove all blocks when integrated into the mobile client.
Is there a way to turn off any automatic/default activation of blocks?
Comment: Did you consider a custom theme that doesn't render any regions? So your page.html.twig only contains something like `{{ page.content }}` and nothing else?
Comment: Either that, or a custom page--path.html.twig that doesn't print those regions, hook_block_access() on your module on those pages or just build your own output with your own custom twig template and return it as a plain Response object.
Comment: @marcvangend - Thanks. I did try that a couple of different ways (altering page.html.twig and using hook_page_alter to unset all other regions) and unfortunately all the blocks just moved over to the content block. :(
Answer: You can use hook_preprocess_html(). For example, to remove the system navigation block from the "sidebar_first" region, define the following hook in your MODULE.module:
<code>function MODULE_preprocess_html(&$variables) {
  if($variables['page']['REGION']['BLOCK'])
    $variables['page']['REGION']['BLOCK']['#access'] = FALSE;
}
</code>
with REGION = sidebar_first and BLOCK = system_navigation.


Multiple voting avoidance Tornado

Question: I am developing a website with Tornado and users will be able to vote on items. These items are uploaded by other users and when they upload something I provide them with a url which can share with friends so that they can vote.
The website requires registration for those who upload items and ideally I want to keep it that way. However, it is possible for a person who is not authenticated to vote multiple times on an item because I don't know how to track what they vote! Is there any good way to go about it?
I emphasize the fact that ideally I want people to be on the website without registration!
George
Answer: Really you only have a couple options on this. All of them require the ability to track the person somehow.
If you aren't going to require authentication then you are only left with tracking against the IP to prevent anyone else from that IP from voting (A problem if people connect from a NAT based network.
The other option is setting a cookie with a unique ID assigned to them (That I would personally generate using a combination of a Hash based off their IP and a random number.) The problem with the Cookie is that if someone clears their cache they are able to vote again. This is why most places require people to be logged into an account to vote.

Multiple voting avoidance Tornado


Juggling three non-Archimedean fields

Question: I'm comparing the field of hyperreals, the Levi-Civita field and the Dehn's field for the first time. I'm not very familiar with their properties, so I'm looking for ways to understand and distinguish them.
I think Dehn's field is just a Pythagorean extension of the ordered field $\mathbb R(x)$.
The construction of the Levi-Civita field makes it appear to be an extension of $\mathbb R((x))$, where the coefficients of $x$ can be well-founded sets of rational numbers, rather than just well-founded sets of integers. So this would also extend $\mathbb R(x)$.

Does the Levi-Civita field extend Dehn's field?

I'm not comfortable with the construction of the hyperreals $^\ast\mathbb R$ yet, so I am treading lightly on how it compares to the above. Being constructed with ultrafilters, I feel like it should be huge, and I half expect that it might contain both Dehn's field and the Levi-Civita field.

Do the hyperreals extend the Levi-Civita and/or Dehn fields?

I've found unclear indications that the hyperreals extend the Levi-Civita numbers, but I wasn't able to find information on the comparison with the Dehn field.
Comment: The Dehn field is an algebraic ordered field extension of $\mathbb{R}(x)$, as such it is contained in the Levi-Civita field which contains its *real closure* (the Levi-Civita field is the *Cauchy-completion* of the real closure of the Cauchy-completion of $\mathbb{R}(x)$). The other intermediate steps are from smallest to biggest *Laurent series* and *Puiseux series*.
(I used several key-words which I suggest you look up: and I would add Hahn series)
Comment: (continued) As for hyperreal numbers defined using the ultrapower construction, they contain any ordered field of *germs* at infinity of real valued functions, hence the Dehn field. The Levi-Civita field is not such a field as far as I know, but since the field of hyperreal numbers is countably saturated and real closed, it also contains Cauchy-completions of its subfields with countable cofinality, so it contains the Levi-Civita field, but not in a canonical way (as far as I know). I can explain this in more detail if you tell me which of those notions you know.
Comment: @nombre Oh!  I had another question I was about to ask about the Levi-Civita construction asking what to call that completion process, but it seems you've anticipated it!  I didn't have a real term for "making the passage from k[x] to k[[x]] to k((x))" that works for (semi)group rings instead of just the semigroup ring k[x] :)
Comment: @nombre So is this what you mean: in the Levi-Civita style construction, you could use well-founded sequences of integers (Laurent series) and then well-founded Puiseux sequences, and then these well-founded sequences of rationals?
Comment: @nombre and also a field of Hahn series between Levi-Civita and the hyperreals?  You really *must* write a solution... please!  I can't believe nobody ever talked with me about this circle of ideas before. It's very interesting.,
Comment: I'll try to write something addressing your questions if nobody answers before, but tomorrow (french time).
Answer: $\DeclareMathOperator{\cof}{cof}$The Dehn field embeds naturally into the Levi-Civita field and fields $^*\mathbb{R}$ of hyperreal numbers defined by ultrafilters on $\mathbb{N}$, and the Levi-Civita field embeds into $^*\mathbb{R}$.
I'll try to explain this in some detail. I assume you are familiar with the notion of ordered Hahn series fields and I first introduce what I called Cauchy-completion. You'll find a discussion about it here.

Any linear order $X$ is equipped with a topology, called the order topology, whose open sets are the unions of open intervals. In ZFC, $X$ has a cofinality $\cof(X)$ which is the least order type of a cofinal subset of $X$. If $F$ is an ordered field, then there is also a natural uniform structure on $F$ and in particular a notion of Cauchy sequence (same as regular Cauchy sequences but indexed by $\cof(F)$). The topology is sequential, in that closed sets are sets which contains the limits of their convergent sequences (indexed by $\cof(F)$), and thus in general every topological notion can be stated in terms of sequences indexed by $\cof(F)$, with the usual properties: continuity is sequential continuity, and so on....
An ordered field $F$ is said Cauchy-complete if its Cauchy sequences are convergent in $F$, or equivalently if it has no proper dense (ordered field) extension.
Every ordered field $F$ has a dense Cauchy-complete extension $(\widetilde{F},\varphi)$, with the following initial and terminal properties:
(IP:) If $(I,\mu)$ is a Cauchy-complete continuous (for the order topology, equivalently, the embedding is cofinal) ordered field extension of $F$, then there is a unique morphism $\sigma: \widetilde{F} \rightarrow I$ with $\sigma \circ \varphi=\mu$.
(TP:) If $(T,\mu)$ is a dense extension of $F$, then there is a unique morphism $\sigma: T \rightarrow \widetilde{F}$ with $\varphi=\sigma \circ \mu$.
The extension $(\widetilde{F},\varphi)$ is called the Cauchy-completion of $F$.
For instance $\mathbb{R}$ is the Cauchy completion of $\mathbb{Q}$, and the field $\mathcal{L}=\mathbb{R}((\varepsilon^{\mathbb{Z}}))$ of Laurent series is the Cauchy-completion of $\mathbb{R}(\varepsilon)$. To prove this, one needs only check that this is a dense ordered field extension of this field, and that each Cauchy sequence in $\mathbb{R}(\varepsilon)$ converges in $\mathcal{L}$.

Cauchy-completion is similar real closure in that they correspond to a specific version of reflective subcategories linked to properties of extensions: algebraic extensions and dense extensions. In this answer, I give some (quite poorly written) explanation. What matters here is that the Cauchy-completion is a functorial construction.
Using the Newton polygon method, one can prove that the real closure of $\mathcal{L}$ is the ordered field $\mathcal{P}=\bigcup \limits_{n \in \mathbb{N}^{>0}} \mathbb{R}((\varepsilon^{\frac{1}{n}.\mathbb{Z}}))$ of Puiseux series. Its Cauchy-completion, which is the Levi-Civita field $\mathcal{C}$ (sorry Levi...) can be construed as the field of Hahn series $s=\sum \limits_{n \in \mathbb{N}} s_n \varepsilon^{q_n}$ where $(s_n)_{n \in \mathbb{N}}$ is a sequence of real numbers and $(q_n)_{q \in \mathbb{N}}$ is a strictly increasing and cofinal sequence of rationnal numbers. As the Cauchy-completion of a real-closed field, $\mathcal{C}$ is automatically real-closed.
Since the Dehn field $\mathcal{D}$ is an algebraic extension of $\mathbb{R}(\varepsilon)$, by the terminal property of real closure, there is a unique embedding of $\mathcal{D}$ into the real closure of $\mathbb{R}(\varepsilon)$ extending the given real closure morphism. By the initial property of real closure, this real closure enjoys a unique embedding in $\mathcal{C}$ extending the embedding $\mathbb{R}(\varepsilon) \rightarrow \mathcal{C}$.

Now let's turn to germs of real valued functions. The ring $\mathcal{G}$ of germs of real valued functions is the quotient of the set of real valued functions defined on intervals $[a,+\infty)$ for some real number $a$ by the equivalence relation $f \sim g$ iff $f(x)=g(x)$ for sufficiently big $x$.
It is a partially ordered ring under poitwise sum and product, and eventual comparison. Any (linearly) ordered subfield $F$ of $\mathcal{G}$ embeds naturally in the ultrapower $^*\mathbb{R}$ (given a free ultrafilter $U$ on $\mathbb{N}$) by sending the germ of a function $f$ defined on $[n,+\infty)$ to the class of $(0,0,...,0,f(n),f(n+1),...)$ modulo $U$ (where there are $n$ zeroes for instance).
The Dehn field is such an ordered field, or more precisely it is a field or representatives of germs of real valued functions. Thus it also embeds naturally in $^*\mathbb{R}$.
The field of Laurent series, and for that matter the Levi-Civita field, are not fields of germs of real valued functions, at least not that I know of (but maybe every Laurent series is Borel summable?). Thus I don't see how to naturally embed them into $^*\mathbb{R}$. It is possible that the saying "$^*\mathbb{R}$ extends the Levi-Civita field" is better understood as a thematic remark: the Levi-Civita can be used to do analysis although it is not archimedean, and thus "not standard" analysis, with nice properties (see this here found on Wikipedia), and fields of hyperreal numbers can be seen as the completion of this goal.

In ZFC, there are embeddings of $\mathcal{C}$ into $^*\mathbb{R}$. To see this, we can use the fact that $^*\mathbb{R}$ is real-closed and countably saturated: if $L,R$ are countable sets of hyperreal numbers with $L<R$, then there is a hyperreal number $a$ with $L<a<R$. This implies that
$(i)$: $^*\mathbb{R}$ contains a canonical copy of the real closure of each of its subfields, and
$(ii)$: $^*\mathbb{R}$ contains a copy of the Cauchy-completion of each of its subfields with countable cofinality.
The first statement follows from the initial property of real closure.
To prove the second one, consider a subfield $K$ of $^*\mathbb{R}$ with countable cofinality. The set of cofinal extensions of $K$ in $^*\mathbb{R}$ is inductive for the relation of inclusion, and has a maximal element $F$ by Zorn's lemma. Since any algebraic extension is cofinal and by the first statement, $F$ must be real-closed. Assume for contradiction that there is a non-convergent Cauchy sequence $u$ in $F$. We may also assume that we have $u_{2m}<u_{2n+1}$ for all $m,n \in \mathbb{N}$ (I let you figure this out). Let $L$ (resp. $R$) be the set of elements of the sequence which lie below (resp. above) infinitely many elements of the sequence. We have $L<R$ so there is a hyperreal number $a$ with $L<a<R$. Note that $a$ leis outside of $F$, otherwise $u$ would converge to it. I claim that the subfield $F(a)$ of $^*\mathbb{R}$ is a dense extension of $F$ where $u$ converges to $a$.
In fact, we only require that it is a cofinal extension of $F$, but density follows. Indeed, it will follow that $u$ converges to $a$. Then since $F$ is real closed, no polynomial in $F[X]$ annihilates $a$, and thus by continuity of fractions in $F(X)$ on $F(a)$ outside of their poles (true for any ordered field), for such fraction $f(X)$, the sequence $(f(u_n))_{n \in \mathbb{N}}$ converges to $f(a)$.
So let's prove that $F$ is cofinal in $F(a)$. It is easy to see that each number $P(a)$ for $P \in F[X]$ is bounded by elements of $F$. We must only check that for any non zero polynomial $Q \in F[X]$, the fraction $\frac{1}{Q(a)}$ is also bounded in $F$, that is, we must check that $Q(a)$ may not be infinitesimal with respect to $F$, denoted $Q(a)\prec_F 1$. We do so by valuation-theoretic arguments. Since $^*\mathbb{R}$ is countably saturated, in particular $F$ is bounded in $F$, and its convex hull in $^*\mathbb{R}$ is a proper convex valuation ring on $^*\mathbb{R}$ which contains $a$. By real closure of $^*\mathbb{R}$, the corresponding valued field is henselian (see for instance Theorem 3.5.16 in ADH). Assume towards a contradiction that there is $Q \in F[X]$ which is non zero with $Q(a) \prec_F 1$, and choose such polynomial $Q$ with minimal degree, hence $Q'(a)$ is not infinitesimal with respect to $F$. By henselianity, this means that there is $b \in ^*\mathbb{R}$ with $Q(b)=0$ and $a-b\prec_F 1$. The first relation yields $b \in F$ (by real closure of $F$), and the second implies that $u$ converges to $b$ in $F$: a contradiction.
Thus $F(a)$ is a cofinal extension of $F$, which contradicts the maximality of $F$. So $F$ must be Cauchy-complete. The initial property of Cauchy completion then implies that the Cauchy-completion of $K$ embeds in $F$ and thus in $^*\mathbb{R}$.
Applying those two results and starting with the fields-of-germs-style embedding $\mathbb{R}(\varepsilon) \rightarrow ^*\mathbb{R}$ with $f(\varepsilon)\sim (0,1,\frac{1}{2},\frac{1}{3},...)$, we get an embedding of Laurent series, then Puiseux series, then "Levi-Civita series" into $^*\mathbb{R}$.
(Using similar arguments as above, one can prove that the maximal subfields $F$ in $^*\mathbb{R}$ are in fact almost countably saturated (countably saturated but at $+\infty$ and $-\infty$), hence in particular spherically complete. This implies that $^*\mathbb{R}$ also contains a copy of the Hahn series field $\mathbb{R}((x^{\mathbb{R}}))$.)
Comment: @rschwieb: (continued) Maybe you could find the book *Super-real fields* by Dales and Woodin where they introduce and describe various big ordered field extending the reals, including hyperreal fields. Regarding topological and uniform notions, there is the first Bourbaki of topology. For more focus on ordered field, there are articles by Sikorski that are for instance cited in [Generalized Archimedean fields][1] which you may find interesting.

  [1]: https://projecteuclid.org/euclid.ndjfl/1093870226
Comment: @rschwieb: Not really. I don't know any book dedicated to ordered fields, and although it is certain that there are many texts written on fields of hyperreal numbers and probably a few about the Levi-Civita field, I don't know any of them. (to continue)
Comment: Better answer than I ever dared hope for :)  Do you happen to know of any good texts/articles which also cover this family of fields?
Comment: The Levi-Civita field is just the field of fractions of the monoid ring $\mathbb R[M]$ where $M$ is the additive monoid of nonnegative rationals, right? I suppose it is equally true that it's the field of fractions of the group ring $\mathbb R[\mathbb Q]$ for that matter.
Comment: @rschwieb It is the Cauchy-completion of that fraction field, any left-finite set of rational numbers can appear as the support of a Levi-Civita series.
Comment: oh right. Thanks for reminding me it is more like Laurent series.

Juggling three non-Archimedean fields


how to process a set of urls instead of one url per time?

Question: lets say i have a list of urls such as
http://stackexchange.com
https://stackoverflow.com/users/login
http://careers.stackoverflow.com
http://chat.stackoverflow.com
http://meta.stackoverflow.com
https://stackoverflow.com/about
this list is in a text file.
now i would like to process all the urls in one go. The below coding is the processor.
<code>String sourceUrlString="http://stackexchange.com";
    if (args.length==0)
      System.err.println("Using default argument of \""+sourceUrlString+'"');
    else
        sourceUrlString=args[0];
    if (sourceUrlString.indexOf(':')==-1) sourceUrlString="file:"+sourceUrlString;
    Source source=new Source(new URL(sourceUrlString));
    String renderedText=source.getRenderer().toString();
    System.out.println("\nSimple rendering of the HTML document:\n");
    System.out.println(renderedText);
</code>
as you see, the coding above only can process one url at one time where i must manually key in the url at the sourceurlstring. How do i process all of the urls in the text file in one go ?
Comment: Loon - you should probably spend some time learning basic Java programming ... before you embark on your project.
Answer:
Learn what methods are by reading this part of the Java tutorial.
Implement a method taking one URL as argument and processing it.
Learn how to read a text file by reading this part of the Java tutorial.
Implement a method to read the text file line by line, and call your first method for each line read in the file.
Answer: You need to take advantage of Multithreading.
This should get you started on the right path:  The Basics of Multiple Threads in Java
Comment: I think he needs to start by iterating before jumping into multithreading.
Comment: I don't think he means all at the same time, but rather how can he read each url from the text file.
Comment: apologies if I misunderstood. "all the urls in one go" sounded like he needed multithreading.
Comment: @Gugussee: given that the OP says that he must manually key in the url at the sourceurlstring (rather than making it an argument of the program), I'd rather think that he's looking for how to read a text file and call a method for each line.


Independent arguments for View Page and Attachment

Question: Setup:
A Views page with an Attachment
Is it possible to have the first argument in the url affect the main page only, and the second argument affect the attachment only?
e.g.
http://url.com/%1/%2
%1 is a cck field in a node.  If %1 == 'acme' the main page displays a list of all nodes where a certain cck field equals 'acme'.  It then ignores the second argument (e.g. %2 can equal anything or nothing without  affecting the page list).
%2 is an nid.  The Views page's attachment displays a single node where the nid the value of the second argument.  (Argument 1 will always be true for this node, so it can be inherited, but it doesn't have to be).
Is this possible?
I also tried by using a combination of an argument for the page and exposed filter for the attachment I could create a url like:
http://url.com/cck_field_value_to_match?nid=123
…but that still produced no results for the attachment.
…but that still prod
Answer: Personally, if you just want some content from the node at the top of a view, I'd override the Views template.
Then, in that template just use the following code to get the content:
<?php if (is_numeric(arg(2)) : ?>
  <?php $node = node_load(arg(2)); ?>
  <?php print $node->content; ?>
<?php endif; ?>

I'm pretty sure you can get attachments to inherit arguments, but they can't be used independently; all arguments will always affect the parent view.
If you have to use a view, you can always do as above, create a template, then create a 'new' view; then, embed that view inside the other using:
<?php print views_embed_view('viewname', 'displayname', arg(2); ?>

This will manually pass the third argument into the embedded view.
Answer: I could be wrong about this, but I believe that the first term in a view path cannot be a % (neither should the last term). The path you are defining is the identity for the view, not an intercept for the URL.  In other words, The view is called when its path is called and there should not be another content item with the same URL path.  You can use & as middle terms in the path and use contextual filters to read them and further filter the view.  A view page can have a contextual filter and so can the attachment.
Remember that if you have two path segments with % that it takes two contextual filters to read the second one.  Before expanding into all of that, could you provide some additional information about what you want to achieve?


Drupal and Session Limit

Question: I am using Drupal 6 with the Open Atrium distribution. Is there a problem if the same user connects from more than 100 different computers at the same time? At the moment I am unable to do a test but I would like to know if I can encounter any problem. So far I did try with 10 PCs and no problem whatsoever. Also is there a limit that I have to remove or by default there is no limit? Thank you.
Answer: There is no hardcoded limit, but sessions by default are kept in database, so user<->session queries will get slow like a hell pretty soon. Move sessions to memcache or apc if possible, and consider giving each of those 100 guys his own account.
Comment: Thank you for the answer, unfortunately I cannot give them a personal account for reasons that I can't explain here (it's not a technical reason anyway). Perhaps I need to ask another question but do you know where I can find information regarding moving a table to APC? Thx.
Comment: Google. Really. It's so easy to google for drupal's sessions in apc that I refuse to do it for you.
Comment: Forgive my question but what is the difference between having 100 different accounts and having a single account? In the end if all of these users are connected at the same moment what will change in the session table?

Drupal and Session Limit


probability that the machine has its 3rd malfunction on the 5th day, given that the machine has not had three malfunctions in the first three days.

Question:
On any given day, a certain machine has either no malfunctions or
  exactly one malfunction. The probability of malfunction on any given
  day is 0.40. Machine malfunctions on different days are mutually
  independent. Calculate the probability that the machine has its third
  malfunction on the fifth day, given that the machine has not had three
  malfunctions in the first three days.

Try:
Let $X$ be number of days until third malfunction (success). We see $X$ is binomial with $r=3$ and $p=0.4$. therefore,
$$ P(X = 5 | X > 3) = \frac{P(X=5)}{P(X>3)} = \frac{ {4 \choose 2 } 0.4^2 \cdot 0.6^3 }{1 - P(X=2)-P(X=1) } = \frac{0.20736}{1-0-0} = \boxed{0.20736} $$
is this correct?
Comment: Not quite... $P(X>3)=1-\color{red}{P(X=3)}-P(X=2)-P(X=1)-P(X=0)$.  Do not confuse $P(X>3)$ with $P(X\geq 3)$
Comment: It is also worth pointing out that $(X=5)$ is a subevent of $(X>3)$, which is why there is not an additional term being multiplied to compensate for that fact in the numerator.  Ordinarily we have $P(A\mid B)=\dfrac{P(A\cap B)}{P(B)}=\dfrac{P(A)P(B\mid A)}{P(B)}$
Answer: The beginning is correct, as per Bayes theorem we have
$$
\mathrm{P}(X = 5|X > 3) = \frac{\mathrm{P}(X = 5, X > 3)}{\mathrm{P}(X > 3)} = \frac{\mathrm{P}(X = 5)}{\mathrm{P}{(X > 3)}},
$$
since $X > 3$ always true when $X = 5$.
Now, if $X = 5$, then we have two malfunctions during first $4$ days, and the third on fifth day, so
$$
\mathrm{P}(X = 5) = \binom{4}{2}\cdot 0.4^2\cdot 0.6^2\cdot 0.4.
$$
Also we note that $\mathrm{P}(X > 3) = 1 - \sum_{x = 0}^{3}\mathrm{P}(X = x)$, and the only non-zero element is $\mathrm{P}(X = 3) = 0.4^3$. Final calculations give that $\mathrm{P}(X = 5|X > 3) \approx 0.14769$.


Repeatedly strumming one string: name and technique

Question: Is there a name or word for the action of repeatedly and quickly strumming a single string on a guitar, ukulele, lute or other similar instrument?
Answer: Tremolo. Yes, it's also the name for a wangy bar that was coined erroneously by a certain Mr. Fender. Can be performed using a pick, or 2,3 or 4 fingers.


How to chose Lamba and Fraction in an elastic net model implemented with caret train?

Question: I have this model :
<code>enet2_model <- train(
    x = train_glm[-1],
    y = train_glm[[1]],
    method     = "enet",
    preProcess = c("center", "scale"),
    metric     = "RMSE",
    maximize   = FALSE,
    trControl  = trainControl(
        method            = 'repeatedcv',
        number            = n_folds,
        repeats           = n_reps,
        search            = "grid",
        selectionFunction = "oneSE",
        savePredictions   = "final",
        seeds             = caret_seeds # note: use the same seed!!
    ),
    tuneGrid   = expand.grid(
        fraction = seq(
            from = 9e-2,
            to   = 5e-1,
            length.out = tune_length/2
        ),
        lambda = c(0, seq(
            from = 9e-3,
            to   = 1e-1,
            length.out = tune_length/2 - 1
        ))
    )
 )
</code>
I'm trying to understand by which criterion i have to choose correctly the range of lambda and Fraction looking at this kind of plot:

If you look at the plot you will notice a square in the upper left side. I want to chose the simpler model that is at one standard deviation from the best model that is clearly the one at the minimum point. The question is : how do I choose fraction and Lambda? Which criterion would you use?
In this plot I see (let's call this the 1std-model) the 1std-model to fall onto a curve that corresponds to a lambda with not the deepest minimun. So I decided to search further. So the question becomes: seeing that the 1std model falls onto a curve that does not correspond to the the curve with the deepest minimun could be a criterion to search other set of parameters to choose your lasso model?
I obtained this one and I think I could be satisfied. Am I wrong or am I thinking correctly?
Answer: It may be an old question, but for you and others, who came across elastic net in the caret package, I would rely on lambda thus your weight decay mainly:
As you can also see here in this picture, which is similar to your plot, you are looking for a general turning point, or break even:
What you have done is mainly one technique in ML, 'narrowing down the model parameters'.
Like in the image you already found that the best lambda/weight decay is between 0.01 and 0.38750 [your orange lines in the first plot]. Then you are narrowing down the weight decay further. Fraction seems mostly identical. So it seems correct for me. We do not know but just with a keen eye to be sure where our minimum exactly lies and what our required parameters exactly are.
Imagine we have a ensemble method where we highlight the depth of the trees and we set it to 10, 20, and 30 and get 10 as the best estimator. Then we could try to narrow it down e.g. max_depth >= 5 & max_depth <=10. The only theory to derive how to choose lambda or weight decay here may be in terms of coefficient shrinkage. If you know you have high coeffs and you will need some shrinkage. maybe your need a higher penalty and thus a greater lambda. The rest is simple fiddling, as rigorous as it sounds. But in caret Enet you only have fraction and lambda for the tuning grid and thats it.


Finding a path integral

Question: Consider a path
$$ L_1 \ : \quad
\frac{1}{2}+\epsilon \quad \rightarrow \quad
\frac{1}{2}+\epsilon+i(p+\epsilon) \quad \rightarrow \quad
\frac{1}{2}+i(p+\epsilon). $$
where $\epsilon>0$ is arbitrarily small and $p>0$ is fixed.

Question: Find the limit of the path integral
$$ \lim_{\epsilon\to 0^+} \Im\left(\int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds\right)$$

I tried the following:
First thought: Using fundamental theorem of calculus the path integral becomes
\begin{align*}
\int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds
&= \log\left[\left(\frac{1}{2}+i(p+\epsilon)\right)\left(-\frac{1}{2}+i(p+\epsilon)\right) \right] \\
&\quad -\log\left[\left(\frac{1}{2}+\epsilon\right)  \left(-\frac{1}{2}+\epsilon\right) \right].
\end{align*}
Hence we have
$$ \int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds
= \log\left(-(p+\epsilon)^2-\frac{1}{4}\right)-\log\left(\epsilon^2-\frac{1}{4}\right)$$
So we get
$$\lim_{\epsilon\to 0^+} \Im\left(\int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds\right) = i\pi-i\pi = 0$$
But my Professor says that the answer should be $\pi$. Please help me.
Comment: Is there a branch cut crossing on the path?
Comment: That doesn't inherently matter; if you cross a branch cut then you cannot just apply FTC from one side to the other.
Comment: Well, where is the branch cut? I guess it's on $[0,1]$?
Comment: Both the start and end points of the path are on the standard branch cut of $\log$. I think the rest of the path gives a number with positive imaginary part as the $\log$ operand so it doesn't actually cross it and the limits are $+\pi i$. But it would probably be worth a more careful integration on parameterizations of most of the path, and take the limits as the endpoints approach the actual full path, to see if there's more going on.
Comment: I won't likely have time for that for a few days, but I'll bookmark this.
Comment: Right now I suspect you're correct and the answer is zero, but the more careful way might give a different answer.
Comment: @aschepler Please tell me the answer. I will then try the question. Is it $\pi$?
Comment: I don't know...
Comment: @aschepler Yo said that "rest of the path gives a number with positive imaginary part as the log operand so it doesn't actually cross it and the limits are $+\pi i$ ." How do we get $+\pi i$?
Comment: @Ian Is the answer $\pi$?
Comment: The $+\pi i$ I mentioned are related to the two parts you have in your $i \pi - i \pi = 0$.
Answer: Note that
\begin{align*}
\operatorname{Im} \left( \int_{L_1} \frac{\mathrm{d}}{\mathrm{d}s} \log(s(s-1)) \, \mathrm{d}s \right)
&= \operatorname{Im} \left( \int_{L_1} \left( \frac{1}{s} + \frac{1}{s-1} \right) \, \mathrm{d}s \right) \\
&= \operatorname{Im} \left( \int_{L_1} \frac{1}{s} \, \mathrm{d}s \right) + \operatorname{Im} \left( \int_{L_1} \frac{1}{s-1} \, \mathrm{d}s \right).
\end{align*}
Now we invoke the following well-known fact that
$$ \operatorname{Im}\left( \int_{\gamma} \frac{\mathrm{d}z}{z - a} \right) = \text{[change of argument about $a$ along $\gamma$]} $$
for any piecewise $C^1$ path $\gamma$ not passing through $a$. This gives
\begin{align*}
\operatorname{Im} \left( \int_{L_1} \frac{1}{s} \, \mathrm{d}s \right)
&= \color{blue}{\arctan\left(2(p+\varepsilon)\right)}, \\
\operatorname{Im} \left( \int_{L_1} \frac{1}{s-1} \, \mathrm{d}s \right)
&= \color{red}{-\arctan\left(2(p+\varepsilon)\right)}, \\
\end{align*}
see the picture below as well.

Therefore, we have
$$ \operatorname{Im} \left( \int_{L_1} \frac{\mathrm{d}}{\mathrm{d}s} \log(s(s-1)) \, \mathrm{d}s \right) = 0 $$
and letting $\varepsilon \to 0^+$ still gives $0$.
Comment: Thank you. But you did not consider the branch of log?
Comment: @Ken, In my calculation I did not use logarithm at all :) You just need to compute the (signed) angle.
Comment: \begin{align*}
\operatorname{Im} \left( \int_{L_1} \frac{1}{s} \, \mathrm{d}s \right)
&= \color{blue}{\arctan\left(2(p+\varepsilon)\right)}, \\
\operatorname{Im} \left( \int_{L_1} \frac{1}{s-1} \, \mathrm{d}s \right)
&= \color{red}{-\arctan\left(2(p+\varepsilon)\right)}, \\
\end{align*}     How did we get the minus sign in second equation?
Comment: @Ken, That's exactly what I am talking about. In the first integral, for instance, as the point $P$ moves along the contour $L_1$, the "argument" of $P$ changes by $\arctan(2(p+\varepsilon))$. (Here, I am not talking about the argument as the function $\arg$. The point is that, the change of argument can be well-defined regardless of all that branch business. This is essentially because the differential $\mathrm{d}\theta$ is well-defined on $\mathbb{C}\setminus\{0\}$.)
Comment: @Ken, Of course, if the path $\gamma:[t_0,t_1]\to\mathbb{C}$ lies in a simply connected domain $U$ of $\mathbb{C}\setminus\{0\}$, then a branch of the argument can be well-defined on $U$. Moreover, for any branch choice $\operatorname{Arg}$ of the argument on $U$, we can compute: $$\operatorname{Im}\left(\int_{\gamma}\frac{\mathrm{d}z}{z}\right)=\operatorname{Arg}(\gamma(t_1))-\operatorname{Arg}(\gamma(t_0)).$$ This is indeed the case for the two integrals in my answer, and then you may make use of this observation for a quicker computation.
Comment: @Ken, For the first integral, you may choose $\mathrm{Arg}$ to be the principal argument function $\arg$ and hence we get $$\mathrm{Im}\left(\int_{L_1}\frac{\mathrm{d}z}{z}\right)=\arg\left(\frac{1}{2}+i(p+\varepsilon)\right)-\arg\left(\frac{1}{2}+\varepsilon\right)=\arctan(2(p+\varepsilon))-0.$$
Comment: For the second integral, you may choose $\mathrm{Arg}$ so that it takes values in $[0, 2\pi)$. (I.e., the branch cut is chosen as $[0,\infty)$.) Then $$\mathrm{Im}\left(\int_{L_1}\frac{\mathrm{d}z}{z-1}\right)=\operatorname{Arg}\left(-\frac{1}{2}+i(p+\varepsilon)\right)-\operatorname{Arg}\left(-\frac{1}{2}+\varepsilon\right)=\left(\pi-\arctan(2(p+\varepsilon))\right) - \pi.$$
Comment: So we cannot use directly Fundamental Theorem of Calculus? We have to take arguments?
Comment: @Ken, You can also use FToC, but with a carefully chosen branches of the complex logarithm.
Comment: Thank you. Which branch should I choose and how? Please guide me.
Comment: Nice way to do it. Also even if the path did cross the branch of the $\log$ in the original formula (presumably meaning the principal definition), the undefined derivative there would have the specified limit, so it can be ignored integrating in this way.

Finding a path integral


Adding the tag values for packages

Question: In EA there is a tag tab for packages.So from EA we can create the tag and add it to the packages.Now We want to create the tag values from addin and add it to the packages.For creating tagged values for EA.Element we have API
Element.TaggedValues.AddNew

but for packages we don't have this option.So how can we create the tagged values for packages through addin.
Answer: A package has a corresponding
Package.Element

Use that to place your tagged value for the package:
Package.Element.TaggedValues.Addnew("name", "notes")

Adding the tag values for packages


Dimension of $SO_n(\mathbb{R})$

Question:
Is there a simple proof that the dimension of $SO_n(\mathbb{R})$,
  a.k.a the group of rotations in $n$-dimensional space is $(n-1)n/2$?

It would be great to see some proofs based only on the algebraic definition:
$$R \mid \left\{ R^T=R^{-1} \land \det(R)=1 \right\}$$
or alternatively proofs invoking geometrical arguments (though I'd like to stay away from proofs using Lie Algebra methods).
Any takers?
Answer: The orthogonality condition is equivalent to the columns of $R$ being an orthonormal basis. You can pick

first column $v_1$ from $S^{n-1}$, with $(n-1)$ dimensions to choose from.
second column $v_2$ from $S^{n-1}\cap \{v_1\}^\perp = S^{n-2}$, with $(n-2)$ dimensions.
third column $v_3$ from $S^{n-1}\cap \{v_1,v_2\}^\perp = S^{n-3}$, with $(n-3)$ dimensions.

and so on, until you have $S^0$ for the last column (two vectors, of which only one gives positive determinant). The total is
$$0+1+2+\dots+(n-1) = \frac{n(n-1)}{2}$$
Answer: I don't want to work that hard.
Take any skew symmetric square matrix, $S^T = -S.$ We get $e^S \in SO_n(\mathbb R),$ and a neighborhood of the identity is automatically covered, in bijection with a neighborhood of the $0$ matrix.
Oh, $S$ and $S^T$ commute, so $e^S (e^S)^T = e^S e^{S^T} = e^{S + S^T} = e^0 = I,$ and
$\det e^S = e^{\operatorname{trace} S} = e^0 = 1.$
Comment: @nbubis, think of shyness as a lack of practice in a few specific social situations, rather than a permanent condition.
Comment: +1 for really elegant, but exactly the methods I was trying to shy away from :)

Dimension of $SO_n(\mathbb{R})$


Efficiency / Accuracy of Medical Tests for unknown diseases

Question: Context : A few days ago, a few friends and I were trying to conduct a little study on the possible distribution of number of asymptomatic people infected by COVID-19 with the help of a slightly modified version of the SIR Model. However, while trying to digest those things, a question struck me suddenly.

Let us consider an unknown disease (e.g. COVID-19) which has started breaking out recently in a community. After a few months, we have a lot of possibly infected people. Now, some researchers claim that they have devised a first-of-its-kind medical test which determines whether a person is infected or not. Suppose, we find a few people who were tested to be infected, but they didn't have any observable symptoms. The researchers claim that those persons are asymptomatic.
But it is possible that a normal person who was was tested to be infected, was actually not infected. Instead, due to some errors in the medical test procedure, some normal people are labelled as infected (and hence, asymptomatic). My question is that in scenarios like this, how can a brand claim that their vaccine is "90% effective", "95%  effective" etc. ? How do the medical companies judge how much effective their vaccine is (Ignore side-effects and other factors) ? It may happen that a normal person is tested to be infected due to an error in the medical test, and in that case, the final accuracy of the medical test is hampered.
In cases like this, does anyone know how can we find out how accurate the test is ? Is there some sort of statistical method which can answer this ?
Answer: First of all the tests for vaccines are not solely based on a PCR type of test but also on symptoms (which they separate into 'confirmed COVID-19' and 'confirmed severe COVID-19'). But anyway, since those symptoms are mild and may happen due to many other cold viruses and bacteria, let's assume that the efficiency is solely based on PCR type of tests.
Your idea seems to be the following thought: if vaccine efficiency testing is based on PCR-tests and PCR-tests are unreliable, does this make the vaccine efficiency testing unreliable?
In this answer, which is in short 'No, it is not unreliable', I would like to stress two points:

Indeed, the PCR test might be not very accurate.
If perform a test with a particular person then indeed you can not be very sure whether or not the individual person is sick/infectious/infected or not.
However, on a population level the rise or decrease in positive PCR tests does have a more accurate meaning. The probability of a type I error (claiming an anomaly, patient is sick, while it is not) will decrease a lot when the sample size is very large.
What this means for the vaccine efficiency testing: If you have two groups one treated with placebo and the other treated with vaccine and you find that they greatly differ in the number of positive PCR tests, then this will be very unlikely in the case that the vaccine has not any effect.
(I would say that we can actually reason the other way around and the vaccine proofs that the PCR test works reasonably accurate. Otherwise you can not explain the very unlikely low amount of PCR tests among vaccinated people.)

A hypothesis test is indeed not only a test for the specific scientific hypothesis, but for the entire test procedure. The statistical model relates to the outcomes (e.g. the hypothesis is that among the PCR verified infections we find the same number of people from the vaccinated group as from the placebo group).
When the hypothesis test fails, then this means we have experienced an unlikely event, an anomaly, that can not be explained given a set of assumptions.
Typically the assumption that is considered to be rejected is the null hypothesis/theory, which is the theory that there is no effect of the vaccine (and we should accept the alternative that the vaccine works).
However, there are multiple assumptions underlying the procedure that generated the data and test-results and possibly those are wrong. It might be that the null hypothesis is correct, but that the anomaly is generated because of our testing procedure or our way of analysis.

I would say that these criticisms are weak arguments against the efficiency of the vaccine (more about that in the following 3rd point).

While the PCR test might not be accurate on an individual level, it is a reasonable probe to test the amount of infections in larger groups. Discussions about the curves of positive cases and how these might relate to changes in testing procedures rather than changes in the crude amount of infections are interesting and useful. However, for the testing of the vaccine, we deal with two groups that have been treated equally and a result that is obviously an anomaly due to the treatment and not due to aspects of the testing. There are many more PCR positive tests among the placebo-treated people than among the vaccine-treated people. This is a very unlikely event that can be considered evidence that the vaccine is efficient in preventing the infection (or at least it prevents positive PCR tests).
It is clear that an anomaly has been detected. What has caused it is not clear (and the data can not tell us). By assumption we believe that it is the falsification of the null hypothesis (the null hypothesis is that the vaccine is not effective, so the falsification of that means that the vaccine is effective). But maybe the test could be the cause of the anomaly. I would consider this very unlikely. The statistical model is not very far stretched and there are not weird assumptions about the distribution of the final outcome (it is a simple binomial distribution). If you have two groups of equal size, one treated with vaccine and the other with placebo, and among the people with confirmed COVID-19 you only find a few people from the vaccine group, then this is very unlikely and should be considered an anomaly. This is not a vague result that is in some gray area. Statistically speaking there is not some alternative way to look at it that would change the probabilities such that it is not significant anymore. The results are extremely significant.

One third point that must be made, and this is not statistical anymore or is at the border of statistics:

The numbers only prove that the vaccine works (is efficient) against PCR detections and mild symptoms. I do not think that it would be useful to discuss those numbers and the statistical issues related to it. The numbers are very convincing.
The implications however are open for discussion.

How long does the immunity last?
What does the immunity mean for cross-immunity (against future coronaviruses or mutations of the current virus) and does it possibly weaken our immune system in that aspect?
How does the reduction of PCR detections translate to the protection against severe cases and protection among weaker people?
Is the immune response after vaccination stronger in comparison to the immune response from natural infection?
If the vaccine works in the tested population during summer, will it also work as effectively in another population during winter (does the test have external validity)?
Etc.

Some mathematics
If it is indeed true that the PCR tests are not very accurate, then this would actually work against the vaccines and they might be more effective than we think.
Say an infected person has a probability of 99.9% for a positive PCR test and 0.1% for a negative PCR test.
Say an non-infected person has a probability of 0.1% for a positive PCR test 99.9%  for a positive PCR test.
Those figures are actually not very bad, but I believe that there are not many indications that it is worse. If the PCR-tests would be false, then you would not find the small 0.1%-ish percentages of positive PCR-tests among non-infected populations.
Now if we have 15000 vaccinated people and 15000 placebo people. Let's assume that the virus is 100% effective (nobody get's sick) and that among the placebo people 1% get's sick during the experiment.
Then you will have 15000 non-infected vaccinated people (leading to 15 positive PCR tests), 14850 non-infected placebo people (leading to, rounded up, 15 positive PCR tests) and 150 sick placebo people (leading to, rounded up, 150 positive PCR tests). The result will be 15 positive PCR tests among the vaccinated people and 165 positive PCR tests among the placebo people. The conclusion would be that the vaccine reduces the infections from 165 down to 15, 91% effectivity, while in reality, it is 100% effective.


Simple logarithmic question (fundamentals)

Question: I'm studying Asymptotic Analysis and I need to refresh the log functions, so on this particular case:
$(log\ N)^3$ what would that be equal to? is it:
$log^3(N)$ ?   which would be $log(log(log(N)))$ right? I'm a little confused... lol
In case someone knows:
Why $f(N) = N! + 2^n$ the upper bound using Big O is: $O(N^n)$ ?
isn't N! in the long run greater than $2^n$? and why is it $n^n$ and not $2^n$?
Thank you
Comment: $(log N)^3$ is the written, equivalently, as $log^3(N)$.
Comment: Please see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for typesetting
Comment: $$log^{3}(N) = \big(log(N)\big)^{3}$$
Comment: Also, $N^n$ is an upper bound on both, $N!$, and $2^n$
Answer: $\log(N)^3$ is exactly what it appears to be: the cube of the logarithm of $N$. However, you are right to note that $\log^3(N)$ is ambiguous. The convention is that $\log^3(N) = \log(N)^3$, but it would be more consistent mathematically to have it mean $\log(\log(\log(N)))$. But it's convention that matters, so $\log^3(N) = \log(N)^3$. (And of course none of these should be confused with $\log(N^3)$.)
Your factorial question is kind of unrelated, but Stirling's approximation tells us that $n! \approx (n/e)^n\sqrt{2\pi n}$. This dominates all exponential functions, but grows slower than $n^n$. So $n! = O(n^n)$ is true, but $n! = O(a^n)$ is false for all $a$.
Comment: thank you very much, one more thing before closing it, so

log^3(N)=log(N)^3 and we can say that it's the same as:
3log(N) right?

Then what about:  log(N^3) ? there is no way to separete the exponent right?
Comment: No.  It is $\log(N^3)$ that is equal to $3 \log N$.  The expression $\log(N)^3$ does not simplify further.
Comment: thank you very much, with that info I have #1 of the exam correct for sure :)


Wave Equation BC's

Question: So, I'm trying to solve the wave equation with the Fourier transform, and I'm struggling to figure out how to apply the BC's.  Here's the problem I considered:
$$\frac{d^2u}{dt^2}=c^2\frac{d^2u}{x^2}$$
$$u(x,0)=g(x)$$
$$\frac{du}{dt}=0$$ at t = 0
Running through computations, I find that the Fourier transform solution is as follows:
$$F(u(\lambda,t))=A(\lambda)e^{ic\lambda t}+B(\lambda)e^{-ic \lambda t}$$
How would I apply boundary conditions to this and then transform back to u?  ANy detailed explanation on this would be appreciated (I'm still learning this stuff).  I'm thinking it may be easier to work with cosines and sines.
Answer: You basically fourier the initial condition to get:
$\hat{u}(\lambda,0)=\hat{g}(\lambda)=A(\lambda)+B(\lambda)\Rightarrow A(\lambda)=\hat{g}(\lambda)-B(\lambda)$
$\frac{\partial\hat{u}}{\partial t}=ic\lambda A(\lambda)e^{ic\lambda t}-ic\lambda B(\lambda)e^{-ic\lambda t}=0\Rightarrow A(\lambda)=B(\lambda)e^{-2ic\lambda t}$
$\Rightarrow \hat{g}(\lambda)-B(\lambda)=B(\lambda)e^{-2ic\lambda t}\Rightarrow B(\lambda)=\large\frac{\hat{g}(\lambda)}{(1+e^{-2ic\lambda t})}$
$\Rightarrow A(\lambda)=\large\hat{g}(\lambda)-\frac{\hat{g}(\lambda)}{(1+e^{-2ic\lambda t})}$
Thus $\large\hat{u}(\lambda,t)=(\hat{g}(\lambda)-\frac{\hat{g}(\lambda)}{(1+e^{-2ic\lambda t})})e^{ic\lambda t}+(\frac{\hat{g}(\lambda)}{(1+e^{-2ic\lambda t})})e^{-ic\lambda t}$
$\large=\frac{e^{-ic\lambda t}}{1+e^{-2ic\lambda t}}+(\frac{\hat{g}(\lambda)}{(1+e^{-2ic\lambda t})})e^{-ic\lambda t}=\frac{1+\hat{g}(\lambda)e^{-ic\lambda t}}{1+e^{-2ic\lambda t}}$
Now you inverse fourier to find $u(x,t)$
Hope that helps.
Inverse fourier: (you are correct, this seems hard)
Write $\large\frac{1+\hat{g}(\lambda)e^{-ic\lambda t}}{1+e^{-2ic\lambda t}}=\frac{1}{1+e^{-2ic\lambda t}}+\frac{\hat{g}(\lambda)e^{-ic\lambda t}}{1+e^{-2ic\lambda t}}=\frac{1}{1+e^{-2ic\lambda t}}+\hat{g}(\lambda)\hat{f}(\lambda,t)$
Then $u(x,t)=F^{-1}(\frac{1}{1+e^{-2ic\lambda t}})+(\sqrt{2\pi})g(x)f(x,t)$
This simplifies things, so you need to calculate:
$\large F^{-1}(\frac{1}{1+e^{-2ic\lambda t}})$, and $\large F^{-1}(\frac{e^{-ic\lambda t}}{1+e^{-2ic\lambda t}})$
Comment: Thank you for repsonse.  That was very helpful, but I think we'd have a lot of trouble inversting that transform.  How would you go about performing a Fourier inverse on that?  Wouldn't that integral be unsolvable?
Comment: I've put in an edit that should help you to get closer, but the integration seems difficult.
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
$\ds{{\rm u}\pars{x,t} = \fermi\pars{x - ct} + {\rm h}\pars{x + ct}}$ is a general solution.

\begin{align}
\left.\partiald{{\rm u}\pars{x,t}}{t}\right\vert_{t\ =\ 0} = 0\quad\imp\quad 0=-c\fermi'\pars{x} + c{\rm h}'\pars{x}\quad\imp\quad{\rm h}\pars{x} = f\pars{x} + A\,,\quad A\ \mbox{is a constant}
\end{align}

Then, $\ds{{\rm u}\pars{x,t} = \fermi\pars{x - ct} + \fermi\pars{x + ct} + A}$

$$
{\rm u}\pars{x,0} = {\rm g}\pars{x}\quad\imp\quad
2\fermi\pars{x} + A = {\rm g}\pars{x}\quad\imp\quad\fermi\pars{x}
= {{\rm g}\pars{x} - A \over 2}
$$

$$
{\rm u}\pars{x,t}={{\rm g}\pars{x - ct} - A \over 2}
+{{\rm g}\pars{x + ct} - A \over 2} + A
$$

$$\color{#00f}{\large%
{\rm u}\pars{x,t} = \half\,\bracks{{\rm g}\pars{x - ct} + {\rm g}\pars{x + ct}}}
$$

Wave Equation BC's