A Simple Two-State Markov Chain : How to Explain a Strange Result?

Question: Context : After reading answers to my previous post (you don't need to read , this post is self sufficient)  , I obtained a strange result which I'm unable to explain .

Problem : An opera singer is due to perform a long series of concerts. Having a bad temper, singer is liable to pull out each night with probability $f(a)\in (0,1]$ . Once this has happened singer will not sing again until the promoter convinces singer of the promoter's high regard. This the promoter does by sending flowers every day until the singer returns. Flowers costing $b$ thousand GBP , $0 ≤ b ≤ 1$,
bring about a reconciliation with probability $g(b) \in (0,1] $ .The promoter stands to
make $a$ thousand GBP from each successful concert , $0 ≤ a ≤ 1$ . How much should promoter spend on flowers?

This's equivalent to finding the expected eventual daily profit then maximizing . The later is irrelevant here .
This could be solved by (thanks to user Sharky Kesa):
Suppose the opera singer has $n$ performance days . Let
$$
U_i = \left\{ \begin{array}{cc}
1 & \text{ if performance occurs on day } i \\
0 & \text{ else }
\end{array} \right.
$$
for $i\in \{1,...,n\} $ .
$(U_i)_{i\ge 0}$ is a Markov chain on state space $\{0,1\}$ .
The profit is $M = (a + b)(U_1+...+U_n) - nb $ .
We have transition matrix
$$
P^n = \begin{bmatrix}
1 - g(b) & g(b) \\
f(a) & 1 - f(a)
\end{bmatrix}^n
= \begin{bmatrix}
1 & 1 \\
1 & - \frac{f(a)}{g(b)}
\end{bmatrix}
\begin{bmatrix}
1 & 0 \\
0 & (1-f(a)-g(b))^n
\end{bmatrix}
\begin{bmatrix}
\frac{f(a)}{f(a)+g(b)} & \frac{g(b)}{f(a)+g(b)} \\
\frac{g(b)}{f(a)+g(b)} & \frac{-g(b)}{f(a)+g(b)}
\end{bmatrix}
$$
Let the distribution of $U_i$ be $u_i$ , we have
$$
u_1 = \begin{bmatrix}\frac{1}{2} &  \frac{1}{2} \end{bmatrix}
$$
$$
\implies u_i = u_1 P^{i-1} =
\begin{bmatrix}
\frac{1}{2}\frac{ 2f(a) - (f(a)-g(b) )(  1 -f(a) - g(b) )^{i-1}   }{f(a) + g(b) } &
\frac{1}{2}\frac{ 2g(b) + (f(a)-g(b))(1-f(a)-g(b))^{i-1} }{f(a)+g(b)}
\end{bmatrix}
$$
Let $U = \lim_{i\to\infty} U_i  $  and the eventual daily profit  $D =  (a+b)U - b $ , so
$$
ED  =
\lim_{i\to \infty} (a+b)EU_i - b =
\lim_{i\to \infty} (a+b)\left( \frac{1}{2}\frac{ 2g(b) + (f(a)-g(b))(1-f(a)-g(b))^{i-1} }{f(a)+g(b)} \right) - b
$$
$f(a) , g(b) \in (0,1] \implies | 1-f(a)-g(b) | < 1$ or
$f(a)-g(b) = 0 $ so
$$
 = (a+b)\left( \frac{1}{2}\frac{ 2g(b)  }{f(a)+g(b)} \right) - b
$$
$$
 =  \frac{ ag(b)  - bf(a)  }{f(a)+g(b)}
$$
$$
 =  \frac{ a\frac{1}{f(a)}  - b\frac{1}{g(b)}  }{\frac{1}{f(a)}+\frac{1}{g(b)}}
$$
$$
=  \frac{ aEX - bEY  }{EX+EY}
$$
with $X\sim Geo(f(a)) , Y \sim Geo(g(b))$ and there's no restriction on their dependency . You could also arrive here by solving for invariant distribution and applying theorem 1.10.2 here
. How to explain this result ? e.g. Could it be explained by the 2 approaches I mentioned or does it suggest a third approach to the problem ?

A possible third approach : (thanks to user Jafego)
Instead of viewing $(U_{n})_{n\ge 0}$ as a "straight line" , warp it to form numerous cycles according to some rules  (like a spring except size of each cycle is random)  .
Each cycle has 2 components : A consecutive number of days $X\sim Geo(f(a)) $ where the promoter makes a profit $a$ thousand GBP per day . A consecutive number of days
$Y\sim Geo(g(b))$ where the promoter losses $b$ thousand GBP per day . A cycle is of length $X + Y$  . So the "sample mean" of daily profit in a cycle is $ \frac{aX-bY}{X+Y}$ .  I think this "sample mean" is also i.i.d for each cycle .   However , it has variable sample size so I'm unable to proceed from here .
This's as close as I could get to explaining the result .
Comment: Writing an answer. It may take some time, because I tend to write long answers, but I thought I'd inform you in case you need to let me know anything more before I finish. Thanks.
Comment: @SarveshRavichandranIyer Thanks , I've tried to include everything  I know in this post  .  Maybe another thing is I found that numerically $ E\left[\frac{.75X-bY}{X+Y}\right] = \frac{.75E[X]-bE[Y]}{E[X]+E[Y]} $ is unlikely true .
Answer: Setup(Start all over)
For starters, let me get the setup right. You have a Markov chain which is as follows : given some real numbers $a,b$, the Markov chain $U_i$ is on the state space $\{0,1\}$ , and has transition matrix equal to $$
P = \begin{pmatrix}
1-g(b) & g(b) \\
f(a) & 1-f(a)
\end{pmatrix}
$$
where the process being at $0$ at time $t$ is equivalent to the assertion that the singer did not perform on the $t$th day of the concert. Let $M_n$ be the "profit after $n$ days" defined by $$
M_n = (a+b)(U_0+\ldots+U_n) - nb
$$
and we would like to study $M_n$.
Oh, and the singer is Miley Cyrus. And we are organizing the concert. Both of us. For the uninitiated, I will drop some references to some of her songs as I'm part of her free promotion as well. This answer is more about math and less about Miley, though.
For the sake of clarity , let's assume that we start looking at our profits from the first day Miley sings (is "on a roll?"), i.e. let $U_0 = 1$. If Miley is in a bad mood on the day we start looking at our profits, then $U_0=0$. Thankfully, in the limit the analysis is very similar, so it doesn't matter what Miley does on the "zeroth" day (Side Note : I'm starting the Markov Chain $U$ from time $0$ , so that $U_0$ is the beginning and not $U_1$. This is in accordance with Norris' "Markov Chains". Similarly, $M_0 = a$ as per the definition. The book is publicly available, see here. Of course, the change of time barely changes the analysis).

A summary of what's coming
We provide three different ways of looking at the result. Each has their positives and deficiencies, but each illustrates a principle that isn't seen in the other approaches.

The first uses convenient stopping times to show that the average profit , in the limit, can be interpreted as a ratio of sums of iid random variables. Therefore, we can use the strong law of large numbers alone to deduce what the average looks like (rather than the stronger Theorem $10.2$). It is a great technique for guessing what the limit can be.

The second uses Theorem $10.2$ in conjunction with the fact that the profit has a special structure, to deduce the limit rigorously, as well as provide intuition by borrowing the intuition of Theorem $10.2$.

The third approach uses the fact that invariant measures allow us to view the Markov chain and the associated profit as a sum of identically distributed random variables, which allows us to interpret the profit very comfortably.

Note : the short form "iid" refers to "independent and identically distributed" random variables.

Approach 1 : Where does the geometric random variable come from?
The geometric random variable arises from the "holding times" of the Markov chain at the states $0$ and $1$. These two combine to produce a sequence of "first return times" along which the profit functional behaves very regularly.
Note : To clarify (I don't think Norris uses geometric random variables with explicit mention, but I can match my definition with the OP's usage), the random variable $R \sim \mbox{Geo}(p)$ for $0<p\leq 1$ satisfies $\mathbb P(R = k) = (1-p)^k p$ for $k=1,2,3,\ldots$ (in particular, $R=0$ doesn't happen and the counting starts from $1$). We have $\mathbb E[R] = \frac{1}{p}$.
Intuitively, we will look at the "runs" of $0$s and $1$s in $U_i$ (or the "singing/not singing" streaks of Miley Cyrus), using appropriate stopping times. Recall that $U_0 = 1$ by choice.
Now consider the following random variables $X_i,Y_i,R_i$ for $i \geq 1$ and $T_j$ for $j \geq 0$. Define $T_0 = 0$. Now define inductively, for $i \geq 1$, $$
X_i = \min\{k > 0 : U_{k+ T_{i-1}} = 0, U_{k+T_{i-1}-1} = 1\}\\ Y_i = \{k >0 : U_{k+T_{i-1}+X_i} = 1, U_{k+T_{i-1}+X_i-1}= 0\} \\
R_i = X_i+Y_i , T_i = T_{i-1}+R_i
$$
Providing intuitive explanations :

The Markov chain $U_i$ begins at $U_0 = 1$. $X_1$ is the first time it moves to $1$. This is basically the number of days that Miley sings for (her "first streak"), before she slides away for her first "hissy fit".

$Y_1$ is the number of days that Miley hissy fit lasts for, before she returns to the stage for her second streak.

Similarly, $X_i$ is the duration of Miley's $i$th singing streak and $Y_i$ is the duration of her $i$th hissy fit.

$R_i$ counts the number of days between consecutive returns of Miley to the stage from her hissy fits.

$T_i$ is the number of days from the start till the $i+1$th time she returns to the stage (i.e. the day after her $i$th hissy fit ends).

All this demands an example of Miley's schedule and how we calculate the above times (I'm going to delete a comment of mine where I was misleading. I tried hard to "#GetItRight" this time).
Let the sequence $U_0,U_1,U_2,\ldots$ look as follows :
$$
\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
U_0 & U_1 &U_2 & U_3 & U_4 & U_5 & U_6 & U_7&U_8&U_9&U_{10} & U_{11} & U_{12} & U_{13} & U_{14} & U_{15} & U_{16} & U_{17} & U_{18} & U_{19} & U_{20} & \ldots \\ \hline
1&1&0&0&0&1&1&1&1&0&1&0&1&1&1&0&0&0&0&0&1&\ldots \\ \hline
\end{array}
$$
Then we have :

$X_1 = 2, Y_1 = 3, X_2 = 4, Y_2 = 1, X_3 = 1, Y_3 = 1, X_4 = 3, Y_4 = 5,\ldots$

$R_1 = 5, R_2 = 5, R_3 = 2, R_4 = 8,\ldots$

$T_0 = 0, T_1 = 5, T_2 = 10, T_3 = 12, T_{4} = 20,\ldots$

Now we begin our observations.
We note that $X_i$ and $Y_i$ are independent identically distributed random variables. Why?
That's because each $X_i$ is the time the Markov chain stays at a point before going to the other one, likewise $Y_i$. By time-homogeneity, the holding times don't change based on what time you reach a state. Now, imagine that leaving the point you're currently at is a "success" and that staying at the point you're currently at is a "failure". Then, the random variable $X_i$ is actually counting the time it takes to record the "success" of exiting $1$ on the $i$th occasion, likewise $Y_i$.
However, the "Strong Markov property"(because we're trying to restart at stopping times $T_i$ instead of fixed times, Theorem 1.4.2 here) applies) tells you that each attempt to leave is independent of the previous attempts. When one performs independent trials, the time it takes to record a success is a geometric random variable! (as we defined it)
In this case, the probability of exit from $0$ to $1$ (a success in that direction) is $g(b)$, while an exit from $1$ to $0$ happens with probability $f(a)$. Therefore, the distribution of $X_i$ is $\mbox{Geo}(f(a))$ and the distribution of $Y_i$ is $\mbox{Geo}(g(b))$.
Furthermore, because of the strong Markov property, $X_i$ and $Y_i$ are iid sequences of random variables. By the disjoint blocks theorem, $R_i = X_i+Y_i$ is also a sequence of iid random variables.
(Note: I have not rigorously shown that $X_i$ are geometric with the given distribution, but I leave this as an exercise using the Strong Markov property).
Finally, $T_i$ is a sum of iid random variables.
That's how geometric random variables enter the picture. How do they relate to the $M_i$, however?

Relating $M_i$ to the $X_i,Y_i,T_i$
The relation between the $M_i$ and the $X_i,Y_i$ is captured by fact that $M_i$ is an additive functional of $U_i$. Let's define what an additive functional is in general.

Let $V_i$ be any sequence of random variables taking values in a state space $S$. Then, another sequence of random variables $N_i$ is called an additive functional of $V_i$ if the following is true : there exists a function $W : S \to \mathbb R$ such that $$
N_k = \sum_{i=1}^k W(V_i)
$$
for all $i$.

Let me put it this way : an additive functionals of $V_i$ that can be calculated purely by seeing how much time $V_i$ spent at each state, and not necessarily its entire trajectory till a certain time.
See, the trajectory contains a lot more information than just how much time was spent at each point : for example, it contains details of how the random variables $V_i$ transitioned between various states. However, $N_i$ can purely be made out by counting how many times $V_i$ was at some state, and then adding it all up with some weight function $W$ involved. You don't need to know the transitions or any other details to calculate $N_i$.
Now, the special thing about $M_i$ is that $$
M_n = \sum_{i=0}^n W(U_i)
$$
where $W(0) = -b$ and $W(1) = a$. This is basically saying that you earn a profit of $a$ each time Miley Cyrus turns up, and incur a loss of $b$ each time she decides to act like a wrecking ball and not turn up. Thus, $M_i$ is an additive functional of $U_i$.
Now, because one doesn't care about the transitions, it is clear that $M_i$ depend only upon the various holding times at each point! That's the reason why we expect $M_i$ to depend only upon the $X_i$ and $Y_i$.
Indeed, we have the following result :

$M_{T_{i+1}} = M_{T_i} + aX_i - bY_i$ for all $i \geq 0$.

I leave you to see this result. Use the additivity, and the definitions of $X_i,Y_i$ to prove this result.

This shows that $M_{T_i}$ is a sum of iid random variables, because $P_i = aX_i - bY_i$ for $i \geq 1$ is a sequence of iid random variables.

This is the key intuition in understanding how $M_i$ interacts with the holding times. It's an additive functional, and in general you expect additive functionals to interact with processes in the same way. Something very similar happens in continuous time as well.

Getting the limit random variable
Now, we use some nice facts. Rather obviously , $T_i \geq i$ for all $i \geq 0$ so $T_i \to \infty$ as $i \to \infty$.
Now, look at the ratio $$
\frac{M_{T_i}}{T_i} = \frac{M_{T_i}}{i} \frac{i}{T_i}
$$
Now, both $T_i$ and $M_{T_i}$ are the sums of independent, identically distributed random variables.  Thus, by the strong law of large numbers, we have almost surely $$
\lim_{i \to \infty} \frac{M_{T_i}}{T_i}  = \lim_{i \to \infty}\frac{M_{T_i}}{i} \lim_{i \to \infty} \frac{1}{\frac{T_i}{i}} = \frac{\mathbb E[aX_i - bY_i]}{E[R_i]} = \frac{aE[X] + bE[Y]}{E[X]+E[Y]}
$$
where $X \sim X_1, Y \sim Y_1$ and $E[R_i] = E[X_i+Y_i]= E[X]+E[Y]$. This explains, very clearly, the origin of the ratio , from the strong law of large numbers. It is somewhat incomplete, however.
Why? That's because we have only shown that $\lim_{i \to \infty} \frac{M_{T_i}}{T_i}$ exists, not that $\lim_{i \to \infty} \frac{M_{i}}{i}$ exists, right? It is the latter we desire.

Approach 2 : On why $\lim_{i \to \infty} \frac{M_i}{i}$ exists
To understand this, we go back to the theory of additive functions.
Recall what additive functions are : they depend not upon the trajectory of the process, but about how much time it spends at each point.
Here's the intuition : if we know the average amount of time a process spends at each state, then we obviously know the average amount of any additive functional in the limit, simply because that is the only information we need to determine an additive function!
Now, because Markov chains have a limit theorem for the amount of time spent at a state,  we would expect the same to be true of the average profit.
What is that limit theorem? That limit theorem is Theorem $10.2$ cited by the author. The proof of Theorem $10.2$ can be adapted for additive functions in the following manner.

Let $V_i$ be a process on a countable (can take as finite if you need) state space $S$ such that for every $s \in S$, $\lim_{i \to \infty} \frac{\#\{k \leq i : V_k = s\}}{i}$ exists and is independent of the starting distribution $V_0$. Then, for every additive functional $M_i$ of $V_i$ with associated weight function $W$ such that $\sum_{s \in S} |W(s)| < \infty$ (integrability condition), we have $$
\lim_{i \to \infty} \frac{M_i}{i} = \sum_{s \in S} \left[W(s) \lim_{i \to \infty} \frac{\#\{k \leq i : V_k = s\}}{i} \right]
$$

Now, using this result in conjunction with Theorem $10.2$ tells us instantly that $\lim_{i \to \infty} \frac{M_i}{i} = \frac{aE[X] - bE[Y]}{E[X]+E[Y]}$.
However, how is this result proved? It's proved by observing that because $M_i$ is additive, $$
M_n = \sum_{s \in S} W(s) \#\{k \leq n : V_k = s\}
$$
Now, divide by $n$ like so $$
\frac{M_n}{n} = \sum_{s \in S} W(s) \frac{\#\{k \leq n : V_k = s\}}{n}
$$
Observe that $$
\sum_{s \in S} \left|W(s) \frac{\#\{k \leq n : V_k = s\}}{n}\right| \leq \sum_{s \in S} |W(s)| < \infty
$$
so by the usual sum-limit interchange theorem, $$
\lim_{n \to \infty} \frac{M_n}{n} = \lim_{n \to \infty} \sum_{s \in S} W(s) \frac{\#\{k \leq n : V_k = s\}}{n} \\ = \sum_{s \in S} W(s) \lim_{n \to \infty} \frac{\#\{k \leq n : V_k = s\}}{n}
$$
as desired.
Note that everything done in this section is not restricted to Markov chains! Indeed, even for other kinds of processes, one can consider objects like occupation measures and additive functionals, and similar results can be obtained.
However, this clearly explains, once again, the origin of the fraction.
We must finally come "Full Circle" and look how how invariant measures interact with additive functionals to get a third way of attacking this problem.

Approach $3$ : Invariant measures and additive functionals
What a invariant measure does to a Markov chain is quite brilliant, and the most beautiful part of this exposition. Miley should look to make a song on invariant measures sometime.
I think of stationary measures in our context like this :

Can we reimagine our process in such a way that it appears, despite our flowers and profits and losses, that Miley's decisions are identically distributed across different days?

That is, can we reformat our entire model so that Miley Cyrus' intentions to sing on a certain day look just like an identically distributed sequence of Bernoulli$(p)$ random variables, for some parameter $p$?
What a stationary measure does is exactly that. It actually makes Miley's decisions appear independent of our efforts (sending here flowers and forgiveness and love). As a result, we can use the theory of identically distributed random variables to predict Miley's behavior!
Here's how it works rigorously : we find the stationary distribution by solving the equation $$
\begin{pmatrix} x_0 & x_1\end{pmatrix} = \begin{pmatrix}x_0 & x_1\end{pmatrix} \begin{pmatrix}
1-g(b) & g(b) \\
f(a) & 1-f(a)
\end{pmatrix}
$$
along with $x_0+x_1 = 1$. Solving this yields $$
x_0 = \frac{g(b)}{g(b)+f(a)} , x_1 = \frac{f(a)}{f(a)+g(b)}
$$
which is the desired invariant distribution. The point of a stationary distribution is the following fact which follows by definition of a time-homogenous Markov chain :

If $V_i$ is a Markov chain on $S$ (finite state space) with invariant distribution $\eta$, then assuming that $\mathbb P(V_0= s) = \eta(s)$, the collection $\{V_i : i \geq 0\}$ are identically distributed random variables, all distributed according to $\eta$.

Now, what happens when you have an invariant measure? The intuition is the following : because of identical distribution of the $V_i$ as $\eta$, for any $s\in S$ and $n \in \mathbb N$, we have $$
\frac{\mathbb E[\#\{k \leq n : V_k = s\}]}{n} = \sum_{i=1}^n \frac{\mathbb E[1_{V_k = s}]}{n} = \frac{n \times \mathbb P(V_0 = s)}{n} = \eta(s)
$$
and therefore, because it's just a constant sequence, $$
\lim_{n \to \infty}\frac{\mathbb E[\#\{k \leq n : V_k = s\}]}{n} = \eta(s)
$$
So, through the looking glass that is the invariant measure, we manage to obtain the quantity $V_i$. However, the same logic can be repeated with an additive functional! As a result, we have the following theorem :

Let $V_i$ be a Markov chain on finite state space $S$ with unique invariant measure $\eta$, and let $N_i$ be an additive functional of $V_i$ with weight function $W$, which satisfies $\sum_{s \in S} |W(s)| <\infty$. Suppose that $V_0 \sim \eta$. Then, we have almost surely $$
\lim_{i \to \infty} \frac{N_i}{i} = \sum_{s \in S} W(s) \eta(s)
$$

The proof is very identical to what we did in the previous section. Use the fact that $V_i$ are identically distributed if $V_0 \sim \eta$.
Using the same logic with $U_i$ and $M_i$ here,
$$
\lim_{i \to \infty} \frac{M_i}{i} = a\frac{g(b)}{f(a)+g(b)} - b\frac{f(a)}{f(a)+g(b)} = \frac{ag(b) - bf(a)}{f(a)+g(b)}
$$
Note that this doesn't explain two things :

Where the geometric random variables come from.

What happens if $V_0$ isn't distributed like $\eta$?

The first is answered by the other approaches, so don't hold me prisoner for not showing how it comes up here!
For the other question (you can skip the explanation if it's complicated, I'm not going to make it too "clear" because it is a borderline concern for this problem),  the uniqueness of the left eigenvector implies that for any $v$ which is not a scalar multiple of the left eigenvector $\pi$, the quantity $v-k\pi$ , for some scalar $k$, lies in a subspace orthogonal to the subspace generated by $\pi$. Hence, $(v-\pi)P^n \leq \lambda^n \|v-\pi\|$  where $\lambda$ is the smallest eigenvalue not equal to $1$, and this goes to $0$ as $n \to \infty$, so that $vP^n - \pi P^n \to 0$. However, $\pi P^n = \pi$, completing the proof.
Therefore, the hypothesis that $V_0 \sim \eta$ is actually unnecessary for technical reasons. Only the existence and uniqueness of $\eta$ is necessary.

Conclusion
We saw the following (and organized Miley's concert, hence multi-tasked) :

How we can interpret the profit process as an additive functional of the Markov chain.

How additive functions are related to holding times.

How the structure of additive functionals, independence of holding times and the strong law of large numbers can be used to prove limit existence along a random subsequence.

How the holding times can be used with existing holding limit theorems like Theorem $10.2$ to provide limit theorems for additive functionals in general.

How the notion of an invariant measure can instantly provide a holding limit theorem , and therefore provide a limit theorem for additive functionals.

We found some good songs for Miley(?).

A brief note on optimization (and TWO Miley Cyruses?)
For optimization, recall that $\lim_{i \to \infty} \frac{M_i}{i} = ax_0+bx_1$ from the invariant measure result, and $x_0+x_1 = 1$. So we need to maximize $ax_0 + b(1-x_0)$ over $0 \leq x_0 \leq 1$. However, this function equals $(a-b)x_0+b$.
Since $a>b$ (otherwise we're loss making all the time, and we need to find someone cheaper than Miley Cyrus. How about Ariana Grande? Shakira? I know  I'm not very good at this), the maximum is attained when $x_0$ is as close to $1$ as possible (note : if $x_0$ ever attains a value of $1$ then Miley Cyrus never throws a hissy fit. Can't be true, eh?).
So find $\frac{g(b)}{f(a)+g(b)}$ to be as large as possible, and you've maximized the result. Now, because of the monotonicity of the reward system in $x_0$, it is possible to provide, using stochastic coupling and domination methods, a proof of the fact that increasing $\frac{g(b)}{f(a)+g(b)}$ increases the average profit. However, this will take us into stochastic coupling, where we have TWO (yes, TWO) Miley Cyruses that we treat differently, and we show that one will always give us more profit than the other. Then, we introduce more and more profit methods until Miley is singing "the most" she can.
The definition of stochastic dominance and an elementary usage of it can be found here. Note that our use will be more difficult, but we can still get it to work step-by-step. Such a method will not require us to even calculate the average earnings or use Markov chain theorems. That's why it will be more powerful.
All that, however, "someday" else.
Comment: @C.C Yes, I have access to Norris' book. I'll keep this answer up because the latter parts of the answer don't use the notation $T_i$, but I'll make sure to correct the $T_i$ using Norris' notation and words. Thanks for letting me know that you use Norris, because I can then adjust this answer. However, I'm at work so I'll correct this once I return. Thanks (If you need to , kindly leave a downvote so that others can know there is some problem with the answer).
Comment: @C.C Thank you for the reference to Norris. I have used my notation, but I used his theorems for reference. I couldn't edit my answer yesterday, but my first priority was to make sure that it gets done today, and I've just done it. I tried to be as comprehensive and correct as possible this time, and I hope that there are no errors.
Comment: @C.C Sure. As $T_i \to \infty$, we know that $M_{T_i} - M_{T_0} = \sum_{k=0}^{i} M_{T_{k+1}} - M_{T_k}$, where $M_{T_{k+1}} - M_{T_k}$ is a sequence of iid random variables because of the result just at the end of the first section. Now, the SLLN tells you that if $Z_1,Z_2,\ldots$ are iid random variables with finite expectation then $\frac{Z_i}{i} \to E[Z_1]$ almost surely. You apply this to $\frac{M_{T_i}}{i}$ carefully (the $M_0/i$ will go to zero).
Comment: @C.C Yes, this is equivalent. You need to prove that $T_i < \infty$ for this, which can be done by induction. $T_0$ is finite, and $T_1 = R_1$ so you show that $R_1$ is finite (which it is because it's the sum of two geometric random variables with positive success probability), and so on.
Comment: Thanks for answering . But I'm not convinced that "$T_n$ are the number of days between the $n$th and the $n+1$th time that ..." . To me , $T_n$ is the $n$th passage time to state $1$ , also $U_i = 1$ only if $i \in \{T_0,T_1,...\}$ . Do you see the issue/misunderstanding ? Should I elaborate more ?
Comment: To me , $T_0 =1 , T_1 = 2 ,T_2 = 5  .... $ We could deal with $X,Y$ later (I think clarifying $T_i$ more important now and definition of $X,Y$ could be clearer) . Your definition of $T_i$ is similar to page 24 of Markov Chain by J.R Norris , do you have access ?
Comment: Thanks , I'm actually counting on you . I think great presentation of idea is very important to a great answer . So you may first want to see if $T_i$ helps you present your idea before clarifying .
Comment: Nice update . I don't get why one could apply strong law of large no. (SLLN) on $\lim_{i\to \infty} \frac{M_{T_i}}{i}$ just because $i\to \infty \implies T_i\to \infty$ . I don't think this's the [conventional definition](https://en.wikipedia.org/wiki/Law_of_large_numbers) of SLLN which seems to require the no. of target random variables in the sum $M_{T_i}$ to always match the  sample size $i$ . But here there's no guarantee that $T_i$ will ever equal $i$ . I've seen this kind of application of SLLN before and I thought that was "abuse of $\infty$" . I'd be glad if you could clarify .
Comment: I interpret you construction as
$
X_i = \sup\{k > 0 : U_{T_i} =1 , ... ,  U_{T_i+k-1} = 1  \} , \;
Y_i = \sup\{k > 0 : U_{T_i+X_i} = 0 , ... ,  U_{T_i+X_i+k-1} = 0 \}
$
and assume $T_i <\infty , \forall i$ to apply strong Markov property . Is this equivalent to your definition ?


Typo confusion: What theorem to prove?

Question: I'm given the following problem:

Let $f: \mathbb{R}^N \rightarrow \mathbb{R}^N$ be a contraction with
  contraction-constant $\lambda \in [0, 1)$, i.e. we have for all $x, y
 \in \mathbb{R}^N$ that
$$||f(x) - f(y)|| \leq \lambda||x-y||.$$
Let $x_0 \in \mathbb{R}^N$ and $x_n = f(x_{n-1})$ for $n \in
 \mathbb{N}$. Let further $\bar x$ be a fixed point of $f$, i.e.
  $f(\bar x) = \bar x$. Show that we have
$$||x_n - \bar x|| \leq \frac{\lambda^n}{1-\lambda}||x_0 -
 \color{red}{n_1}||$$

The red $n_1$ is obviously a typo and I'm wondering what is actually to prove here.

Should the $n_1$ be $\bar x$? In this case I'm wondering how to prove the statement. I'm able to prove $||x_n - \bar x|| \leq \lambda^n||x_0 - \bar x||$, but where does the denominator $1 - \lambda$ come from?
Should the $n_1$ be $x_1$? In this case I'm wondering how to eliminate the $\bar x$ from the equation?
Answer: Hint: $$\|x_{n+m}-x_n\|\leq \|x_{n+m}-x_{n+m-1}\|+...+\|x_{n+1}-x_n\|$$ $$\leq (\lambda ^{m-n-1}+ \lambda ^{m-1}+...+1) \|x_{n+1}-x_n\| \leq (\lambda ^{n+m-1}+ \lambda ^{m-1}+...+\lambda ^{n}) \|x_1-x_0\|$$. Compute the geometric sum and use the fact that $x_{n+m} \to \overset {-} x$ as $ m\to \infty$ by Contraction Mapping Theorem.
Comment: Thank you so much! I see where this is going. To fix the typo we use $x_1$.

Typo confusion: What theorem to prove?


Passar body em requisição GET

Question: Bom dia amigos. Como posso passar um body na requisição GET?
Tenho um API que faz uma busca por CPF em um PDF e me retorna a página em que ele se encontra. No terminal, o comando é o seguinte:
http GET http://127.0.0.1:8000/files/processed/cpf.pdf data="123.456.789-10"

Gostaria de consumir essa API com Dart/Flutter, mas não consigo passar o body na requisição. Tentei com o seguinte código:
   class PdfSearch{

      Future catchPage(String numero) async {
      Uri uri = Uri.parse("http://127.0.0.1:8000/files/processed/cpf.pdf");
      http.Request request = http.Request("GET", uri);
      request.body = '{"data": $numero}';
      final response = request.send().asStream().first;

  }

}

Sem sucesso...
Answer: Endpoints GET originalmente não deveriam conter body na requisição, é justamente por isso que o método http.get() não tem um parâmetro body. Pois ele é simplesmente ignorado.
Future<Response> get(Uri url,{Map<String, String>? headers})

Se ele é necessário, isso pode indicar um bad design na criação da API.
No seu caso, seria mais indicado a utilização de queryParams:
http://127.0.0.1:8000/files/processed/cpf.pdf?cpf=12345678910

Ferramentas que fazem cache de APIs por exemplo, se utilizam da url para isso.
Assim, é possível passar os dados na url utilizando o seu próprio código.

Passar body em requisição GET


How do I visualize a tree dfs traversal?

Question: I kind of have the intuition of its traversal, but I feel like I wanna visualize it even better...I want to make myself sure of the thing that tree traversal will take each and every element and terminates.
How do you visualize it?
Sorry for the naivety, but have been trying and then thought to put it up here. Thanks in advance :)
Comment: There are several ways to traverse a tree. Please add details about what traversal algorithm you are interested in.
Comment: Dfs traversal @Guyslain
Answer: Suppose we have the next tree and, therefore, the algorithm Depth first search will be performed relatively of the every vertex:

I can offer the solution of your problem as a proof, performed in C++:
#include <iostream>
#include <vector>
using namespace std;
const int maximumSize=10;
vector<int> visited(maximumSize, 0);
vector<int> graph[maximumSize];
int vertices, edges;
void createGraph()
{
    cin>>vertices>>edges;
    int vertex0, vertex1;
    for(int edge=1; edge<=edges; ++edge)
    {
        cin>>vertex0>>vertex1;
        graph[vertex0].push_back(vertex1);
        graph[vertex1].push_back(vertex0);
    }
    return;
}
void dfs(int current, int previous)
{
    if(visited[current]==1)
    {
        return;
    }
    visited[current]=1;
    cout<<"Current vertex is <- "<<current<<", previous vertex is <- "<<previous<<endl;
    for(int next : graph[current])
    {
        if(next==previous)
        {
            continue;
        }
        dfs(next, current);
    }
    return;
}
void solve()
{
    createGraph();
    dfs(1, 0);
    return;
}
int main()
{
    solve();
    return 0;
}

Input:
6 5
1 2
2 3
2 4
1 6
6 5

Output:
Current vertex is <- 1, previous vertex is <- 0
Current vertex is <- 2, previous vertex is <- 1
Current vertex is <- 3, previous vertex is <- 2
Current vertex is <- 4, previous vertex is <- 2
Current vertex is <- 6, previous vertex is <- 1
Current vertex is <- 5, previous vertex is <- 6


git reset upstream branch

Question: So the master branch of my upstream repo is in bit of a mess.
Commits on upstream branch looks like below.
A - Latest commit
|
B
|
C - Bad commit
|
D - Commit I want the upstream master branch to be at.

on my forked branch I can do a git reset --hard D. But how can I apply these changes back to the upstream master branch. While creating a PR(Pull Request) from forked branch to upstream branch there are no changes shown.
NOTE: Direct commits on upstream branch is prohibited, it has to be done using a Pull Request from the Fork.
EDIT
This is how i have cloned the remote repository.
git clone http://myrepo.git
git remote add upstream http://main-repo.git

Now origin and upstream are like below.
origin - http://myrepo.git
upstream - http://main-repo.git

Forked repository is basically a mirror clone of the remote repository. On the bit bucket UI there is an option to create a fork and enable fork syncing between origin & upstream.
When I say forked branch it means that the branch which is on the forked repository.
Comment: What do you mean by upstream repository? Do you have permission to force push? If the upstream repository is not yours, then why you would like to reset other's repository?
Comment: @ChuckLu - ````origin```` would be my forked repository and ````upstream```` is the remote repository.
Comment: @ChuckLu And no permission to force push on upstream repo.
Comment: Still confused about your description, what do you mean by forked branch? It's the first time I hear it, I just know the forked repository concept on github.
Comment: Actually for the concept of repository, for example user1 have a repository1 on github,like user1/repository1. User2 forked the repository1 of user1, and user2 will get a forked repository on github user2/repository1. User2 can clone the forked user2/repository1 to local folder repository1. Here, the user1/repository1 should be the upstream repository, and user2/repository1 is a simple remote repository. Now you can make it clear in your description, which remote repository you want to change(rewrite history)?
Comment: @ChuckLu - Edited the question explaining the forked branch.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/222939/discussion-between-chuck-lu-and-mohammed-aamir-k).
Answer: If changes need to be done by pull request, you cannot remove commits.
Instead, you will want to revert; this creates a new commit, which reverses the effects of the bad one. Both changes will remain part of history.
Create a new branch as normal, then run the command: git revert hash_of_C (where you substitute the hash of commit C). Review the change, fine-tune the commit message with git commit --amend if needed, then push for review as normal.
If you absolutely need to remove the commit, you'll need to discuss that with the project lead. Editing history that's already part of upstream master is a major disruption to the whole team, most likely you'll be told to revert instead. If the project lead agrees that commit C must not be part of history, they'll probably remove it themselves, most likely by temporarily giving themselves permission to push directly to master. The whole team will need to be alerted as well.
Comment: Agreed with your point of reverting a single commit.````git revert -m has_of_C```` works as it was a merge commit. But I was thinking on the lines of reverting all commits ie C,B,A so that the upstream repository is clean and at commit D. Could something like this be achieved.
In my scenario right now between A and D there are around 32 commits which include merges too and the direct commits are just package updates. So there is no objection in reverting all the commits.
Comment: That would require force-pushing to the already-published master branch. Only the project lead can approve that.
Answer: The operation you want is a git push with --force, and since you do not have permission to do this.
Then the alternative operation could a revert operation, and there is an elegant solution for you to revert multi commits.
How to revert multiple git commits?

git reset upstream branch


Oracle EE 11.2g: how to generate fresh new redo logs

Question: In the company I work for we are heavy users of VMware machines. Almost all our projects are developed inside a virtual environment up to the point where we have to deploy them into a production system.
While in development, some colleagues of mine deleted the redo log files for Oracle in the hopes of gaining some free space. Now they are unable to start the database instance. Is there a way of generating a fresh new redo log so that the instance can be started?
Answer: There are two types of redo logs, online and archive. You can restart without the archived ones. The online ones are a different matter. You need to use the RESETLOGS option
http://www.stanford.edu/dept/itss/docs/oracle/10gR2/backup.102/b14191/osrecov009.htm
Comment: It seems my colleagues tried using the RESETLOGS option but with no luck. Thanks for your help nonetheless.


Error:java.lang.RuntimeException: proguard - release (app:transformClassesAndResourcesWithProguardForRelease)

Question: I tried all the options that exist in Google but nothing helped.
on gradle 1.3 version of the project was going to but when all the ones on during assembly 2,2,3 release version error.
Error when proguard enable:
<code>    Error:java.lang.NullPointerException
Warning:The interface com/github/tibolte/agendacalendarview/agenda/IAgendaHeaderView has a static method "inflate" but backporting default methods is not enabled
Warning:Exception while processing task java.io.IOException: java.lang.NullPointerException
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: java.lang.NullPointerException
</code>
Gradle:
<code>   android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    useLibrary 'org.apache.http.legacy'
    signingConfigs {
        releaseConfig {
            storeFile file("test.jks")
            storePassword "test"
            keyAlias "test"
            keyPassword "test"
        }
    }

    defaultConfig {
        applicationId "by.test.by"
        minSdkVersion 15
        targetSdkVersion 25
        // versionCode 1
        versionName project.props.version

        multiDexEnabled true
    }

    lintOptions {
        abortOnError false
        checkReleaseBuilds false
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.releaseConfig
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    dexOptions {
//        incremental false
        javaMaxHeapSize "2048m"
        preDexLibraries = false
</code>
Proguard rules:
<code> -dontwarn by.mrsoft.mrdoc.**
-dontwarn com.radaee.**
-dontwarn okio.**
-dontwarn org.joda.time.**
-adaptresourcefilenames
-adaptresourcefilecontents
-keepdirectories
-keep class android.support.v7.** { *; }
-keep class android.support.graphics.drawable.** { *; }

-assumenosideeffects class * {
 @by.mrsoft.mrdoc.model.System.OnlyDebug *;
}

-keep class org.kxml2.** { *; }
-keep class org.acra.** { *; }
# исключение Radaee
-keep class com.radaee.** { *; }

#-keep class by.mrsoft.mrdoc.** { *; }

-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }

-keepclasseswithmembernames class * {
    @butterknife.* <fields>;
}

-keepclasseswithmembernames class * {
    @butterknife.* <methods>;
}

-keep class com.feitian.** { *; }
-keep class org.pkcs11.** { *; }
-keep class ru.aladdin.** { *; }
-keep class by.mrsoft.mrdoc.Eds.** { *; }

#-keep class java.awt.** { *; }
#-keep class javax.naming.** { *; }
#-keep class org.spongycastle.** { *; }
#-libraryjars <java.home>/lib/rt.jar
-dontwarn java.awt.**
-dontwarn javax.naming.**
-keep class com.sun.** { *; }
-keep class ru.rutoken.** { *; }

-keep class ru.CryptoPro.** { *; }
-keep class javax.** { *; }
-keep class com.intellij.** { *; }
-keep class org.apache.** { *; }
-dontwarn ru.CryptoPro.**
-optimizationpasses 1
#-optimizations !code/allocation/variable,

-dontwarn org.apache.**
-keep class org.apache.** { *; }

-keepclasseswithmembernames class * {
    native <methods>;
}

-keep class android.support.design.widget.** { *; }
-keep interface android.support.design.widget.** { *; }
-dontwarn android.support.design.**
</code>
Error in gradle:
FAILURE: Build failed with an exception.
<code>* What went wrong:
Execution failed for task ':app:transformClassesAndResourcesWithProguardForRelease'.
> Job failed, see logs for details

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesAndResourcesWithProguardForRelease'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: Job failed, see logs for details
    at com.android.build.gradle.internal.transforms.ProGuardTransform.transform(ProGuardTransform.java:196)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:178)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:174)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:156)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:173)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:245)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:232)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 14 more
Caused by: java.io.IOException: java.lang.NullPointerException
    at com.android.build.gradle.internal.transforms.ProGuardTransform.doMinification(ProGuardTransform.java:283)
    at com.android.build.gradle.internal.transforms.ProGuardTransform.access$000(ProGuardTransform.java:63)
    at com.android.build.gradle.internal.transforms.ProGuardTransform$1.run(ProGuardTransform.java:173)
    at com.android.builder.tasks.Job.runTask(Job.java:49)
    at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
    at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:223)
Caused by: java.lang.NullPointerException
    at proguard.util.FixedStringMatcher.matches(FixedStringMatcher.java:52)
    at proguard.util.OrMatcher.matches(OrMatcher.java:46)
    at proguard.classfile.util.WarningPrinter.accepts(WarningPrinter.java:89)
    at proguard.classfile.util.WarningPrinter.print(WarningPrinter.java:77)
    at proguard.AssumeNoSideEffectsChecker.checkClassSpecifications(AssumeNoSideEffectsChecker.java:86)
    at proguard.ConfigurationChecker.check(ConfigurationChecker.java:141)
    at proguard.ProGuard.execute(ProGuard.java:73)
    at com.android.build.gradle.internal.transforms.BaseProguardAction.runProguard(BaseProguardAction.java:54)
    at com.android.build.gradle.internal.transforms.ProGuardTransform.doMinification(ProGuardTransform.java:254)
    ... 5 more
</code>
Answer: Try disabling 'Instant Run' if enabled and rebuild the project. Also, see if everything is set as per the instructions given here:
https://developer.android.com/guide/platform/j8-jack.html
Comment: not help, error
`Error:java.lang.NullPointerException
Error:java.io.IOException: java.lang.NullPointerException
Error:java.lang.RuntimeException: Job failed, see logs for details
Warning:Exception while processing task java.io.IOException: java.lang.NullPointerException
Warning:The interface com/github/tibolte/agendacalendarview/agenda/IAgendaHeaderView has a static method "inflate" but backporting default methods is not enabled`
Comment: Compiling with Java 8 might be causing the issues, since its neither fully supported nor backward compatible. Try going through this and see if everything is set properly.https://developer.android.com/guide/platform/j8-jack.html
Comment: @ Suhayl SH
your answer as the Council has not helped


How to put a token in field Simplenews -> Subscribtion block -> block message

Question: I want to add a token in a field which is used when the simplenews module is installed and configured. There is then a block available for each newsletter.
In this block the user can fill in his email and push the subsribe button.
I want to display a token in this field:

Block > Simplenews subscribption block > block message.

(the block title is supporting tokens, but the block message not)
How to do this?
Answer: It's likely there's no off-the-shelf solution here. The block message field is a variable in the Simplenews module. It's not possible to make variables dynamic; there's no hook to override variable values.
In order to make something like this happen, you'd have to use a combination hook_form_alter() to change the block setting form & hook_block_view_alter() to alter the output of the Simplenews block.
Comment: Oke, I never did this so I will try. I guess I have to make a custom module with this methods to override the current behavior.


What's a good way to split a 'item_list' into two columns?

Question: I'm working in a custom module that will output to my custom theme in D7. This theme & module will never be used apart.
Say I have a simple list in a block (six items), I want it split into two adjacent columns of three items...

Can this be done only with CSS? (just curious, not a constraint)
What seems easier; should I render two lists & just float the second right?
Answer: You can do this just using CSS by giving the list items a width and floating left:
.list-class li { width: 50%; float: left; }

You might need to adjust the width to a static number depending on the padding you have on the
s.
Comment: Yep, the above (with a static width) worked perfect


Triggering onclick button with Python mechanize

Question: So,here's the problem:
I got a form that gives an info. The form has only one field and i can easily write inside anything using .select_form and .form functions of mechanize.
However the submit func.doesn't work as well as it should.
How can i click the onclick button using mechanize?
I know it's JS but it should be a proper way to do it also in Py.
This is the HTML code of the form:
<input type="text" name="P_COD" value="IT001990225863" class="textbox2" maxlength=14 size=20 onblur="this.value=this.value.toUpperCase()">

<input TYPE="button" VALUE="Search" onclick="query()" class="pulsante">

I've tried also br.click('Search'), it correctly point to the button, but gives the following error: ControlNotFoundError: no control matching name 'Search', kind 'clickable'
this is the list of the forms:
<HiddenControl(P_CAP=BOV) (readonly)>
  <HiddenControl(P_COD_S=) (readonly)>
  <TextControl(P_COD=IT001990225863)>
  <IgnoreControl(<None>=<None>)>>

Answer: You will need to use something like Selenium, or else a headless browser, to run JavaScript on your pages. Mechanize does not have a JavaScript engine built-in.
Comment: Ok, i'll try using Selenium. I'll let you know.


Server 2016 Tombstone Lifetime

Question: Does anybody know what the default tombstone lifetime for Server 2016 is?
Thanks in advance.
Comment: Seems to be "180", look here: http://www.dell.com/support/article/de/de/rc1210960/sln283178/windows-server-understanding-and-modifying-the-active-directory-tombstone-lifetime?lang=en
Comment: Seems like you're right buddy
Comment: From the @boboes' link: _In the Attribute Editor tab of the properties window, locate the `tombstoneLifetime` attribute. The value of this attribute represents the forest's current tombstone lifetime in days. If the attribute's value shows_ ****, _the tombstone lifetime of the forest is **60 days**._
Answer: You can check your forest's value by launching the ADSI edit tool (ADSIEDIT.msc) and browsing the Configuration partition for the AD forest. Navigate to CN=Directory Service, CN=Windows NT, CN=Services, CN=Configuration, DC=domain, DC=com. Right-click the CN=Directory Service object and select Properties. Look for the tombstoneLifetime value. 2016 Server is 180 Days. Hope this helps!

Server 2016 Tombstone Lifetime


Custom view for Entityform submission

Question: I have a simple Entityform where the user selects from a list of Profile2 user profiles (internal staff and external staff). In simpler terms, the user selects from a list of entities (ie. pick 3 from a list of 10).
The Profile2 user profiles are being shown on the form via an Entity reference view so you can see the name (from user profile), picture (from user profile), status (from Profile2 staff profile) etc. associated with the selected users.
Unfortunately, the submission confirmation and submission screens only show the entity name (User Profile) instead of the actual user profile details. Basically I see:
<code>Submitted by There, Hello on Thu, 03/05/2015 - 10:53
Person Selection
External Staff
Internal Staff
</code>
What I want to show is:
<code>(picture) Joe Schmoe, Washington
(picture) Alex Trebec, Montreal
</code>
Does anyone know how to alter the confirmation and submission pages to show more detail about the underlying Entity (and/or associated Entity)?
Answer: Here is what I would suggest.

Clone the built in View
In the Entityform Type edit form select your new View under Submission Views -> View for submissions reports
In your new View add relationship to Profile2 entity via the Entity Reference field on the Entityform
Now you can add any field from the Profile2 to the View.

Custom view for Entityform submission


How to deploy C# DLL of hidden NuGet dependency automatically when mixing .Net Standard and .Net Framework?

Question: I have a Visual Studio (2017) C# solution which is structured like this:

Solution

ExeProject
DLLProject

NuGet-Dependency to Stateless package ("Stateless" is the name of the package)

The DLLProject hides the dependency within its interfaces, i.e. the usage of the Stateless library is supposed to be an implementation detail of DLLProject.
The ExeProject accesses only the public interfaces and factories of DLLProject.
Due to reasons which go beyond the scope of this question, ExeProject targets .Net Framework 4.6.1, while DLLProject targets .Net Standard 2.0.
This compiles fine, but when debugging, the Stateless.dll is not found by the executable.
Is it possible to automatically deploy that DLL when linking against DLLProject without adding a Stateless NuGet dependency to the ExeProject?
Comment: Why do you want to avoid adding a nuget dependency?  This is exactly what they are designed for.
Comment: @BradleyUffner Maintainability, Compatibility, Testability, Interface Segregation etc. I want to be able to alter/switch out/remove the library in question without having to modify the `ExeProject`. It's not that important in the minimal example I provided, but the real task at hand has multiple of these issues.
Comment: Can you make DLLProject .Net Framework 4.6.1? Should "just work" if its all in the same solution.
Comment: @mxmissile `DLLProject` is additionally used in environments where .Net Framework is not available, so unfortunately, no.
Answer: In .NET Core this transitive NuGet dependencies work automatically.
On .NET Framework, there is a "Copy Local" option for referenced libraries. Make sure that it is set to True for the problematic one.
Update
For your case, .NET Framework App and .NET Standard lib, the setup requires manual modification of the .NET Framework app's .csproj file. Please follow:
Copy all dependencies from .Net Standard libraries to .Net Framework Console application
Comment: My Exe project targets.NET Framework (it targets Desktops specifically) while the DLL targets .Net Standard. I updated the question to include that detail. Any chance to get it to work automatically in that case?
Comment: Updated the answer.


Can't see my chromecast in the available receiver list using my APP-ID

Question: I'm trying to test some chromecast examples using chrome, but can't see the chromecast in the available receiver list for my APP-ID.
This is my situation,

My chromecast device is whitelisted. I received my APP-ID associated with my receiver urls.
I can get access to my receiver url, using the browser and it is exactly the same url associated with my App ID.
The receiver.html has something like this:

var receiver = new cast.receiver.Receiver(
        'APP-ID',
        ['Test'],
        "",
        5);
The APP-ID is the one I received when I whitelisted the chromecast device.

The receiver.html is hosted with a public ip. It is accessible for everyone.
The sender.html:
var appId = "APP-ID";
$window.addEventListener("message", function(event) {
if (event.source == window && event.data &&
    event.data.source == "CastApi" &&
    event.data.event == "Hello") {
  $log.info("CastApi Hello message received!");
  initializeApi();
}

});
var initializeApi = function() {
cast_api = new cast.Api();
cast_api.addReceiverListener(appId, **onReceiverList**);

};
var onReceiverList = function(list) {
$scope.receivers = list;
var fn = list.length ? $log.info : $log.warn;
fn("Receivers: ", list);
$scope.$apply();

};

THE PROBLEM is the receiver list is always empty!!!

The sender.html is hosted in my localhost server and I whitelisted it with the word "localhost" in the option page of chromecast extension.
I check the option "Send this Chromecast's serial number when checking for updates" when I was setting up the chromecast the first time with Chrome (No Android). I'm able to access to debug mode using the url http://MY-CHROMECAST-IP*:9222 so I'm sure it's working.

Don't know what I am missing.
Someone could help me?
Comment: Restart your ChromeCast device to make sure the serial number is sent to Google.
Comment: I did it using android app but nothing change.I am still having the same problem.
Comment: Ok, I figured out what's going on. I was running the example in ubuntu!!! when I tested in OSX it works fine!!!!!
Answer: I had this issue on windows 7 on 2 different networks.
People on OSX and Linux see an available receiver without issues.
The tab itself can see the chromecast, and all other chromecast actions on the PC works correctly, but when I ask the JS API if there is any any receiver is there, its always empty.
This is regardless of whether the app is published or not.
Seems like there is a legitimate bug in the API that needs to be addressed by Google.
Comment: Exactly the same problem here :-(
Answer: The ideal scenario would be to host the receiver locally during development so you can make and save changes and see them represented on the Chromecast device immediately without the need to push your changes to a publicly accessible server.
To achieve this I used https://meetfinch.com/ and it worked really great.  After installing and registering (which is free), run this:
finch forward http://localhost:8080


REGEX validação de senha

Question: Tenho um problema de Validação e não consigo aplicar dentro de uma estrutura simples, 3 validações não pode ter alfanuméricos  decrescentes, crescentes e nem repetidos numa mesma senha.

Por exemplo: 00000000 , 01234567 , 98765432 , aaaaaaaa, aa1123456

alguém consegue me ajudar ?
Comment: Se eu fosse seu usuário, iria agradecer se não restringisse a senha (ainda mais nesse nível). Boa sorte.
Comment: Quer disser que se meu ano de nascimento fosse 1987 eu não poderia usar ele por ser sequencia?
Comment: Quantos caracteres repetidos será considerados para dizer que a senha tenha que estra nessa validação, por exemplo a senha aa123r56, seria valida? sua senha sempre vai ser composta por 8 caracteres?
Comment: a senha aa123r56 não seria válida por existir uma sequencia  repetição em aa e 123 na mesma senha a principio sim seria 8 caracteres possivelmente irão aumentar o valor do campo.

usei uma solução anterior mas, não me atendeu bem, por conta da documentação.
Comment: Parece que detectar sequências usando regex não é possível. Veja este tópico no SOen, pode ajudar. http://stackoverflow.com/questions/8880088/regular-expression-to-match-3-or-more-consecutive-sequential-characters-and-cons
Comment: Pelo que conheço, não é possível detectar sequência de números com _regex_. É possível detectar números ou letras repetidos, como `000` ou `aaa`, mas uma sequência `123`, `987` ou `abc` não.
Answer: Pelo que conheço, não é viável detectar sequência de números com regex.
É possível detectar caracteres repetidos facilmente, como 000 ou aaa, mas uma sequência 123, 987 ou abc não.
O regex por si só, não atribui valor aos caracteres. Ele não identifica que 2 é maior que 1 ou que b é seguido de a no alfabeto.
Para fazer isso você teria que escrever todas as sequências possíveis para ele dar match em alguma delas. Como exemplo a pattern "123|12|23|321|32|21" para identificar uma sequência simples entre três números.
Para letras ou números repetidos você poderia usar um pattern que procura por ocorrências repetidas como "(\d|\w)\1+".
Nesse caso o pattern obtém uma letra ou número e logo em seguida verifica se ele se repete uma ou mais vezes.
Veja funcionando no regex101.

REGEX validação de senha


How to get archived events based on end date for a content type with a start date and end date field?

Question: Create a content type Event with fields for Start date and End date. Validate the creation of events where Start date cannot be in the past and End date cannot be less than start date. Create a View where the Start date & End date are exposed filters and end date validated as in content creation page. The View should also filter expired events (i.e. Content with expired End date) and displayed in a similar view display named Archived Events
Answer: Archived events get based on an end date.
Go to view named archived events. Then click the end date exposed filter in FILTER CRITERIA. Check Filter type to expose is single filter. Then below operator drop down box choice is less than. Next drop down box choice enter relative date. Below now shows Relative date text box give now.
Then click on Apply button.


python exe in windows not writng

Question: I have converted my python program to exe using pyinstaller. My exe creates a temporary folder _MEIxxxxx to keep files. In the same folder there is a file which is being changed by the program, but unfortunately it is not happening.
In the program I change the folder to go to above folder:
os.chdir('C:\\Users\\Public')
for foldername in os.listdir():
if foldername.startswith('_MEI'):
    myfolder = foldername
    os.chdir('C:\\Users\\Public'+myfolder+'\\Quiz')

Thanks in advance.
Comment: don't hardcode those windows directories. They may be different. Use env.variables. The error here: missing backslash. Use os.path.join
Answer: this doesn't work:
os.chdir('C:\\Users\\Public'+myfolder+'\\Quiz')

because myfolder doesn't contain a \ at start.
Don't hardcode C:\Users\Public, use PUBLIC env. var
And avoid chdir, it's equivalent as a global variable shared between all modules. What if some module needs one current dir, and the other another?
Your attempt looks more like a shell script ported to python cd xxx; ls; .... Break this habit.
Use absolute paths/paths passed as parameter instead. My proposal:
pubdir = os.getenv("PUBLIC")
for foldername in os.listdir(pubdir):
  if foldername.startswith('_MEI'):
      myfolder = foldername
      quizdir = os.path.join(pubdir,myfolder,'Quiz')
      # now do something with quizdir

and if you need an absolute directory to run a system call, subprocess functions have a cwd parameter for that. So you can avoid os.chdir 99% of the time.

python exe in windows not writng


Prove a binomial identity: $\sum_{i=1}^n i \binom{2n}{n-i}=\frac12(n+1) \binom{2n}{n-1}$

Question: I want to prove the product of even/odd power with a combinatorial number:
\begin{aligned}
  \sum_{i=1}^n i \binom{2n}{n-i}&=\frac12(n+1) \binom{2n}{n-1},  \\
  \sum_{i=1}^n i^2 \binom{2n}{n-i}&=2^{2n-2} n.
\end{aligned}
I am sure these results are correct since WolframAlpha verifies them. I wonder if the first formula can be proved, and also the general version can be proved: Formula related to combinatorial number.

Below is proof for the second formula:
First, note that $r\binom{n}{r}=n\binom{n-1}{r-1}$, and $\sum_{i=0}^n\binom{n}{i}=2^n$. We thus have
\begin{aligned}
    \sum_{i=0}^n i\binom{n}{i}&=2^{n-1}n,  \\
    \sum_{i=0}^n i^2\binom{n}{i}
    &= \sum_{i=0}^n i(i-1)\binom{n}{i}+\sum_{i=0}^n i\binom{n}{i} \\
    &= 2^{n-2}(n^2-n) + 2^{n-1} n  \\
    &= n(n+1)2^{n-2}.
\end{aligned}
Therefore,
\begin{aligned}
    \sum_{i=0}^{2n}(n-i)^2\binom{2n}{i}
    &= n^2\sum_{i=0}^{2n}\binom{2n}{i}-2n\sum_{i=0}^{2n}i\binom{2n}{i}+\sum_{i=0}^{2n}i^2 \binom{2n}{i}  \\
    &= 2^{2n}n^2-2^{2n+1}n^2+n(2n+1)2^{2n-1}  \\
    &= 2^{2n-1} n,
\end{aligned}
and thus
\begin{aligned}
    \sum_{i=0}^n i^2 \binom{2n}{n-i}
    = \sum_{i=0}^n (n-i)^2 \binom{2n}{i}
    = \frac12 \sum_{i=0}^{2n} (n-i)^2 \binom{2n}{i}
    = 2^{2n-2} n.
\end{aligned}
Answer: \begin{align}
\sum_{i=1}^n i\binom{2n}{n-i}
&= \sum_{i=0}^n i\binom{2n}{n-i} \\
&= \sum_{i=0}^n (n-i)\binom{2n}{i} \\
&= n\sum_{i=0}^n \binom{2n}{i} - \sum_{i=1}^n i\binom{2n}{i} \\
&= \frac{n}{2}\left(\binom{2n}{n}+\sum_{i=0}^{2n} \binom{2n}{i}\right) - 2n\sum_{i=1}^n \binom{2n-1}{i-1} \\
&= \frac{n}{2}\left(\binom{2n}{n}+2^{2n}\right) - 2n\sum_{i=0}^{n-1}\binom{2n-1}{i} \\
&= \frac{n}{2}\left(\binom{2n}{n}+2^{2n}\right) - \frac{2n}{2}\sum_{i=0}^{2n-1}\binom{2n-1}{i} \\
&= \frac{n}{2}\left(\binom{2n}{n}+2^{2n}\right) - n2^{2n-1}\\
&= \frac{n}{2}\binom{2n}{n}\\
&= \frac{n+1}{2}\binom{2n}{n-1}
\end{align}
Comment: Nice, that is a standard solution! Thanks!
Answer: Let $$S_n=\sum_{k=0}^{n} {2n \choose k}$$
and let
$$S'_n=\sum_{k=0}^{n} k {2n \choose n-k}=\sum_{k=0}^{n} (n-k) {2n \choose k}=nS_n-T_n$$
$$2^{2n}=\sum_{k=0}^{2n} {2n \choose k}=\sum_{k=0}^{n} {2n \choose k}+\sum_{k=n+1}^{2n} {2n \choose k}$$
$$\implies S_n+\sum_{k=n+1}^{2n} {2n \choose k}=2^{2n}$$
Change $k$ to $2n-j$, then
$$S_n+\sum_{j=n-1}^{0} {2n \choose 2n-j}=2^{2n}$$
$$\implies S_n+ \sum_{j=0}^{n} {2n \choose j}-{2n \choose n}=2^{2n}$$
$$\implies S_n=2^{2n-1}+\frac{1}{2}{2n \choose n}.$$
Next let
$$T_n=\sum_{k=0}^{n} k {2n \choose k}=\sum_{k=0}^{n} k\frac{(2n)!}{k!(2n-k)!}=2n\sum_{k=0}^{n}{2n-1 \choose k-1}=2n\sum_{j=0}^{n-1}{2n-1 \choose j} $$
We have $$2^{2n-1}= \sum_{k=0}^{2n-1} {2n-1\choose k}=\sum_{k=0}^{n-1} {2n-1 \choose k}+\sum_{k=n}^{2n-1} {2n-1 \choose k}=\sum_{k=0}^{n-1} {2n-1 \choose k}+\sum_{j=0}^{n-1} {2n-1 \choose n+j}$$ $$2^{2n-1}\implies \sum_{k=0}^{n-1} {2n-1 \choose k}+\sum_{j=0}^{n-1} {2n-1 \choose n+j}=\sum_{k=0}^{n-1} {2n-1 \choose k}+\sum_{j=0}^{n-1} {2n-1 \choose n-1-j}$$ $$\implies 2^{2n-1}= \sum_{k=0}^{n-1} {2n-1 \choose k}+\sum_{m=0}^{n-1} {2n-1 \choose m} \implies \sum_{k=0}^{n-1} {2n-1 \choose k}=2^{2n-2}$$
Finally, we have $$S'_n=n2^{2n-1}+\frac{n}{2} {2n \choose n}-n2^{2n-1}=\frac{n}{2}{2n \choose n}$$
Answer: Related Equation
Just for a fun alternative, we have the following equation that we will prove below.
$$
\sum_{i=2}^{n} (n+i)\binom{2n}{n+i} -
\sum_{i=1}^{n} (n-i)\binom{2n}{n-i}
=
0
$$
Combinatorial Proof
One wish to colour $2n$ distinguishable balls such that exactly one is pink, some (can be none) are black, and some (can be none) are white. The two terms on LHS are, respectively:

Number of possible colouring such that there are at least $n+1$ black balls
Number of possible colouring such that there are at most $n-2$ white balls

Easy to see that (1) equals (2) so their difference is zero.
Relation to Original Question
$$
\begin{align}
\sum_{i=1}^{n} i\binom{2n}{n-i}
&=
\frac{1}{2}
\left[
\sum_{i=1}^{n} (n+i)\binom{2n}{n+i} -
\sum_{i=1}^{n} (n-i)\binom{2n}{n-i}
\right]
\\\\
&=
\frac{n+1}{2}\binom{2n}{n+1}
\end{align}
$$
Potential Extension
Instead of one pink, colour $m$ balls pink.
$$
\sum_{i=m+1}^{n}\binom{n+i}{m}\binom{2n}{n+i} -
\sum_{i=1}^{n}\binom{n-i}{m}\binom{2n}{n-i} =
0
$$
The two terms are, respectively:

Number of possible colouring such that there are at least $n+1$ black balls.
Number of possible colouring such that there are at most $n-m-1$ white balls.

These two are the same, thus the difference is zero and we can write:
$$
\sum_{i=1}^{n}\left[\binom{n+i}{m}-\binom{n-i}{m}\right]\binom{2n}{n-i}=
\sum_{i=1}^{m}\binom{n+i}{m}\binom{2n}{n-i}
$$
For odd $m$, $\binom{n+i}{m}-\binom{n-i}{m}$ has the term $i^{m}$
Comment: @lsstat I added some possible extension in the answer. The first part of the answer is a special case of $m=1$, for this value we can get quite elegant solution. For higher $m$, I think it's not elegant anymore, so I didn't write the answer for higher $m$ before
Comment: @lsstat btw, I posted a question for the identity in my answer. In case you are also interested in other proof, here is the link: https://math.stackexchange.com/q/4614246/751970
Comment: Thanks! This is a very clever idea. I wonder whether this idea can be used to prove the general version. I use $\sum_{i=1}^n i\binom{2n}{n-i}$ to prove $\sum_{i=1}^n i^3\binom{2n}{n-i}$ and it can be done. But using induction (i.e. using case $i^r$ to prove case $i^{r+2}$) seems complicated. Do you have any idea?
Comment: Thanks! You are quite correct. For higher $m$, it may be much more difficult than we thought. I was thinking of the generating functions for $i^m\binom{2n}{n-i}$. By WolframAlpha, it is $i^m\binom{0}{-i} _3F_2(\frac12,1,1;1-i,i+1;4z)$. The partial sum of hypergeometric functions may give some useful results, but I haven't found them yet. See page 223 section 5.7 in the book: https://www.csie.ntu.edu.tw/~r97002/temp/Concrete%20Mathematics%202e.pdf
Answer: I don't konw how to prove it, but for general case I found something:
Integral Representation and the Computation of Combinatorial Sums by G.P.EGORYCHEV  Page77
says that:

verify the formula$\sum\limits_{i=1}^n i\left(\begin{array}{c}
2 n \\
n-i
\end{array}\right)=\frac{1}{2}(n+1)\left(\begin{array}{c}
2 n \\
n-1
\end{array}\right)$ with Mathematica
<code>Sum[Binomial[i, 1]*Binomial[2*n, n - i], {i, 1, n}]
</code>
$$
\frac{1}{2} (n+1) \binom{2 n}{n-1}
$$
Comment: Thanks! Mathematica indeed gives the answer, but I would like to know the proof. For the book, I guess what I need is $k^x$ instead of $x^k$ on the right-hand side of (2.42).
Comment: no, just let $x=1$ would be ok.
Comment: OK. It seems we can choose $a_1=2,a_4=1,a_5=-1,a_2=a_3=a_6=0$. But how can we choose $b$ to make the second combinatorial number become $k^r$?


Socket support using wamp in windows 7

Question: I'm running windows 7 and using WAMP for my local development. Now I Installed Cultbooking (sourceforge.net/projects/cultbooking/) in my wamp and can't finish my installation because it says sock "Socket support - Socket not supported". I don't know how I can enable my socket. I'm new to web development.
This is what I did, I download the Cultbooking from the (sourceforge.net/projects/cultbooking/) and drag the files to my 'www' directory of my wamp. Now when i pointed my browser to my localhost it say
<code>  PHP version >= 5.0 Yes

  zlib compression support Available

  XML support Available

  MySQL support Available

  Socket support Unavailable

  configuration.php Writeable
</code>
Now my only problem is my Socket support. How do I enable it? if you're in my shoes, Any Ideas?
Thanks!
Answer: It looks like you've got a build of PHP installed that doesn't have sockets enabled. (Sockets are an abstraction that are used in code that makes and receives TCP/IP connections.)
It looks like this was supposed to be fixed in the official Windows binaries back in 2002. If you're not running an official build it might help to investigate that first. If the official builds aren't being compiled with "--enable-sockets" specified then you'll need to build it youself with the option enabled.

Socket support using wamp in windows 7


How to show function is uniformly continous on certain interval

Question: Let $ f\colon \mathbb{R} \to \mathbb{R}$ be  $$x \mapsto \begin{cases} \frac{(x-1)^2}{x^2+1}, &|x| \neq 1 \\2, &|x|=1\end{cases} $$
How can I show that $f$ is uniformly continuous on $[-2,2]\backslash \{ - 1,1\}$?
I thought it could be done with  the $ \epsilon - \delta$ criteria but I am not sure because of the specific interval.
Answer: $$f(x)= 1-\frac{2x}{x^2+1}$$ for $|x|\neq 1. $
$$|f'(x)| =\left|\frac{2(1+x^2) -2x\cdot 2x }{(1+x^2)^2}\right|=\frac{2|1-x^2|}{(1+x^2)^2}\leq\frac{2(1+x^2)}{(1+x^2)^2}\leq 2 $$
Hence
$f$ is Lipschitz continuous and therefore uniform continuous for $|x|\neq 1.$
Answer: $\frac{(x-1)^2}{x^2+1}$ defines a continuous function on $[-2,2]$. Continuous functions on compact sets are uniformly continuous, so this function is uniformly continuous on $[-2,2]$, and thus also on all subsets of $[-2,2]$, including $[-2,2]\backslash\{\pm1\}$, where it's identical to $f$. So $f$ is uniformly continuous on said set.


OpenVPN bridging

Question: I was wondering, if I am setting up an Linux OpenVPN server using ethernet bridging rather than a routed tunnel. Do I still need to push a route to the client that is connecting to me?
I am setting OpenVPN to use DHCP proxy instead of giving it a pre defined pool.
What do I need to still configure, other than the SSL params?
Answer: First, here are my OpenVPN configuration notes as a general starting point.
And here are the OpenVPN docs about bridging.
The short answer is that if you set up a bridged openvpn config and you use a split tunnel, the clients will be directly connected only to the server's network via the vpn.  If you want the clients to be able to connect to other networks beyond that on the server side, you need to push one or more routes to them via the vpn.
If you don't use a split tunnel (all traffic goes through the vpn, via the redirect-gateway setting), then you can use the dhcp server config to push a default gateway to the hosts, and they can use that (over the vpn) to get to other networks, or out to the internet.  You also need to use an iptables nat config as detailed in the docs.
Comment: Oh I see, if all traffic is going over the tunnel then no need for routes. But if I am using a split I have to route the traffic. Makes sense if I got it right.
Comment: Yup you got it.

OpenVPN bridging


Show that if $n-m=2$, then the simplex method will not cycle, no matter which pivoting rule is used

Question: Here $n$ is the number of variables and $m$ is the number of constraints. This is the Exercise 3.10 (with asterisk) in the classical textbook Introduction to Linear Optimization by Dimitris Bertsimas and John Tsitsiklis.
The solution given by my professor says "Please find the proof in Marshall and Suurballe (1969)." However, in their 1969 paper "A note on cycling in the simplex method", they actually assumed a specific pivoting rule. They only proved that using that version of simplex method, the claim is true. The proof is highly dependent on the way of choosing entering and leaving variable. I tried to imitate the proof in an arbitrary pivoting rule setting, but failed.
I also searched online for references that are related to this topic, but the most related convincing result is "a basic feasible solution with a single degeneracy cannot reappear in the sequence of bases" in the paper by Saul I. Gass, published in Annals of Operations Research $47(1993)335-342$.
I can easily prove no cycling occurs for any pivoting rule when $n-m=1$ because the variable just entered the basis cannot leave in the next iteration. However, this cannot be generalized to $n-m=2$ because the entered variable can leave basis in the next second iteration.
I would appreciate it if anyone could give some hint on this problem.
Answer: Here is a solution manual for that question.
https://math.berkeley.edu/~bernd/HW3solution.pdf
I don't really understand the arguments, but basically it says when $n-m=2$, either the polyhedron is unbounded or the polyhedron is bounded but all BFS are nondegenerate. In both cases, simplex method terminates in finitely many steps.
Comment: Thanks for your reply. Actually I also noticed this solution, but I cannot understand his arguments. It is pretty vague. Also, why unbounded polyhedron implies negative infinity optimal objective? I mean, in general this cannot be true, then how does $n-m=2$ imply this?
Comment: I don't think $n-m =2 $ implies unbounded polyhedron has negative infinity optimal objective. When there are cycles in simplex, all the bases in the cycle are degenerate, meaning you are stuck at the same basic feasible solution, I don't understand how this is connected to polyhedron though.
Comment: I think for $n-m =2$ you can convert it into an LP on a polyhedron in $\mathbb{R}²$, now you can draw it on the plane, and run simplex on its dual. Then you are just picking the normal vectors in the polyhedron in an order that's closer and closer to the objective function in a plane. So it will not cycle.
Answer: Suppose towards a contradiction that some pivoting rule generates a cycle. Without loss of generality, let's assume the tableau looks like below at the beginning of the cycle.
\begin{array}{c| c c c c c c c}
   -{c_b}^T x_b  & 0 & \dots & 0 & \dots & 0 & c_{m+1} & c_{m+2}\\
   \hline
   x_1           & 1      & \dots & 0 & \dots & 0 & u_{1,1} & u_{1,2}\\
   \vdots        & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
   x_l           & 0      & \dots & 1 & \dots & 0 & u_{l,1} & u_{l,2}\\
   \vdots        & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots  \\
   x_m           & 0 & \dots & 0 & \dots & 1 & u_{m,1} & u_{m,2}\\
\end{array}
Also, suppose $c_{m+1} < 0$ and the pivoting rule select $x_l$ as the entering variable. Then $l \in r_1 = \{i| 1\leq i \leq m, u_{i,1} > 0\}$. After this iteration, the tableau becomes
\begin{array}{c| c c c c c c c}
   -{c_b}^T x_b  & 0 & \dots & -\frac{c_{m+1}}{u_{l,1}} & \dots & 0 & 0 & c_{m+2}\\
   \hline
   x_1           & 1      & \dots & -\frac{u_{1,1}}{u_{l,1}} & \dots & 0 & 0 & u_{1,2}\\
   \vdots        & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
   x_{m+1}       & 0      & \dots & \frac{1}{u_{l,1}} & \dots & 0 & 1 & u_{l,2}\\
   \vdots        & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots  \\
   x_m           & 0 & \dots & -\frac{u_{m,1}}{u_{l,1}} & \dots & 1 & 0 & u_{m,2}\\
\end{array}
For simplicity, we still notify the updated last column with the same variable names. As the reduced cost of the basic direction $x_l$ is $-\frac{c_{m+1}}{u_{l,1}} < 0$, we must have $c_{m+2}<0$ otherwise the simplex algorithm will terminate. Suppose the exiting variable is $x_j$, we will show 1)$j\neq l$ and 2)$j\in r_1$. First notice that, after this iteration, we will have two nonbasic variables $x_j$ and $x_l$. Since $x_j$ just exits the basis, it cannot reenter the basis in the very next iteration. Hence $x_l$ must be the entering variables in the next iteration. It implies the reduced cost $\bar{c_l}$ in the next iteration must be negative. If $j = l$, then the reduced cost $\bar{c_l} = -\frac{c_{m+1}}{u_{l,1}} + (-\frac{c_{m+2}}{u_{l,2}})\cdot \frac{1}{u_{l,1}}  > 0$ as $c_{m+1},c_{m+2}<0$ and $u_{l,1}, u_{l,2} > 0$. Therefore $j \neq l$. To prove 2), suppose that $j \notin r_1$. Then $u_{j,1} \leq 0$. The reduced cost $\bar{c_{l}}$ in the next iteration would be $ \bar{c_l} = -\frac{c_{m+1}}{u_{l,1}} + (-\frac{c_{m+2}}{u_{j,2}}) \cdot (-\frac{u_{j,1}}{u_{l,1}}) > 0$. Hence 2) must be true.
From 1) and 2), we conclude that $j$ must belong the the set $r_2 = \{i| u_{i,2}>0, i\in r_1, i \neq l\}$. As $\lvert r_1 \rvert \leq m$, we have $\lvert r_2 \rvert \leq m -1$. If we continue this process, we will have $\lvert r_{m+1} \rvert \leq 0$. Hence the simplex must terminate after m iterations and therefore it cannot cycle, we reach a contradiction here. As a corollary, we conclude that if $n-m=2$, then the simplex algorithm will terminate after at most $m$ iterations.


Submit the form using JavaScript showing the please wait message not functioning

Question: In my ASP.NET MVC application, in a form submit event I wanted to show please wait for a message when clicking the submit button.
There also I have added required attributes for the mandatory fields.
So I modified the code as follows. Then it checks the required fields are filled before submitting.
But when this happens it doesn't show the please wait for meassage.
Even if all fields are filled, it's also submitting the data without showing the Please wait for  message.
This is the example I got from the internet. https://weblogs.asp.net/psheriff/displaying-a-wait-message-on-an-mvc-page
This is my customized code

  <input type="submit" value="Register Customer" id="submitButton" class="btn btn-success" onclick="return DisplayProgressMessage();" />

Javascript
function DisplayProgressMessage(ctl, msg) {
  //document.getElementById('submitButton').style.display = 'none',
  $('my-form').on('submit', CheckRequired);
  $(ctl).prop("disabled", true);
  $(ctl).text(msg);
  $(".submit-progress").removeClass("hidden");
  $("body").addClass("submit-progress-bg");

};

Answer: Finally I made it doing this change
  let allAreFilled = true;
 document.getElementById("my-form").querySelectorAll("[required]").forEach(function (i) {
   if (!allAreFilled) return;
   if (!i.value) {
     allAreFilled = false;
     return;
   }
 })
 if (!allAreFilled) {

 } else {
   $(ctl).prop("disabled", true);
   $(ctl).text(msg);
   $(".submit-progress").removeClass("hidden");
   $("body").addClass("submit-progress-bg");
   document.getElementById("my-form").submit();
 }


Best practice: Twig template for custom module's block

Question: I'm looking to provide a template for a custom block in my custom module. There are two ways to go about this: provide a template for just the block's content, or provide a template that extends block.html.twig. I've returned empty-handed in my search for a best practice. Let me clarify the two options to provide a template for my custom module's block:
Option 1: provide a template for the block's content
<?php
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule' => array(
      'variables' => array('var' => 'test'),
    ),
  );
}
?>

The template named mymodule.html.twig looks like this:

This is my content: {{ var }}

Option 2: extend block.html.twig
<?php
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'block__mymodule' => array(
      'base hook' => 'block',
      'variables' => array('var' => 'test'),
    ),
  );
}
?>

The template named block--mymodule.html.twig looks like this:

{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

Looking for a best practice
The documentation on Twig Template naming conventions is quite clear on this: for a block, the name should be block--module.html.twig. However, is that the filename a themer would use to overwrite my block content (option 1) or is it the filename I should use for the template I provide for my custom module (option 2)? I haven't found a clear answer on this so as far as I can see there's no best practice on this yet.
Answer: I would prefer option 1. Theme the inside of a block in a custom template with custom variables or build a render array with render elements. Use the block template only to theme the outside of the block, for example add a wrapper div.
Option 2 is not a good idea, because it uses this block template:
{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

Normally a block template looks like this:
{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ content }}
{% endblock %}

By ignoring {{ content }} in a block template no cache metadata can bubble up. See https://www.previousnext.com.au/blog/ensuring-drupal-8-block-cache-tags-bubble-page
You could try to add the cache metadata with block methods. But this is not good practice, because if later someone tries to add block content and is not aware of that the block template doesn't use the base hook variables this person will have a hard time debugging this.
Answer: I would prefer to use option 2, but depending on the use case without the {% extends... %} part and possibly at some template suggestions just in case that block is used in various contexts where the additional HTML is needed.
Comment: You're right about the use case of various contexts. If I provide a template for just the content, people can copy _mymodule.html.twig_ to their theme's directory, or create their own _block--mymodule.html.twig_ template, chosing to extend _block.html.twig_ or not.

If I go for option 1, I might implement `hook_theme_suggestions_HOOK_alter`.


HAProxy high CPU usage when exists CLOSE_WAIT connections

Question: I'm using https://github.com/mesosphere/marathon-lb to configure the HAProxy. Because of it change the configuration with any change in our microservices instances, it create a lot of haproxy process. For example:
# pgrep haproxy -a
690 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 70155
3108 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 72735
7540 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 77012
8297 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 77058
9651 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 78452
10690 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 79475
15639 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 84966
15760 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 85082
16574 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 85637
16923 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 86235
17022 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 86278
17672 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 86375
18060 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 87011
18620 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 87398
19470 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 87809
20350 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 88653
52146 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 20253
52339 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 20744
53367 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 20934
53468 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 21957
53710 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 22058
54324 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 22295
54967 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 23482
55476 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 23537
55796 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 24162
55987 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 24199
56180 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 24546
56246 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 24582
56519 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 24879
57201 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 25317
57546 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 25568
57774 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 26080
60398 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 30723
60783 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 31118
89062 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 56479
89509 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 57252
89784 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 57531
90949 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 58144
91675 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 59389
93436 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 59422
93677 haproxy -p /tmp/haproxy.pid -f /marathon-lb/haproxy.cfg -D -sf 61172

The haproxy process will finish when all connection are finished. But sometimes a process only has connection with CLOSE_WAIT status and it will consume 100% of the CPU.
# lsof -i | awk '{if($1 == "haproxy") print $2 " " $10}' | sort -u
10690 (ESTABLISHED)
15760 (ESTABLISHED)
16574 (ESTABLISHED)
16923 (ESTABLISHED)
17022 (ESTABLISHED)
17672 (ESTABLISHED)
18060 (ESTABLISHED)
18620 (ESTABLISHED)
19470 (ESTABLISHED)
20350 (CLOSE_WAIT)
20350 (ESTABLISHED)
20350 (LISTEN)
3108 (ESTABLISHED)
52146 (ESTABLISHED)
52339 (ESTABLISHED)
53367 (ESTABLISHED)
53468 (ESTABLISHED)
53710 (ESTABLISHED)
54324 (ESTABLISHED)
54967 (ESTABLISHED)
55476 (ESTABLISHED)
55796 (ESTABLISHED)
55987 (ESTABLISHED)
56180 (ESTABLISHED)
56246 (ESTABLISHED)
56519 (ESTABLISHED)
57201 (ESTABLISHED)
57546 (ESTABLISHED)
57774 (ESTABLISHED)
60398 (CLOSE_WAIT)
60783 (CLOSE_WAIT)
690 (ESTABLISHED)
7540 (ESTABLISHED)
8297 (ESTABLISHED)
89062 (ESTABLISHED)
89509 (ESTABLISHED)
89784 (ESTABLISHED)
90949 (ESTABLISHED)
91675 (ESTABLISHED)
93436 (ESTABLISHED)
93677 (ESTABLISHED)

Here the processes 60398 and 60783 only has CLOSE_WAIT status.
# lsof -i | awk '{if($2 == "60398") print $2 " " $9 " " $10}'
60398 mesos-lb-3.mydomain:35819->leia-5.mydomain:31302 (CLOSE_WAIT)
# lsof -i | awk '{if($2 == "60783") print $2 " " $9 " " $10}'
60783 mesos-lb-3.mydomain:37419->leia-8.mydomain:31682 (CLOSE_WAIT)

The strace of booth show the same result:
poll(0x7fe774e2e010, 0, 0)              = 0 (Timeout)
poll(0x7fe774e2e010, 0, 0)              = 0 (Timeout)
poll(0x7fe774e2e010, 0, 0)              = 0 (Timeout)
poll(0x7fe774e2e010, 0, 0)              = 0 (Timeout)
poll(0x7fe774e2e010, 0, 0)              = 0 (Timeout)
poll(0x7fe774e2e010, 0, 0)              = 0 (Timeout)

The tcpdump -vv port 35819 didn't show nothing. The same for the port 37419
About the enviroment:
# haproxy -vv
HA-Proxy version 1.6.9 2016/08/30
Copyright 2000-2016 Willy Tarreau <firstname.lastname@example.com>

Build options :
  TARGET  = custom
  CPU     = x86_64
  CC      = gcc
  CFLAGS  = -g -fno-strict-aliasing -Wdeclaration-after-statement
  OPTIONS = USE_LINUX_SPLICE=1 USE_LINUX_TPROXY=1 USE_LIBCRYPT=1 USE_ZLIB=1 USE_POLL=default USE_DL=1 USE_OPENSSL=1 USE_LUA=1 USE_PCRE=1 USE_PCRE_JIT=1

Default settings :
  maxconn = 2000, bufsize = 16384, maxrewrite = 1024, maxpollevents = 200

Encrypted password support via crypt(3): yes
Built with zlib version : 1.2.8
Compression algorithms supported : identity("identity"), deflate("deflate"), raw-deflate("deflate"), gzip("gzip")
Built with OpenSSL version : OpenSSL 1.0.2j  26 Sep 2016
Running on OpenSSL version : OpenSSL 1.0.2j  26 Sep 2016
OpenSSL library supports TLS extensions : yes
OpenSSL library supports SNI : yes
OpenSSL library supports prefer-server-ciphers : yes
Built with PCRE version : 8.39 2016-06-14
PCRE library supports JIT : yes
Built with Lua version : Lua 5.3.3
Built with transparent proxy support using: IP_TRANSPARENT IPV6_TRANSPARENT IP_FREEBIND

Available polling systems :
       poll : pref=200,  test result OK
     select : pref=150,  test result OK
Total: 2 (2 usable), will use poll.

It's running using docker and the image was based on debian:stretch image.
The docker host info is:
# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

# uname -a
Linux mesos-lb-4.mydomain 3.13.0-98-generic #145-Ubuntu SMP Sat Oct 8 20:13:07 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

# docker version
Client:
 Version:      1.10.3
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   20f81dd
 Built:        Thu Mar 10 15:54:52 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.10.3
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   20f81dd
 Built:        Thu Mar 10 15:54:52 2016
 OS/Arch:      linux/amd64

Any idea what's happing?
Thanks for the attention
Answer: Just changing the haproxy to use epoll is enough to solve the problem.
Solved on version https://github.com/mesosphere/marathon-lb/releases/tag/v1.4.2


How should I mic a violin in a live concert?

Question: Which are good mics and what are good positions of the microphone rel to the violin?
Keeping in mind:

confort for the player
acoustic feedback sensitivity
best quality tone from the instrument?

(this question does not include electrical violins)
Comment: Many string players I know go for a piezo pickup rather than a mic.  Much less acoustic interference, easy to attach to bridge or f-hole as you desire.
Comment: Good remark @CarlWitthoft, piezzo is even more known in the guitar "world" bu I think it's very limited in sound/tone quality. It looses the acoustic sound feeling. Although very practical to play in loud stages and avoid feedbacks.
Comment: Sergio - I would definitely recommend trying some of the Fishman piezo pickups. They are expensive (I think my last one cost more than my violin) but they (in my opinion) sound better than a mic'ed up violin!
Comment: @DrMayhem, I agree with you, the downside is that I play often in classical concerts and the piezo mics are not practical to take on/off, and when they are on I feel they mute the violin's acoustic sound.
Answer: I have found that positioning a mic about halfway up the fingerboard is the best tone compromise for "mic"ing a violin live. Although I most often use a clip mic near the chin-rest pointing above the bow/string area to avoid having it in my line of sight if I look at my left hand.
Halfway up the fingerboard gives the  best tone quality.
Near the bridge the sound has many high frequencies and sounds quite hard.
Near the f-hole frequencies around 250~300 hertz get a huge boost.
About Mic types, so far dpa-4099 is the best option since it's a harmless rubber clip attached to the instrument, and is a high quality condenser mic.  Because it's a condenser mic it is acoustic feedback sensitive, but it has not been a problem for me.
Answer: Bluegrass players generally use a large diaphragm condenser mic (like a Neumann U87) on a boom stand pointed down.  That way you can move in and out to control mix and dynamics, moving in on intros and breaks, and away when you "chunking" or filling.  The condenser mic picks up a wide range, so you don't lose the warmth of the instrument as you often do with piezzo mics.  You need a good sound guy to dial it in though.
Comment: And also because of that priority to the good sound they lose a bit on mobility and possibility to move on stage.


How to interpret multiple factors in model output in R

Question: I am well aware how to read the model summary in R for a regression model when a factor is included. The "first" level, in terms of ABC, is regarded as the base level to which all further levels of that factor are compared to. In an ANOVA-style model the baseline value is found in the intercept (equals the mean response value for base-level class).
However, if one or several factors are mixed with continuous predictors, then how can I see what the base-level values are at all? to what would I compare?
In the model output below, there are two factors:

LandUse (4 Levels)
Type_LU (4 Levels)

I see now for example that LandUseLow is 0.35 units higher than the base-line LandUseHigh. Would one now simply look at the mean response for the class LandUseHigh and compare? Is it that simple?
My_model:
                  Estimate Std. Error Adjusted SE z value Pr(>|z|)
(Intercept)      4.6086772  1.7754606   1.7773711   2.593  0.00951 **
DiTempRange     -0.1409464  0.0764872   0.0765969   1.840  0.06575 .
LandUseLow       0.3520743  0.5989777   0.5997903   0.587  0.55721
LandUseMedium    0.2741413  0.3668149   0.3675811   0.746  0.45579
LandUseNone     -1.0128945  0.5735342   0.5744652   1.763  0.07787 .
MAP              0.0048810  0.0009128   0.0009142   5.339    1e-07 ***
Rivier           0.3502782  0.2252743   0.2257546   1.552  0.12076
TempRange        0.0823410  0.0606546   0.0607942   1.354  0.17560
Tmean           -0.1762862  0.0994486   0.0996353   1.769  0.07684 .
TYPE_LUconserva -0.9312487  0.4770681   0.4781244   1.948  0.05145 .
TYPE_LUprivate  -0.4839229  0.3289011   0.3296201   1.468  0.14207
TYPE_LUstate     0.0004062  0.4079678   0.4089744   0.001  0.99921
logVRM           0.1370973  0.1140166   0.1142342   1.200  0.23008
logTWI          -0.0735540  0.4195267   0.4202589   0.175  0.86106
logDAH           1.7132823  3.5937000   3.6028996   0.476  0.63441

Answer: @Placidia is right.  However, this is a simplified case because you do not have any interactions.  That is, your model assumes (rightly or wrongly) that moving from LandUseHigh to LandUseLow is associated with an increase of 0.25 units in your response variable no matter what the level of Type_LU is or what the values of your continuous covariates are.
If you did have interactions, then the coefficient on LandUseLow would correspond to the change from LandUseHigh only when Type_LU is set at the reference level.  Likewise, if there were an interaction between LandUse and a continuous covariate, the coefficient on LandUseLow would correspond to the change from LandUseHigh only when the value of the continuous covariate were $0$.  If you had a three-way interaction between LandUse, Type_LU and a continuous covariate, it would indicate the change when both Type_LU is set at the reference level and the value of the continuous covariate were $0$.

Update: The (intercept) indicates the value of the reference category.  You have two categorical variables, so you have two reference categories. Your reference categories are LandUseHigh and an unspecified level of Type_LU (which I assume you know).  So the value of the Estimate in the (intercept) row is the predicted mean for those study units in both of those categories when all the continuous covariates are equal to $0$.  Again, because you don't have an interaction term, the value of LandUseHigh when Type_LU is conserva, private, or state is the sum of the estimate for the intercept plus the estimate for the appropriate level of Type_LU.
Comment: Dear Gung & Placidia, thank your interpretations. Sadly I think I did not write my question clear enough. I wanted to know "how do I know the baseline value to which LandUseLow is compared to?". The value of LandUseHigh is not shown in the table. Of course I can look up by hand, but how would I report this in a paper so that the reader can follow? Thank you VERY much for the hint on the interaction! I did not think about that before (+1).
Answer: The LandUseLow coefficient tells you what happens to the response when everything is held constant, except that land use goes from High to Low -- you then expect to see a change of 0.35.
Comment: Also, it's necessary to keep in mind that the comparison of LandUseLow to baseline, in the presence of continuous variables, compares LandUseLow to baseline when these continuous predictors are 0. Often, this is not reasonable, but I can't tell from the variable names.


Binary logistic regression: interpretation of regression coefficients

Question: I have performed a logistic regression with whether or not an athlete was re-contracted by their sports team as the DV. One of the significant predictors of the final model was draft order (OR 0.888).
<code>Coefficients:
                                  Estimate Std. Error z value Pr(>|z|)
(Intercept)                     -120.69457   46.78377  -2.580 0.009885 **
Debut.first.year                   0.67977    0.21772   3.122 0.001795 **
Grouped.by.fives                  -0.11849    0.02361  -5.019 5.21e-07 ***
Draft.year                         0.06109    0.02334   2.617 0.008863 **
Maturity                          -0.65844    0.40981  -1.607 0.108118
Games.second.season.DC             1.87716    0.34011   5.519 3.40e-08 ***
Interstate.vic.team                0.47625    0.19390   2.456 0.014044 *
Rising.star                        1.50635    0.44429   3.390 0.000698 ***
Team.EOS.ladder.second.year.raw   -0.04403    0.02062  -2.135 0.032728 *
</code>
I understand that this indicates that being selected later in the draft results in a reduced odds of being re-contracted. There are 8 predictors overall therefore my question is, does this indicate that being selected later in the draft results in a reduced odds of being re-contracted when all other predictors are held constant? Does this then mean that draft order is associated with being re-contracted irrespective of rising star nomination, maturity, draft year etc?
The text books I have read and online forums are quite vague and I am struggling to understand the relationship between the regression coefficients.
Thank you!
Answer: No, what you are doing is forced entry regression, to be able to interpret it as you did, you will need a hierarchical regression. So you should first fit a model without draft order and then fit a model with draft order and compare if the fit is significantly better in the second case. If it is, you can then look at how much additional variability is being explained by including draft order.
Comment: What does the OR for draft order tell me then?