Prov that function is eventually periodic to origin.

Question: Let $f:\mathbb{Z}^4 \rightarrow \mathbb{Z}^4$ by
$f(w,x,y,z) = (\mid w-x \mid,\mid x-y \mid,\mid y-z \mid,\mid z-w \mid)$

Prove that for any $(w,x,y,z) \in \mathbb{Z}^4$ there is $n>0$ such that $f^n(w,x,y,z)=(0,0,0,0)$
Prove that there is no $n$ such that $f^n(w,x,y,z)=(0,0,0,0)$ for all $(w,x,y,z) \in \mathbb{Z}^4$

I wrote a computer code in R that can execute this function for any integers $w,x,y,z$ and $n$. See below:
<code>rm(list = ls())
myfun=function(w,x,y,z){
outcome <- c(abs(w-x), abs(x-y), abs(y-z),abs(z-w))
return(outcome)
}
w<-1
x<-3
y<-534
z<-3
n=6

outcome <- matrix (nrow=n, ncol=4)
for (i in 1:n){
outcome[i,] <- myfun(w,x,y,z)
w <- outcome[i,1]
x <- outcome[i,2]
y <- outcome[i,3]
z <- outcome[i,4]
}
outcome
</code>

After executing 100's of points I see that after, $n=5$ we see the function going to $(0,0,0,0)$. I tried using brute force and applied the function 6 times by hand to see if it cancels out but I've end up with a very complex function. There must be a cleaner way of proving this question. Point me in the right direction please.
Comment: @Winther - The max element never grows (other then the first time when the arguments can be negative) and can be shown to decrease after at most 4 applications.
Comment: Hint(s). You can assume all the arguments are positive (why)? What happens to the sizes of the arguments after the next iteration?
Comment: It won't always just take 5 iterations! (If it did, then $n=5$ would have $f^n(x,y,z,w)=(0,0,0,0)$ for all $(x,y,z,w)\in\mathbb{Z}^4$.)
Comment: @BenBlum-Smith I meant after 5 iterations. The 6th iteration will always be (0,0,0,0)
Comment: @EthanBolker The arguments are positive due to the absolute value in the function. I don't see a pattern in terms of the sizes of arguments.
Comment: Can you show that the arguments get smaller (in some appropriate sense) each time?
Comment: @EthanBolker Absolutely! Using the reverse triangle inequality
Comment: @EthanBolker For any point, if I let n=6 then that function will go to (0,0,0,0) (According to my computer program). This makes sense due to the reverse inequality, the function arguments are decreasing in size.

How can I use these facts to prove the statements?
Comment: The decrease should show you how to prove (1). If (2) is true (you've been asked to prove it) then 6 iterations can't always work - your program doesn't test enough cases. Since (presumably) (2) is true, your program will not help no matter how far you go. But the intermediate results may show you how to construct a starting point that will take a long time to get to all zero (I don't know but that's where I'd start).
Comment: For the first part: Can we apply contraction mapping to show it is eventually a fixed point?
Comment: @Nadia - I agree with Ethan Bolker. It can't actually always be zero after 6 iterations.
Comment: By random search, one can find starting arbitrarily long iteration sequences. Say, for $10,536,452,296$ there are 15 iterations.
Comment: Yes as @EthanBolker pointed out, by part 2 of the question there is no fixed number of iterations where the the function goes to $(0,0,0,0)$ for all points.
Comment: @zhoraster that is the first point I have come across where it takes more than 5 iterations. Surprising
Comment: (0,1,2,4) needs 7 steps
Answer: 1. Let us show that $f^n(v)\to 0$, $n\to\infty$, for any $v=(a,b,c,d)\in \mathbb{R}^4$. It is enough to consider non-negative vectors. It is clear that $f$ does not increase the maximum of the numbers, which we denote by $||v||$. Therefore, there exists the limit $\lim_{n\to\infty} ||f^n(v)||$. In particular, the sequence $\{f^n(v),n\ge 1\}$ has a limit point, say, $v_0$.
Clearly, $||f^m(v_0)|| = ||v_0||$ for any $m\ge 0$. Also, extracting a convergent subsequence for preimages of elements converging to $v_0$, $v_0 = f(u_0)$.
Assume that $v_0\neq 0$. Let $a>0$ be the maximal coordinate of $f(v_0)$, wlog the first. Then $v_0$ has either the form $(a,0,*,*)$ or $(0,a,*,*)$. Moreover, the sum of the remaining coordinates must be $a$ due to the fact that $v_0 = f(u_0)$.
Case a Both remaining coordinates are less that $a$ (and therefore positive). Then we have either (here $c$ means any number less then $a$) $$(a,0,c,c)\to (a,c,c,c) \to (c,c,c,c),$$
or
$$(0,a,c,c)\to (a,c,c,c) \to (c,c,c,c),$$
which contradicts to $||f^m(v_0)|| = ||v_0||$.
Case b One of the remaining coordinates is $a$ (and the other is zero). Then we have essentially two possibilities
$$
(a,0,a,0)\to (a,a,a,a)\to (0,0,0,0),
$$
and
$$
(0,a,a,0)\to (a,0,a,0)\to (a,a,a,a)\to (0,0,0,0),
$$
both contradicting the assumption.
Therefore, $v_0=0$, hence, $\lim_{n\to\infty} f^n(v) = 0$, as claimed.
2. First we prove this for real numbers. Notice that the polynomial $(x-1)(x+1)^3+1$ has a positive root $\lambda \approx 0.83929$. Set $(t,u,v,w) = (1,1+\lambda,(1+\lambda)^2,(1+\lambda)^3)$. Then $$f(t,u,v,w) = (\lambda,\lambda(1+\lambda),\lambda(1+\lambda)^2,(1+\lambda)^3-1)\\
 = (\lambda,\lambda(1+\lambda),\lambda(1+\lambda)^2,\lambda(1+\lambda)^3)=\lambda\cdot (t,u,v,w).$$ (I'll not write the vector here, since $\lambda$ is a cumbersome root of a cubic equation, and $(t,u,v,w)$ is even more cumbersome; the numerical values are $(t,u,v,w)\approx (1, 1.8393, 3.383, 6.2223)$.) Therefore,  for any $n\ge 1$  $f^n(t,u,v,w) = \lambda^n\cdot (t,u,v,w)\neq 0$.
Now by way of contradiction assume that there exists $n\ge 1$ such that $f^n(a,b,c,d) = 0$ for any integer $a,b,c,d$. Then, obviously, $f^n(a,b,c,d) = 0$ for any rational $a,b,c,d$. In view of continuity, $f^n(a,b,c,d) = 0$ for any real $a,b,c,d$, which contradicts the previous paragraph.

This proof also gives a way to construct integer quadruples leading to arbitrarily long iteration sequences: one just needs to multiply $(t,u,v,w)$ by a large number and take integer parts. Say, the approximate values $(10000,18393,33830,62223)$ lead to a $24$-step iteration sequence.

The application of this method for triples (perhaps, unsurprisingly) leads to funny example of long iteration triples: $(F_{n-2},F_{n-1},F_n)$, where $F_n$ is the $n$th Fibonacci number.
Comment: The first part of the question is false if you take $\Bbb Z^3$  instead of $\Bbb Z^4$, since  $(n,n,0)$ yields a periodic sequence for every $n$. How you rule out periodic sequences in the case $\Bbb Z^4$?
Comment: I added "f" after the word matrix. as you didn't name it  explicitly. Fine proof.
Comment: So the function f is defined by means of A.  Somebody  who hasn't read the comments might ask you state a def'n of f ,  but I have no problem understanding your solution.
Comment: Sorry about that............
Comment: @user254665, I've removed the matrix $A$, as it is not very relevant.
Comment: @san, considering some zillion cases probably. Quite boring, but can't think of another technique at the moment. A better question is why (or whether) $f^n(a,b,c,d)\to 0$ for *real* $a,b,c,d$.
Comment: I liked it better with the matrix. It made it easy to see how you got the polynomial, and, for me, easy to grasp the proof as a whole. However, it's your proof. +1.
Comment: @user254665, maybe the order of sentences is not optimal now, but the idea is more natural. You start by looking for a vector $z = (1,u,v,w)$ with $1<u<v<w$ such that $f(z) = \lambda z$. Then you must have $u=1+\lambda$, $v=(1+\lambda)^2$, $w = (1+\lambda)^3$. Hence, using that $f(z) = \lambda z$, you get $\lambda (1+\lambda)^3 = (1+\lambda)^3-1$.
Comment: @san, it is hard to read the comments. You can post an alternative answer, this will be more convenient.
Comment: @zhoraster, I have a few questions.
First part:
i) You start your proof by showing $f^n(v)\to 0$, $n\to\infty$, for any $v=(a,b,c,d)\in \mathbb{R}^4$. Why cant we just start in similar faishon but for  $v=(a,b,c,d)\in \mathbb{Z}^4$

ii) Why is it important to show that the sum of the remaining coordinates must be $a$?
Comment: i) yes, we can; the proof is considerably simpler. I just found the integer case not funny enough.   ii) if we don't use this, then there are just some few more cases to consider (not so much though).
Comment: @zhoraster For the second part: In the contradiction part of the proof, we show how $f^n(a,b,c,d)=(0,0,0,0) for integers and similar for rationals. You then proceed to "in the view of continuity,.." and showed the function is zero for all reals (thus contradiction). Why in the view of continuity, the function of reals is zero?
Comment: @Nadia, because each real $x$ is a limit of rational $q_k$. Then $f^n(x) = \lim f^n(q_k) = 0$.
Answer: $\bf{First\ part}$. We prove the statement given by Paul Sinclair in a comment:
The max element never grows (other then the first time when the arguments can be negative) and it decreases after at most 4 applications, if you start at a non-zero quadruple.

We assume that $f:\Bbb{N}_0^4\to \Bbb{N}_0^4$.
Then clearly $Max(f(V))\le Max(V)$ for all $V$.
If $Max(f(V))= Max(V)$, for some $V\ne 0$, then one of the entries of $V$ is $0$ and it is adjacent to the maximal value $m$ (note that we consider the first entry adjacent to the fourth, due to invariance under rotation).
Consequently, if all values of $V$ are different to its adjacent values, then none of the entries of $f(V)$ is zero, hence
$Max(f(f(V)))< Max(f(V))\le Max(V)$.

Now start with a $0\ne V\in \Bbb{N}_0^4$, and we have to prove that $Max(f^k(V))<Max(V)$ for some $k\in\{1,2,3,4\}$.
If $Max(f(V))<Max(V)$, there is nothing to prove.
Else we can assume by 3. that $V=(m,0,a,b)$ with $0\le a,b\le m$.
If $0\ne a$, $a\ne b$ and $b\ne m$, then by 4. we have $Max(f(f(V)))<Max(V)$
and we are done.
Hence we have to consider the three cases
$$
V=(m,0,0,b),\quad V=(m,0,a,a)\quad\text{and}\quad V=(m,0,a,m).
$$
In the first case, if $b=0$, then $f^4(V)=(0,0,0,0)$; if $b=m$ or $b=m/2$, then
$f^3(V)=(0,0,0,0)$ and if $b\ne 0,m/2,m$, then all elements of
$f(V)$ are different, hence by 4. we have $Max(f(f(f(V))))<Max(V)$.
In the second case, if $a=m$ or $a=0$, then $f^4(V)=(0,0,0,0)$, and
else all entries of $f(V)$ are different from the adjacent entries,
hence by 4. we have  $Max(f(f(f(V))))<Max(V)$.
In the third case, if $a=0$, then $f^3(V)=(0,0,0,0)$; if $a=m$ or
$a=m/2$, then $f^4(V)=(0,0,0,0)$ and if $a\ne 0,m/2,m$, then all elements of
$f(V)$ are different, hence, by 4., $Max(f(f(f(V))))<Max(V)$.
This proves the assertion. Note that for $V=(m,0,0,0)$ we have $Max(f^3(V))=m=Max(V)$.
Hence, if you start with any quadruple in $\Bbb{N}_0^4$ with $Max(V)=m$, after at most $4m$ steps it goes to zero, i.e., $f^{4m}(V)=(0,0,0,0)$.
${\bf{Conclusion\ of\ the\ first\ part:}}$ If you start with $(x,y,z,t)\in \Bbb Z^4$, then $V=f((x,y,z,t))\in \Bbb N_0^4$, hence $f^n(x,y,z,t)=0$ for $n=4 Max(V)+1$.
$\bf{Second\ part}$.
If a quadruple $V=(v_1,v_2,v_3,v_4)$ satisfies $v_1\le v_3$ and $\Delta:=v_4−(v_1+v_2+v_3)\ge 0$,
then the cuadruple $C:=(0,2v_1+\Delta,2v_4−2v_3,2v_4+\Delta)$ satisfies $f(f(C))=2f(V)$, and also
$c_1\le c_3$ and $c_4−(c_1+c_2+c_3)\ge 0$.
If $\Delta$ is even, then we can take $\overline C:=\frac 12 (0,2v_1+\Delta,2v_4−2v_3,2v_4+\Delta)$, and then
$f(f(\overline C))=f(V)$.
Starting from any $V=(v_1,v_2,v_3,v_4)$ satisfying $v_1\le v_3$ and $\Delta:=v_4−(v_1+v_2+v_3)\ge 0$,
such that $V$ needs $n$ steps to go to zero ($f^n(V)=(0,0,0,0)$ and $f^{n-1}(V)\ne (0,0,0,0)$),
we can construct (iterating the construction above) an infinite family $V_k$ with $V_0=V$ and $V_1=C$ (or $V_1=\overline C$),
such that $V_k$ needs $n+k$ steps to go to zero.
This proves the second part.
For example, we can consider $V_0=V=(0,0,1,2)$, which needs four steps to go to zero.
Then $V_3=(0,1,3,7)$ needs seven steps to go to zero.
If we set $V=V_0=(0,0,0,1)$, then $V_3=(0,1,2,4)$ needs 7 steps and $V_{11}=(0,20,57,125)$ needs 15 steps.
${\bf{Edit:}}$ Via OEIS on the last entry of the last example ($V_0=(0,0,0,1)$) I found that the problem is solved completely in
http://www.maa.org/sites/default/files/pdf/pubs/AMM-May05_Boxes.pdf
There they found $(0,1,q^2-q,q)$ as a fixpoint of the operation on certain equivalence classes, with $q^3-q^2-q-1=0$, which is related to the $\lambda$ in the answer of zhoraster via $q=\lambda+1$.
Comment: This is a good construction. In fact, it nearly coincides with another one I was going to give. We know that a polynomial corresponds to a recurrent equation; in our case $1+\lambda$ is a root of $x^3-x^2-x-1=0$, which corresponds to the recurrence $t_{n+3} = t_{n+2} + t_{n+1} + t_n$. So we end up with a tribonacci sequence of long-iteration examples. There are several tribonacci sequences: starting with $0,0,1$; $0,1,1$; $1,1,1$. Starting from $0,0,1$ with your approach will give all three of them (I look at $f(V)$ from your construction rather than $V$ itself) at different steps modulo 3.
Comment: Naturally, all the constructed examples will then be close to $(n,n(1+\lambda), n(1+\lambda)^2, n(1+\lambda)^3)$. For example, starting from $0,0,1$ as in above comment, after $20$ steps we arrive to $(927,1705,3136,5768)$, which is $(927, [927(1+\lambda)], [927(1+\lambda)^2], [927(1+\lambda)^3])$, where $[]$ denotes the integer part.
Comment: Very nice proof. Just one question for the first part. When we're examining the rest of the cases, why are we looking at the case $b=m/2$ and $b \neq m/2$ ? Isn't it enough to see if it holds for just $b=m$ and $b \neq m$ ?
Comment: @san In the second case if $a=m$ or $a=0$ then it should be $f^4(V)=(0,0,0,0)$,
Comment: @san The first part proves the assertion, not the first part of the question.
Comment: Error corrected and conclusion of the proof of the first part added.
Comment: If $b=m/2$ in the first case, then $f(V)=(m,0,m/2,m/2)$, so it doesn't hold that all entries are different.
Comment: @san you deleted your comment where you defined V before you wrote this proof. Can you add the comment to the proof? (ie define V)
Comment: I don't remember which $V$ you mean.
Comment: @san The first part. I think you meant "if you start with a non-zero quadruple $V$". Once we prove the assertion, how can we then go and prove the first part of the question?
Comment: @san First part, point 3.

If $V=(m,a,b,0)$ then $Max(V)=Max(f(V))$ . However 0 is not adjacent to m?
Comment: @san Are you sure about the conclusion. Maybe my interpertation is wrong but I'm reading this as:

if we choose $(10,2,1,3)$ then $V=f((10,2,1,3))=(8,1,2,7)$ and so it takes $n=4Max(V)+1$ steps for $f$ to go $(0,0,0,0)$ which means it takes $n=4*8+1=33$ steps for $f$ to go $(0,0,0,0)$
Comment: The quadruples are equivalent under rotation and reflexion,so $(m,a,b,0)$ is equivalent to $(0,m,a,b)$, which is equivalent to $(b,a,m,0)$ and to $(m,0,b,a)$. All this is explained in the article mentioned above.
Comment: In the article a better bound is given, what I say is that in this particular case it takes less than 33 steps to go to zero.


Sort commerce view by calculated price

Question: I use commerce, search api and facets. I have a "shop" view with indexed products. It works good and I can filter and sort the view using "search api" facets and "search api" sorts fields.
I can sort the view by an indexed field, like product base price which is a field of a product object. The problem is this base price could change due to rules (discounts, offers, etc), and then, the final price for the customer could be different.
I need to sort the "shop" view by the final customer prices, but I don't know how to do it with this indexed view. Any sugestion? TIA
Answer: Although I didn't find how to do it with views, I have found an alternative solution using views hooks.
First I have to unset the pager, because I need all records to sort. Only if it's this view and this sort criteria.
function MYMODULENAME_filters_views_pre_execute(&$view) {
  if (('shop' == $view->name) && ($view->exposed_raw_input['sort_by'] == 'field_product_commerce_price_amount_decimal_desc')) {
    $view->query->set_limit(NULL);
    $view->query->set_offset(NULL);
}}

After this, I reorder the $view->results as I need in another hook:
function MYMODULENAME_views_post_execute(&$view) {

    if (('shop' == $view->name) && ($view->exposed_raw_input['sort_by'] == 'field_product_commerce_price_amount_decimal_desc')) {

    $milista = array();
    foreach($view->result as $clave=>$valor) {
        $prdd = node_load($valor->entity);
        $producto = commerce_product_load($prdd->field_product['und'][0]['product_id']);
        $price = commerce_product_calculate_sell_price($producto);
        array_push($milista,array(0=>$clave, 1=>$valor->entity, 2=>$price['amount']));
    }

    if ($view->exposed_raw_input['sort_order']=='ASC') $ordenado = SortByKeyValue($milista, 2);
    else $ordenado = SortByKeyValue($milista, 2, SORT_DESC);

    $listafinal = array();
    foreach($ordenado as $datos) {
        array_push($listafinal, $view->result[$datos[0]]);
    }

    // Now, the pager
    $itemsperpage = 16;  // default items per page
    if ($view->exposed_raw_input['items_per_page']) $itemsperpage = $view->exposed_raw_input['items_per_page'];
    $page=1;
    if (isset($view->query->pager->current_page)) $page =  $view->query->pager->current_page;

    $indice = $itemsperpage * $page;

    if (($indice>sizeof($listafinal)) && ($itemsperpage!=0)) $indice = sizeof($listafinal) / $itemsperpage;

    $listafinal = array_slice($listafinal,$indice,$itemsperpage);

    // Lastly, I change the view results
    $view->result = $listafinal;
  }
}

To sort the array, I used the next functions:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
    if (empty($data) or empty($sortKey)) return $data;

    $ordered = $data;

    if ($sort_flags==SORT_ASC) uasort($ordered,'cmpasc');
    else uasort($ordered,'cmpdesc');

    return $ordered;
}

function cmpasc($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] < $b[2]) ? -1 : 1;
}

function cmpdesc($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] > $b[2]) ? -1 : 1;
}

I hope this solution could help someone with my same use case.

Sort commerce view by calculated price


JSON.stringify multidimensional

Question: I am trying to send a javascript object to PHP using JSON.stringify and I cannot find a solution. Here`s an example of what I have:
var small_array = [],
    final_array = [];

small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";

final_array.push(small_array);

console.log(JSON.stringify(final_array));

The output is "[[]]"
Any guidance on this one? Thanks
Comment: why not take an object instead an array?
Comment: why do you want to take arrays?
Comment: I am more interested to find out a solution for this case, if possible.
Answer: There are no associative arrays in javascript. They are called objects:
const smallObject = {
   ok: "not ok",
   not_ok: "ok"
};

const finalArray = [smallObject];

console.log(JSON.stringify(finalArray));

Answer: You're adding non-array-entry properties to the array. That's fine in JavaScript, but JSON doesn't have the notion of non-array-entry properties in an array (JSON arrays are just ordered sequences, whereas in JavaScript arrays are fully-fledged objects that provide special treatment to certain kinds of properties — more in my [ancient] blog post A Myth of Arrays).
For those property names (keys), you'd want a plain object, not an array:

var obj         = {}, // Note {}, not []
    final_array = [];

obj["ok"] = "ok";
obj["not_ok"] = "not_ok";

final_array.push(obj);

console.log(JSON.stringify(final_array));
Comment: `[ancient]` lol :)
Comment: Thank you, I got it now.
Answer: Objects in javacript are defined like this var obj = {}
var small_array = {},
final_array = {};

small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";

final_array = (small_array);

console.log(JSON.stringify(final_array));
VM1623:9 {"ok":"ok","not_ok":"not_ok"}

JSON.stringify multidimensional


Given the value of random variable $S_1,$ what is the best prediction $g(S_1)$ for the value of $S_2$?

Question: Suppose
$$
S_1 = \exp(X_1), \quad \quad X_1 \sim N(\mu_1, \sigma_1^2)
$$
$$
S_2 = \exp(\lambda X_1 + X_2), \quad \quad X_2 \sim N(\mu_2, \sigma_2^2).
$$
Assume $X_1$ and $X_2$ are independent and $\lambda \in \mathbb{R}$, and $\mu_1, \mu_2, \sigma_1, \sigma_2, \lambda$ are all known.
Given $S_1$, what is the best prediction we can make for the value of $S_2$, written as a function $g(S_1)$?
Here was my approach so far:
We want to find $\mathbb{E}(S_2 | S_1).$
\begin{align*}
\mathbb{E}(S_2 | S_1) &= \mathbb{E}\lbrack \exp(\lambda X_1+ X_2) | \exp(X_1) \rbrack \\
&=
\mathbb{E} \lbrack e^{\lambda X_1} \cdot e^{X_2}|e^{X_1} \rbrack  \\
&=
e^{\lambda X_1} \mathbb{E}\lbrack e^{X_2}|e^{X_1}\rbrack
\end{align*}
since we can "take out what is known" from within the conditional expectation. Now, this is what I'm unsure about. I believe the independence of $X_1$ and $X_2$ would imply the independence of $e^{X_1}$ and $e^{X_2}$. If this were true, then
$$
e^{\lambda X_1} \mathbb{E}\lbrack e^{X_2}|e^{X_1}\rbrack
=
e^{\lambda X_1} \cdot e^{X_2} = e^{X_2}\cdot S_1^\lambda.
$$
Like I said, I'm not sure about the independence of $e^{X_1}$ and $e^{X_2}$. If this is not true, why?
Answer: Since $X_1$ and $X_2$ are independent, it is true that $e^{X_1}$ and $e^{X_2}$ are independent. However, this implies
$$
\mathbb{E}[e^{X_2}\mid e^{X_1}]=\mathbb{E}[e^{X_2}]
$$
which is not what you have written.
Following up, this leads to
$$
\mathbb{E}[S_2\mid S_1] = e^{\lambda X_1}\mathbb{E}[e^{X_2}] = e^{\lambda X_1} e^{\mu_2+\frac{1}{2}\sigma_2^2} = \boxed{S_1^\lambda \cdot e^{\mu_2+\frac{1}{2}\sigma_2^2}}\,.
$$
Answer: You forgot the expectation term, we have
$$\mathbb{E}\lbrack e^{X_2}|e^{X_1}]=\mathbb{E}\lbrack e^{X_2}]$$
You should then get $S_1^{\lambda}e^{\mu_2+\frac{1}{2}\sigma_2^2}$
Comment: $S_1^\lambda \cdot e^{\mu_2+\frac{1}{2}\sigma_2^2}$, rather.
Comment: Ah yes I see. Thank you.
Comment: Exactly Clement C.


Rails 5.2 ActionController::UnknownFormat in PatientsController#index error

Question: class PatientsController < ApplicationController
  #require 'pry';  binding.pry
  def index
    respond_to do |format|
      format.json do
        render json: Patient.all
      end
    end
  end

end

I thought respond_to is included in rails? If I put a pry I can see request.format == :html is true Thanks for any help!
UDPATE:
after changing to
  def index
    respond_to do |format|
      format.json do
        render json: Patient.all
      end
      format.html do
        render :index
      end
    end
end

It works!
Comment: You have not specified a response for an "html" request so making one results in your error. If you were to visit "/patients.json" you should receive a response. If this should default to a json request then specify the format in your routes [Rails routing 3.5 Defining Defaults](https://guides.rubyonrails.org/routing.html#defining-defaults)
Comment: @engineersmnky Thanks that was the problem! IT is working now
Answer: What you see in the error message ActionController::UnknownFormat is telling you what is wrong.
As you mentioned, request.format returns :html but you only have format.json defined.
It looks like you don't format your JSON request properly. In order to do that you either should define headers for a JSON request or make request to the url that ends with .json (a feature from rails).
JSON request headers:
Content-Type: application/json
Accept: application/json


Erro com namespace

Question: Tenho a seguinte estrutura de pastas: Dentro da pasta Form existe um arquivo chamado Form.php (entre outros). O Form.php pertence a namespace 'Livro\Widgets\Form'. Existe outra pasta com o nome Wrapper e dentro dela tem o arquivo FormWrapper.php que pertence a namespace 'Livro\Widgets\Wrapper'. No construtor da classe FormWrapper é pra receber um objeto da Classe Form. Ai que vem o problema, o php não reconhece o s namespaces informados pelos 'use' e quando eu rodo o projeto aparece a seguinte mensagem:
Fatal error: Uncaught TypeError: Argument 1 passed to Livro\Widgets\Wrapper\FormWrapper::__construct() must be an instance of Livro\Widgets\Wrapper\Form, instance of Livro\Widgets\Form\Form given, called in C:\wamp64\www\projetos\phpoo4ed\App\Control\ContatoForm.php on line 20 and defined in C:\wamp64\www\projetos\phpoo4ed\Lib\Livro\Widgets\Wrapper\FormWrapper.php on line 14
Sendo que na pasta Wrapper não existe o arquivo Form. Alguma solução?
use Livro\Control\ActionInterface;
use Livro\Widgets\Form\FormElementInterface;

namespace Livro\Widgets\Form;

class Form {

    protected $title;
    protected $name;
    protected $fields;
    protected $actions;

    public function __construct($name = 'my_form') {
        $this->setName($name);
    }

    public function addField($label, FormElementInterface $object, $size = '100%') {
        $object->setSize($size);
        $object->setLabel($label);
        $object->fields[$object->getName()] = $object;
    }

    public function addAction($label, ActionInterface $action) {
        $this->actions[$label] = $action;
    }

    public function setData($object) {
        foreach ($this->fields as $name => $field) {
            if ($name and isset($object->$name)) {
                $field->setValue($object->$name);
            }
        }
    }

    public function getData($class = 'stdClass') {
        $object = new $class;

        foreach ($this->fields as $key => $fieldObject) {
            $val = isset($_POST[$key]) ? $_POST[$key] : '';
            $object->$key = $val;
        }

        foreach ($$_FILES as $key => $content) {
            $object->$key = $content['tmp_name'];
        }

        return $object;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function setTitle($title) {
        $this->title = $title;
    }

    public function getTitle() {
        return $this->title;
    }

    public function getFields() {
        return $this->fields;
    }

    public function getActions() {
        return $this->actions;
    }
}

<?php
use Livro\Widgets\Base\Element;
use Livro\Widgets\Container\Panel;
use Livro\Widgets\Form\Button;
use Livro\Widgets\Form\Form;

namespace Livro\Widgets\Wrapper;

class FormWrapper {

    private $decorated;

    public function __construct(Form $form) {
        $this->decorated = $form;
    }

    public function __call($method, $parameters) {
        return call_user_func(array($this->decorated, $method), $parameters);
    }

    public function show() {
        $element = new Element('form');
        $element->class = 'form-horizontal';
        $element->enctype = 'multipart/form-data';
        $element->method = 'post';
        $element->names = $this->decorated->getName();
        $element->width = '100%';

        foreach ($this->decorated->getFields() as $field) {
            $group = new Element('div');
            $group->class = 'form-group';

            $label = new Element('label');
            $label->class = 'col-sm-2 col-form-label';
            $label->add($field->getLabel());

            $col = new Element('div');
            $col->class = 'col-sm-10';
            $col->add($field);

            $field->class = 'form-control';
            $group->add($label);
            $group->add($col);
            $element->add($group);
        }

        $group = new Element('div');
        $i = 0;
        foreach ($this->decorated->getActions() as $label => $action) {
            $name = strtolower(str_replace('', '_', $label));
            $button = new Button($name);
            $button->setFormName($this->decorated->getName());
            $button->setAction($action, $label);
            $button->class = 'btn' . (($i == 0) ? 'btn-success' : 'btn-secondary');
            $group->add($button);
            $i++;
        }

        $panel = new Panel($this->decorated->getTitle());
        $panel->addContentBody($element);
        $panel->addContentFooter($group);
        $panel->show();
    }
}

Answer: O erro está na declaração do 'namespace' ser depois das declarações de 'use. Basta inverter que dá certo.
namespace Livro\Widgets\Form;

use Livro\Control\ActionInterface;
use Livro\Widgets\Form\FormElementInterface;

class Form {
    ...

Erro com namespace


Where can I find good statistics quizzes?

Question: Introductory, advanced, and even obscure, please.
Mostly to test myself. I like to make sure I know what the heck I'm talking about :)
Thanks
Comment: community wiki?
Answer: I wrote a post compiling links of  Practice Questions for Statistics in Psychology (Undergraduate Level).
http://jeromyanglim.blogspot.com/2009/12/practice-questions-for-statistics-in.html
The questions would fall into the introductory category.
Answer: Tests and thousands of sample questions are available on the ARTIST ("Assessment Resource Tools for Improving Statistical Thinking") site, https://app.gen.umn.edu/artist/tests/index.html .  Most are appropriate for an intro stats course.


troubleshooting AngularJS directives

Question: I am using ng-file-upload
i've declared a template and controller as per documentation, and have a basic semi-working example
index.html & view :
index.html

MyView.html

     <input type="file" ng-file-select="onFileSelect($files)" multiple>
     <button ng-click="foo()">foo</button>

app / controller:
var app = angular.module('app', ['angularFileUpload'])  // ng-file-upload

angular.module('app').controller('uploader', ['common', '$scope', '$http', '$upload', uploader]);

function uploader(common, $scope, $http, $upload) {
...
    $scope.foo = function () {
        log('bar..');
    };
    $scope.fileUploadObj = "TestString";
    $scope.onFilesSelect = function ($files) {
        log('files selected!');
        ...
    }

I added function foo to ensure that my controller is bound, and that works. However onFileSelect never gets triggered and i don't see any errors.
looking at Angular.js Batarang profiler, i see the following for the scope in question.
Models for (007)
{
    foo: null
    fileUploadObj: TestString
    onFilesSelect: null
}

both functions show as null, but i know foo is wired.
so my question would be, how do i troubleshoot where the disconnect happens for onFileSelect($files).
Answer: ng-file-select="onFileSelect($files)"

vs
$scope.onFilesSelect

one has an s in File
Comment: wow.. cant believe this.. Actually initially i had handlers for single and multiple files (both on the view and controller), and none of them worked. so i narrowed it down to simplest case, and overlooked this small detail :) .. and not sure what i did but it does indeed work now after correcting the name, thanks.
Comment: happens to the best of us

troubleshooting AngularJS directives


C++ Command line program unwantedly pauses on Windows 8. How to prevent?

Question: I have written a C++ CMD program to do a numerically intensive simulation, which takes about 1 hour to run on my Laptop with an i7 processor on Windows 8.
The program prints a status update to the command line about every 5 seconds.
But from time to time, the programs suddenly pauses and does not resume until I click the cursor into the CMD window and hit Enter.
While the program pauses the CPU load, displayed in the taskmanager, also drops to almos 0% (instead of the ~17%).
My program does at no point during the simulation ask for user input.
I assume that for some reason the operating system pauses execution of my program.
My Laptop is connected to the powersupply and all energy saving options are currently disabled.
This behaviour does not always happen, even with the very same program just being restarted.
How do I prevent this unwanted pause?
Could anyone please give me a tip, where I could start searching?
Thank you very much in advance!
Comment: Do you have **"QuickEdit" mode** turned on for your command prompt window? Right-click on the title bar, select Properties, look on the first tab.
Comment: Can you reproduce the behavior while running under a debugger?  If so, instead of clicking into the window use the debugger to break into the program and see what it's doing.
Comment: What Cody Gray is asking for: If you click on the cmd window with the mouse your program will be paused. This is by design to allow to check the cmd output of an busy application. Could it be that you from time to time by accident pause your own program?
Comment: Cody Gray and Alois Kraus were absolutely correct.
I did (when switching to the program that was running in the background) from time to time accidently pause my own program by clicking into it.
Thank you for the answer and please excuse my late reply.
Answer: I suspect if you redirect your program's output to file, all will be good.
In other words, instead of typing this at the command prompt:
d:\MyAppDirectory>  myprogram.exe

Type this instead:
d:\MyAppDirectory>  myprogram.exe > output.txt

The above will place all of your program's output into the output.txt file.
If you need to monitor the program's output in real time, you can probably find a "tail" program for Windows to run in a seperate window.  ala tail output.txt while your main program is running (Google for "tail for windows")
Answer: You can try something along the lines of:
DWORD mode = PIPE_NOWAIT;
SetNamedPipeHandleState(GetStdHandle(STD_OUTPUT_HANDLE), &mode, NULL, NULL);

at the beginning of your program. However, this assumes that there isn't an actual bug in your program and you aren't waiting for input yourself.


String replace não está realizando troca

Question: Eu não estou conseguindo alter o caractere da minha string com a do valor do mapa, se forem iguais: chave e caractere.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Mapa {

    public static Map<Character, Character> mapa;

    public static void main(String[] args) {

        mapa = new HashMap<>();

        mapa.put('á', 'a');
        mapa.put('é', 'e');
        mapa.put('í', 'i');
        mapa.put('ó', 'o');
        mapa.put('ú', 'u');

        String str = "cása";
        for(int i=0; i < str.length(); i++) {
            Character ch = str.charAt(i);
            for(Entry<Character, Character> entry : mapa.entrySet()) {
                if(ch == entry.getKey()) {
                    str = str.replace(ch, entry.getValue());
                }
            }
        }

        // Aqui esta retornando a mesma string.
        System.out.println(str);
    }
}

Answer: Substitua ch == entry.getKey() por ch.equals(entry.getKey()).
== verifica se as duas referências apontam para uma mesma instância de um objeto. Já a implementação do método equals na class Character verifica se os valores deles são iguais.


datatable, how to display table sorted by a column in this date format?

Question: I would like to display the table sorted by a column called createdAt that has this format :
2015-03-09T14:46:57.678-04:00

Comment: not clear what you asking, if u have data in array, just sort it by date
Comment: I don't have access to the api (that was sorted by email), the default sorting for date in jquery datatables is just for simple date format, I need a way to sort by the above date format in the client side .
Comment: You could get simple date from this complicated one. And then sort.
var simpleDate = complicatedDate.substr(0, 10)+" "+complicatedDate.substr(11, 8);
Answer: The above date format can be parsed by Date.parse(). So, if you have some columns like this :

2015-03-09T14:46:54.678-04:00

2015-03-09T14:46:55.678-04:00

2015-03-09T14:46:56.678-04:00

2015-02-09T14:46:57.678-04:00

2015-02-09T14:46:56.678-04:00

2015-03-10T02:46:57.678-04:00

2015-03-11T14:41:57.678-04:00

2015-03-09T12:46:57.678-04:00

2015-03-09T01:46:57.678-04:00

you can make a simple custom sorting plugin and use it for that particular column :
$.fn.dataTableExt.oSort['time-date-sort-pre'] = function(value) {
    return Date.parse(value);
};
$.fn.dataTableExt.oSort['time-date-sort-asc'] = function(a,b) {
    return a-b;
};
$.fn.dataTableExt.oSort['time-date-sort-desc'] = function(a,b) {
    return b-a;
};
var table = $('#example').DataTable({
    columnDefs : [
        { type: 'time-date-sort',
          targets: [0]
        }
    ]
});

demo -> http://jsfiddle.net/kkrqzvx4/
Comment: Thanks lot, I tried  type: 'time-date-sort-desc'  but it does not work.
Comment: The same here , how to display them to show the latest first, I think in desc way. Thanks.
Comment: @user1034127 and @akram -  add `order: [[ 0, "desc" ]]` to the options ->  http://jsfiddle.net/kkrqzvx4/2/ to set descending as default ordering for the first column.
Comment: This is not correct and doesn't require any sorting plug-ins, see http://jsfiddle.net/kkrqzvx4/13/


Sort Enum.values() alphabetically and the add them to a Spinner ArrayAdapter

Question: I'm developing an Android application that works with a Web service.
I want to sort alphabetically Enum.values() by its description.
I have this Enum:
public enum Stature
{
    tall (0, MSDApplication.getAppContext().getString(R.string.stature_tall)),
    average(1, MSDApplication.getAppContext().getString(R.string.stature_average)),
    small(2, MSDApplication.getAppContext().getString(R.string.stature_small));

    private final int stature;
    private final String statureString;

    Stature(int anStature, String anStatureString) { stature = anStature; statureString = anStatureString; }

    public int getValue() { return stature; }

    @Override
    public String toString() { return statureString; }
}

Maybe, this is not the best choice to use an Enum, but I'm very new on Java development.
Do you know how can I sort it alphabetically using its statureString?
I want to do this because I want to use these Enum.values() on an ArrayAdapter:
mSpinStature.setAdapter(new ArrayAdapter<Stature>(mActivity, android.R.layout.simple_dropdown_item_1line, Stature.values()));

And I want to get the Stature selected item here:
private OnItemSelectedListener listener = new OnItemSelectedListener()
{

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long aid)
    {
        if (parent.equals(mSpinStature))
        {
            Stature item = (Stature)parent.getAdapter().getItem(pos);
            Log.v("TAG", item.toString() + item.getValue());
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0)
    {
    }

};

Comment: I have updated my question with more details.
Answer: How about adding a method to the enum
enum Stature {
    tall, average, small;

    public static Stature[] getSortedVaules() {
        Stature[] statures = values();
        Arrays.sort(statures, EnumByNameComparator.INSTANCE);
        return statures;
    }

    private static class EnumByNameComparator implements Comparator<Enum<?>> {

        public static final Comparator<Enum<?>> INSTANCE = new EnumByNameComparator();

        public int compare(Enum<?> enum1, Enum<?> enum2) {
            return enum1.name().compareTo(enum2.name());
        }

    }

}

public class StatureTest {

    @Test
    public void getSortedValues() {
        Stature[] normalValues = Stature.values();
        Assert.assertEquals(Stature.tall, normalValues[0]);
        Assert.assertEquals(Stature.average, normalValues[1]);
        Assert.assertEquals(Stature.small, normalValues[2]);

        Stature[] sortedVaules = Stature.getSortedVaules();
        Assert.assertEquals(Stature.average, sortedVaules[0]);
        Assert.assertEquals(Stature.small, sortedVaules[1]);
        Assert.assertEquals(Stature.tall, sortedVaules[2]);
    }
}

Comment: Use a java.text.Collator if you want Locale-specific (case insensitive) order and not the unicode codepoints as order.
Comment: If you change `return enum1.name().compareTo(enum2.name());` with `return enum1.toString().compareTo(enum2.toString());` it works!!
Answer: Enums are sorted by declaration presedence. So the easiest way would be to declare them in desired order.
You could also try using Comparator interface implementing compare method.


Como manter o mesmo layout para as diferentes versões?

Question: Como posso manter o layout de meus aplicativos para as diferentes versões de Android?
Exemplo: Um EditText tem layout na versão 2.1 e outro nas versões 4.x, como manter o layout da versão 4 nas versões anteriores?
Comment: Caezar, você pode conferir nessa outra dúvida. [http://pt.stackoverflow.com/questions/71731/design-em-diferentes-vers%C3%B5es-do-android/71736#71736]
Answer: Basta que você informe uma cor de fundo que ele já vai perder as características da versão. Exemplo:
<EditText
  android:background="#DDDDDD" />


Overlay layer shown for ajax calls but not when called without ajax

Question: I have a "loading" overlay that I show when I make ajax calls. This works fine.
The overlay is defined in css as:
.loading{
    position:fixed;
    z-index:1010;
    top:0;
    left:0;
    height:100%;
    width:100%;
    background: rgba( 255, 255, 255, .9 )
                url('http://url to image')
                50% 50%
                no-repeat;
}

And it is called in a js function as
function showLoading()
{
    $("#layer").addClass("loading");
}

Once the ajax call returns I call a hideLoading() which hides the layer. All this works fine.
Now I have a button on the click on which I do a client side process intensive calculation, at the end of which I load additional content into the DOM. This function is say calcDataPoints(). I want it so that when someone clicks the calc button, I show the overlay, do the calculation and update the DOM and then hide the overlay.
So I do:
showLoading();
calcDataPoints();
hideLoading();

The problem is that the overlay never gets rendered. It shows for a microsecond when the calc has "completed" and not "before". So it does not have the desired effect.
What am I doing incorrectly here? How can I have the overlay shown before the calc begins and close it once the calc is over and I have written data into the DOM?
Any pointers are greatly appreciated!
Comment: Suggest looking at [this](http://stackoverflow.com/questions/5187968/how-should-i-call-3-functions-in-order-to-execute-them-one-after-the-other) answer.
Comment: Can you post the full code you're running?
Answer: call like that:
setTimeout(showLoading, 10);
setTimeout(calcDataPoints, 2000);
setTimeout(hideLoading, 2000);

In this way we can call function like asynchronously .


Let $x_1+x_2,...+x_{12}=12$. What are all the Integer solutions of $x_1,x_2,...,x_{12}$($\geq 0$)?

Question: I being trying to solve this, and I know there exists a formula but I can't recall it.
What I tried was a lower scenario, i.e, when there is only $x_1, x_2, x_3$.
I took the idea of supposing that $x_1=0$. Then, there are 13 possible solutions for $x_2, x_3$. Then when $x_1=1$ there are 12 possibilities, and so on. Then there exist $1+2+...+13=91$ possibilities fixing $x_1$. Similarly, fixing $x_2, x_3$ we get 91+91 possibilities. So the total possibilities is 273.
But how would I generalize this for when I have 12 x's?
Any help is deeply appreciated!
Comment: https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)
Comment: What you mean to ask is how many nonnegative integers solutions to the equation are there?
Comment: It is possible that "integer programming" could offer an answer, where you would have a dummy objective function and the equation as a constraint assuming all variables are >0.
Answer: The number of non-negative integer solutions to the system of equations:
$$\begin{cases}x_1+x_2+\dots+x_k=n\\x_i\geq 0\end{cases}$$
will be
$$\binom{n+k-1}{k-1}$$
This is seen by using a standard stars-and-bars style argument by comparing this situation to the one where we arrange a collection of $n$ stars and $k-1$ bars in a row and interpreting the number of stars in each group separated by the bars as the value of $x_i$.
Comment: On the wikipedia page you sent, it was (n+1,k-1) though...
Comment: @pratik there are many similar questions, the one asking how many *positive* integer solutions there are rather than just non-negative, the one where there are n variables instead of k, the one where the variables add up to k instead of n, etc... The version of the problem as written has the answer I write above and the most common explanation for why is as mentioned using the concept of stars and bars.


How to use T-SQL Update to change case sensitive results

Question: These are the results I got for the the table Account Ex

I need to use T-SQL to change some of the results that have 'new' or 'NEW' to just 'New'
I attempted this code below is this correct
UPDATE Account Ex
Set[1f9ae786-9aae-4478-8254-3b683804ccfa] = 'New'
WHERE [1f9ae786-9aae-4478-8254-3b683804ccfa] COLLATE SQL_Latin1_General_CP1_CS_AS = 'NEW' AND 'new'

Comment: `AND 'new'` what? That's only half a boolean expression.
Comment: Side Note; A GUID is an odd choice for a column's name.
Comment: You could try this: `UPDATE AccountEx SET [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'New'
WHERE LOWER([1f9ae786-9aae-4478-8254-3b683804ccfa]) = 'new'`. It's a bit blunt and does not perform very well, but I assume you want to either run this only once in a while, or make sure that only correct values will be entered by client applications, or make some redesigns to your data model to avoid such kinds of issues in the first place.
Answer: SQL Server's default collation is case insensitive, so this might do what you want:
UPDATE AccountEx
     Set [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'New'
     WHERE [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'new';

Alternatively, this should work regardless of collation:
UPDATE AccountEx
     Set [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'New'
     WHERE lower([1f9ae786-9aae-4478-8254-3b683804ccfa]) = 'new';

The only downside is that this updates all rows that have "new" in any case.  If the table is not very large, that is not a big deal.
Answer: Try it at the end
UPDATE Account Ex
    Set [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'New'
WHERE
    [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'NEW'
    OR [1f9ae786-9aae-4478-8254-3b683804ccfa] = 'new'
COLLATE SQL_Latin1_General_CP1_CS_AS

But couldnt you just update to New since you want all variants of new|NEW|NEw|nEw|etc to be New.  Wont hurt to update existing value as it will be set to the same.


disadvantages variational inference

Question: A lot of methods utilize variational inference for hyperparameter calculation.
What are the advantages and disadvantages of variational inference ?
(ex: does it guarantee a global optimal ? )
Answer: Further disadvantages:

The outcome tends to depend heavily on the starting point for the optimization. Example: this paper which is heavily cited but known to have severe problems (software packages based on it were later withdrawn, etc.)
The calculations required to figure out what you are optimizing are often very complicated. (See any paper on variational inference.)

On the plus side, there is an excellent introduction to the subject in Mackay's textbook Information Theory, Inference and Learning Algorithms.
Answer: Briefly:

Disadvantages: approximate, very little theory around it
Advantages: speed, scalability, novelty

There isn't much theory around variational inference. However you define "optimal" (qv below), you probably can't expect to obtain it.
VI is a method for approximating a difficult-to-compute probability density, $p$, by optimization. This is done by suggesting a family of distributions $\mathcal Q$ and finding the member $q \in \mathcal Q$ that has the lowest Kullback–Leibler divergence $KL(q \|p)$. How well you can approximate $p$ naturally depends on your choice of $\mathcal Q$, but you can assume that some aspect of $p$ is lost when substituting it by $q$.
VI doesn't guarantee you find the globally optimal member $q \in \mathcal Q$ either. A common choice is to use what's called the mean-field variational family and find $q$ by coordinate ascent. You can find a local optimum.
A big advantage is that VI is very fast and scales well to large datasets. It is natural to compare with MCMC methods as these solve the same problem, see the answer to this related question, which compares the two.

Reading:
David M. Blei, Alp Kucukelbir, Jon D. McAuliffe Variational Inference: A Review for Statisticians

disadvantages variational inference


How to send certain data from parent Fragment to Child Fragment?

Question: I'm an Android novice.
I want to communicate using the interface as follows, but it doesn't work properly. Null Point continues to occur.
I used the viewpager Fragment to organize a Tab Fragment consisting of parents and children.
I want to send some data from parents to children. But it's not easy.
I'm not sure why. I attach my code together. Can you tell me where I'm wrong?!
Parent Fragment
    public class fragment_menu_2_category extends Fragment implements ViewPager.OnPageChangeListener{

    public static Object Test_Listener;

    ImageView menu_2_category_open_btn;

    //interface
    private CustomListener customListener;

    public interface CustomListener{
        void onPositiveClicked(String name);

    }

    public void setListener(CustomListener customDialogListener){
        this.customListener = customDialogListener;
    }

    static String test_bundel="";
    public static int a = 0;

    public static fragment_menu_2_category newInstance()
    {
        return new fragment_menu_2_category();
    }

    private ViewPager mViewPager;

    SectionPageAdapter adapter;

    fragment_menu_2_category_Outer fragment_menu_2_category_outer;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_category, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mViewPager = (ViewPager) view.findViewById(R.id.container11);
        adapter = new SectionPageAdapter(getChildFragmentManager());

        adapter.addFragment(new fragment_menu_2_category_All(), "ALL");
        adapter.addFragment(new fragment_menu_2_category_Outer(), "OUTER");
        adapter.addFragment(new fragment_menu_2_category_Top(), "TOP");
        adapter.addFragment(new fragment_menu_2_category_Skirt(), "SKIRT");
        adapter.addFragment(new fragment_menu_2_category_Pants(), "PANTS");
        adapter.addFragment(new fragment_menu_2_category_Onepiece(), "ONEPIECE");

        mViewPager.setAdapter(adapter);

        mViewPager.setOffscreenPageLimit(3);

        TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        menu_2_category_open_btn = view.findViewById(R.id.menu_2_category_open_btn);
        menu_2_category_open_btn.setOnClickListener(open_category);

    }

     View.OnClickListener open_category = new View.OnClickListener() {
         @Override
         public void onClick(View v) {

             category_dialog category_dialog = new category_dialog(getContext(), R.layout.menu_2_category_dialog);

             category_dialog.show();

             category_dialog.setDialogListener(new category_dialog.CustomDialogListener() {
                 @Override
                 public void onPositiveClicked(String name) {

                   category_dialog.dismiss();

                     String test_date = "test date";
                     customListener.onPositiveClicked(test_date);
                     fragment_menu_2_category_Outer fragment_menu_2_category_outer = new fragment_menu_2_category_Outer();

                   adapter.replaceFragment(1, fragment_menu_2_category_outer,"OUTER");
                  //뷰페이저
                   mViewPager.setCurrentItem(1, true);
                   adapter.notifyDataSetChanged();

                 }

             });

         }

     };

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

      adapter.notifyDataSetChanged();

    }
}

Childe Fragment
public class fragment_menu_2_category_Outer extends Fragment {

    RecyclerView category_name_recyclerview;
    fragment_menu_2_category_name_Adapter name_adapter;
    ArrayList<fragment_menu_2_category_name_Array> name_array;

    RecyclerView outer_category_product_recyclerview;
    fragment_menu_2_category_Adapter outer_category_adapter;
    ArrayList<fragment_menu_2_category_Array> outer_category_array;

    int get_category_position = 0;

    public static fragment_menu_2_category_Outer newInstance(String name)
    {
        fragment_menu_2_category_Outer fragment = new fragment_menu_2_category_Outer();
        Bundle args = new Bundle();
        args.putString("key", name);
       fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(getArguments()!=null){
        a = getArguments().getString("key");
      }

        }

    @Override
    public void onResume() {
        super.onResume();

        fragment_menu_2_category fragment_menu_2_category = new fragment_menu_2_category();

        fragment_menu_2_category.setListener(new fragment_menu_2_category.CustomListener() {
            @Override
            public void onPositiveClicked(String name11) {
              Log.d("Test", name11);
           }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

       return inflater.inflate(R.layout.fragment_menu_2_category_outer, container, false);

    }

ViewPagerAdapter
public class SectionPageAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    public SectionPageAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public int getItemPosition(@NonNull Object object) {

        return POSITION_NONE;

    }

    public void replaceFragment(int index, Fragment fragment, String title) {

        if(index==1)
        {

            mFragmentList.set(index, fragment);

        }

        mFragmentTitleList.set(index, title);
    }
}

Answer: In the parent fragment onCreateView(), get the reference of your child fragment.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View view = inflater.inflate(R.layout.parent_fragment, container, false);
    YourChildFragment child = (YourChildFragment) getChildFragmentManager().findFragmentById(R.id.child_fragment_id);

    //do whatever you want with your child (fragment)
    //e.g.
    child.newInstance("hello");

    return view;
}

In this way, you won't need to make methods static. :)
Comment: Thank you for your quick reply. I'd like to ask you one more question, if you don't mind. What should I do if I want to create a child Fragment and deliver a new value with any click?


hiding urls in a popup window

Question: I am having problem in hiding url in a popup window in Mozilla.I tried using location=no in the popup window parameter but it was no help.Any suggestion or alternative.Is there any way to encrypt the url using javascript and decrypt using java?
Comment: @Jigar JoshiThank you very much for the reply.Will that hide the url in the addressbar or hide the addressbar itself of the popup window?
Answer: I think if you're opening new window in javascript then you can write:-
var win = window.open("about:blank","");

And the from the variable win you can acess the html of the new opened window. Now add an iframe win the body of the new window and set the src to your required src. Like:-
win.document.write('');

hiding urls in a popup window


Problema em gerar múltiplos gráficos

Question: Tenho pouca experiencia com o R e estou apanhando um bocado para gerar um ggplot com 5 geom_lin. Poderiam me ajudar?
A base de dados são cinco séries anuais, em meses.
     2014    2015   2016    2017   2018
jan   10      8     7,5     5      9
Fev   11     12     8      2,35    4,1
Mar   7,5     9     2,5     1,7     3,57
Abr   2,78    11,5  21      15      18
Mai   10      8     7,5     5      9
jun   11     12     8      2,35    4,1
jul   11     12     8      2,35    4,1
ago   7,5     9     2,5     1,7     3,57
Set   7,5     9     2,5     1,7     3,57
out   2,78    11,5  21      15      18
nov   10      8     7,5     5      9
dez   11     12     8      2,35    4,1

data.frame(dados)
a= dados$2014
b= dados$2015
c= dados$2016
d= dados$2017
e= dados$2018
f= dados$meses

ggplot(data=dados, aes(meses())+
geom_line(aes(y=a), color="red")+
geom_line(aes(y=b), color="blue")+
geom_line(aes(y=c), color="green")+
geom_line(aes(y=d), color= "black")+
geom_line(aes(y=e), color="white")

Quando testo a rotina, mostra que esta faltando uma aes, quando corrijo fala para ajustar os parâmetros (x, y). Acredito que o R esteja considerando o número dos dados do eixo y, como eixo x, em alguma situação. O R ainda está desordenando os meses no eixo x, acredita que possa ser a falha para plotar o grafico???
Valeu!
Comment: Bem-vindo ao StackOverflow em Português! Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, [dê uma olhada neste link](https://pt.meta.stackoverflow.com/questions/824/como-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Answer: Primeiro reestruturei seus dados para o formato long (colunas com os meses, anos e os valores) utilizando a função gather do pacote tidyr:
library(tidyr)
dados_long <- gather(dados, ano, valor, X2014:X2018)

O problema dos meses em ordem alfabética, eu contornei forçando os níveis do fator "respeitarem" a ordem que aparece na coluna meses. Para a criação de um gráfico para cada ano, os agrupei dentro do aes com a opção group e os diferenciei com cores diferentes: colour = ano.
library(ggplot2)
ggplot(data = dados_long, aes(x = factor(meses, level = dados$meses), y = valor, group = ano, colour = ano)) +
  geom_line() +
  xlab("Meses")

dput dos dados:
structure(list(meses = c("jan", "Fev", "Mar", "Abr", "Mai", "jun",
"jul", "ago", "Set", "out", "nov", "dez"), X2014 = c(10, 11,
7.5, 2.78, 10, 11, 11, 7.5, 7.5, 2.78, 10, 11), X2015 = c(8,
12, 9, 11.5, 8, 12, 12, 9, 9, 11.5, 8, 12), X2016 = c(7.5, 8,
2.5, 21, 7.5, 8, 8, 2.5, 2.5, 21, 7.5, 8), X2017 = c(5, 2.35,
1.7, 15, 5, 2.35, 2.35, 1.7, 1.7, 15, 5, 2.35), X2018 = c(9,
4.1, 3.57, 18, 9, 4.1, 4.1, 3.57, 3.57, 18, 9, 4.1)), .Names = c("meses",
"X2014", "X2015", "X2016", "X2017", "X2018"), class = "data.frame", row.names = c(NA, -12L))

Answer: Você precisa transformar seus dados de "wide" para "long" format. Eu uso a função melt do pacote data.table:
# criando os dados
set.seed(1)
yrs <- c(2014:2018)

df <- do.call(cbind, lapply(yrs, function(x) {
  out <- data.frame(runif(12, 0, 12))
  names(out) <- x
  out
}))

df <- do.call(cbind, list(data.frame(meses = factor(month.name, levels = month.name)), df))

# carregue o pacote ggplot2
library(ggplot2)
dados <- data.table::melt(df, "meses") # transforme de wide para long

ggplot(dados, aes(meses, value)) +
 geom_line(aes(group = variable, color = variable)) + # precisa agroupar a variavel
 theme(axis.text.x = element_text(angle = 45, vjust = 0.75))

Gráfico:

Problema em gerar múltiplos gráficos


Why ECU Calibration Required

Question: Why ECU Calibration is required in Software Development and testing?
Example would be nice to understand
Answer: During the course of my career, several engineers have enquired about why calibration is required. The answers which I provided can range from a simple clarification regarding how calibration was necessary to ensure certain performance based on a set of optimal performance characteristics that guards against defects or poor performance of electronic systems to more elaborate discussions on the actual predictive mechanisms that ensures a desired system performance.
The question asked here was why an ECU calibration should be done in software development and testing. An Electronic Control Unit(ECU) is a module which comprises of several embedded(integrated circuits, microcontrollers etc) hardware and software functioning as a whole system that controls the fuel injection in a car as shown in Figure 1 below.
Simplified ECU block diagram
Figure 1
As depicted in the diagram, the ECU is connected to other sensors, power, network and other external systems. As such, there is a need to characterise these parameters into external sensory parameters, power parameters, automotive control parameters and network parameters according to the various states that an ECU can be in. An ECU state refers to the behaviour of the ECU i.e. its operation. Hence, this gives rise to a state-machine model that indicates the actual ECU activity together with its configured parameters.
Calibration, thus provides default (known) good values to the various parameters associated with each distinct state of operation. Hence, calibration methodology is adopted during development and testing in order to align an ECU module performance characteristics to an expected set of performance. Such setup ensures the correct processing of observable parameters for accurate prediction of system performance for all available system states.

Why ECU Calibration Required


Can I partition the only independent variable in the regression into two groups and compare the slopes between the partitioned groups?

Question: I have a regression model of y = a + b * x and both variables are continuous. I've found that the coefficient of x, which is b, is statistically significant in the regression y = a + b*x.
Now I want to test whether the coefficients of x will be different for small and large values of x if I partition x into two groups (small vs. large). For example, how can I test whether b1 and b2 are statistically different?
y1 = a1 + b1 * x, for x = a cutoff value of x (large values of x)
I found the method discussed in the Stata FAQs can be helpful https://www.stata.com/support/faqs/statistics/test-equality-of-coefficients/

However, I am not sure if it is OK that my y and z are essentially the same variable, i.e. y1 for small values of x and y2 for large values of x.
Also, one answer to the question How to compare two regression slopes for one predictor on two different outcomes? said the dependent variables in the method above, namely y and z, need to be independent. If it is true, how can I test my y1 and y2 are independent from each other?
Comment: See posts with the [tag:change-point] tag.
Comment: Would you please post the data, or a link to the data?
Comment: @JamesPhillips the data can be accessed via this link https://docs.google.com/spreadsheets/d/1ffb2rNZQpUHiB6OmqIXoz0riz4Qyyh2Dnq1RxEycj68/edit?usp=sharing                 Thanks!
Comment: @whuber Thanks for the reply! But I am more concerned about whether I can set a cutoff value k for the continuous variable x and then run a regression like y = a + b * x + c * dummy x ( x < k or x >= k). Also, a lot of articles and paper I found suggest it is problematic to categorize a continuous variable http://biostat.mc.vanderbilt.edu/wiki/Main/CatContinuous
Comment: You are asking to identify a single changepoint in a regression.  This is not a matter of converting a continuous variable into a category: $x$ still enters directly into the model.
Comment: I see a potential problem, There would two different straight lines, "y = bx + a" and "y = bx + a + c", which means that at the cutoff value of k the lines will be disjointed with a gap between them. Is this acceptable, or are you looking for a "broken stick" model where both lines are equal at the value of "k"?
Comment: @whuber But is it ok to have a continuous variable of x and a dummy variable of x in the same regression model? Is the regression y = a + b * x + c * dummy of x correct (dummy of x determined by the cutoff value of k? More importantly, if in the regression y = a + b * x + c * dummy of x + d * x * dummy of x, I find c and d are not statistically significant, can I say that the coefficients of x are not different for x < k and x >=k? Thanks!
Comment: @JamesPhillips  Actually, I am more interested in whether I can say the coefficients of x are different for x < k and x >=k based on the regression model y = a + b * x + c * dummy of x + d * x * dummy of x, and the dummy of x is categorized by x < k and x >= k. For example, if I find c and d are not statistically significant, can I say that the coefficients of x are not different for x < k and x >=k?  Thanks!
Comment: Absolutely,  Indeed, there's practically no way to exclude this possibility, because it just might happen in a dataset of $(x,y,z)$ values that in every case $z=\mathcal{I}(x\ge k)$ for some number $k.$ There's no difference between using the values of $z$ you collected or using the values as computed from $x.$ As far as your example goes, (1) you should use an $F$ test to evaluate $c$ and $d$ simultaneously and (2) if you estimated $k$ from the data, you need a test that treats $k$ as a parameter, too.  (This will make all coefficients less significant.)
Comment: Have you considered threshold models?
Answer: Using the data linked to in the comments, you can do this in the R package mcp:
Define a model with two linear segments:
model = list(
  y ~ 1 + x,
  ~ 1 + x
)

Now sample it (setting adapt high to reach convergence) and test the hypothesis that the first slope is greater than the second. I get a evidence ratio (Bayes Factor) of around 1.5.
library(mcp)
fit = mcp(model, data = df, adapt = 4000)
hypothesis(fit, "x_1 > x_2")

Note that:

This dataset contains very little information about such a change point. Therefore it is hard to identify and the model fit is poor (poor convergence between chains). To help it along, maybe update the priors to better represent the knowledge about the data you are modeling, e.g., if the change point is known to occur in a certain interval or if the slopes are known to be positive.
Set segment 2 to ~ 0 + x if the slopes are joined.

Read more on the mcp website.


Probability Distributions : "Mode" vs. "Expectation"

Question: I have often heard the argument that in higher dimensions: the "mode" (most common value) of a probability distribution function does not correspond to the "expectation" (mean) of the probability distribution function. The implication of this argument is that it becomes less meaningful to calculate the "mode" of a probability distribution function (i.e. the Bayesian MAP estimate), but rather it now becomes more advantageous to calculate the "expected value" of the probability distribution function (e.g. via MCMC).
I am trying to better understand this logic:

I have heard that in high dimensional space, (it can be mathematically proven that) the majority of the volume of a hypersphere becomes concentrated around a thin outer ring of the hypersphere. If you apply this metaphor to high dimensional data, this means that the majority of the data is located around the extremities of the space, whereas most of the space itself is likely to be "sparsely populated". I can understand this argument. (e.g. Imagine an onion ring (thin torus) - the data would be the "onion crust" and all the volume in the middle is empty)

What I don't understand is the following: In high dimensional space, why should the difference between the "mode" and the "expectation" of the probability distribution function be any more different than in low dimensional space? In high dimensional space, why is the "mode" not as useful (in terms of information, in terms of describing the probability distribution) as the "expectation"? In high dimensional space, logic tells us that most of the space is empty and the data is concentrated around the exterior. One could make the argument that "most of the data is located around the exterior", therefore the "mode" and "expectation" should be both as informative?

I have attached this picture as reference: https://i.stack.imgur.com/fOGE6.jpg

Can someone please help me better understand this?
Comment: You don't need high dimensions e.g. in 1D you just need an asymmetrical distribution, like exponential, for mode not to correspond to expected value.
Comment: The "mode" displayed in Figure 9-4 is *not* the mode of the distribution.  It is the mode of the distribution of radial distances from the mode of the distribution, as explained in the horizontal axis label.
Comment: @Tim One does not even need an asymmetrical distribution: $|x|\mathbb I_{[-1,1]}$ is a (bimodal) symmetric pdf with mean $0$ but modes $\pm 1$.
Comment: But the question is if this becomes *more pronounced* with increasing dimension ...
Comment: Does this answer your question? [How best to summarize a predictive discrete distribution in a single number?](https://stats.stackexchange.com/questions/214515/how-best-to-summarize-a-predictive-discrete-distribution-in-a-single-number)
Answer: It is not clear what exactly the OP is asking. Consider, for example, the density of the vector random variable $(X_1, X_2, \ldots, X_n)$ whose component $X_i$ are $n$ independent standard normal random variables. The mode of this density (the location of the global maximum of the value of the density) is the origin. The expected value of the vector random variable is the vector of expected values of the individual random variables, and thus is also the origin.  Neither of these parameters is a satisfactory measure of where the bulk of the probability mass lies: most of the probability mass lies in a (fairly large volumed) shell quite distant from the origin.  Note that $R^2 = \sum_k X_k^2$ is a $\chi^2$ random variable with $n$ degrees of freedom. For large values of $n$, most of the probability mass of this $\chi^2$ random variable lies in the region $[n-\sqrt{18n} < R^2 < n+\sqrt{18n}]$.  Put another way, if we look at $P\left(\sum_k X_k^2 < r^2\right)$ as a function of $r$, this quantity increases very very slowly when $r$ is small -- despite the density having large value there -- and then increases rapidly when $r$ is close to $\sqrt{n}$, arriving at a value quite close to $1$ -- this is the shell where most of the probability mass is -- and then once again returns to its very very slow rate of increase, asymtpotically approaching its final value of $1$.  If we look at the graph in the OP's question, we see this quite clearly. For $n=10$, the peak is at $r \approx\sqrt{10} = 3.16\cdots$; for $n=100$ at $r \approx10$, and for $n=1000$, at $r\approx \sqrt{1000} = 10\sqrt{10} =31.6\cdots$.
If the question is, as Moderator Kjetil B Halvorsen says, whether the effect becomes more pronounced as $n$ gets larger, the answer is Yes, the distance of this peak from the mode or expected value increases with $n$ but only sublinearly. Fortunately for us, the curse of dimensionality does not increase as $O(n)$, only as $O(\sqrt n)$.


Como salvar relatório FastReport em PDF em modo silencioso?

Question: Eu consigo gerar o PDF a partir do código abaixo:
fdm.frxPDFExport.FileName := 'C:\PASTA_TESTE\ARQUIVO_TESTE.PDF';
frxReport.PrepareReport();
frxReport.Export(fdm.frxPDFExport);

O detalhe é que ele me mostra a tela para escolher onde salvar o arquivo.
Eu gostaria de salvar sem intervenção do usuário, já que determinei o caminho e nome do arquivo.
Answer: Altere a propriedade FileName e DefaultPath para o que você precisa no export.
Também altere frxrRelatorio.PrintOptions.ShowDialog := False; para não exibir a caixa de dialog
Comment: Olá Gabriel, obrigado pela resposta, além do PrintOptions = False, também coloquei fdm.frxPDFExport.ShowDialog := False; e deu certo.
Comment: Isso, eu me esqueci desse o outro era para a impressão, esse era para o export


Use WaitForSeconds for timing recorded commands

Question: What I'm trying to do is a system to replay a list of commands I previously recorded. The list I use contains a class with the command and the time that was recorded (with Time.time), in this way I can decide when to play each command in sequence (for example I execute the first command at 1 second after I press record, and the second command at 5 seconds, in this way when I want to replay the commands they will be replayed waiting the exact seconds).
When I replay the command I used a coroutine with WaitForSeconds, but I discover because is frame rate dependent If the command ends at the middle of the frame the time starts from a cumulative delay (the wait time of the command plus the offset extra to finish the frame) and because this I tried to build something that predicts this problem, but when I replay the commands, the result is a slowdown replay.
private IEnumerator ExecuteBodyAnimation(List<UserBodyRecord> bodyAnimations)
{
    // Prevent multiple calls
    if (IsAnimationPlaying)
        yield break;

    IsAnimationPlaying = true;

    float extraTime = 0;

    for (int i = 0; i < bodyAnimations.Count; i++)
    {
        // Exit if we want to stop the animation sequence
        if (!IsAnimationPlaying)
            break;

        int currIndex = i,
            nextIndex = i;

        // Prevent OutOfRangeException
        if (currIndex < bodyAnimations.Count - 1)
            nextIndex++;

        UserBodyRecord currBodyAnimation = bodyAnimations[currIndex],
            nextBodyAnimation = bodyAnimations[nextIndex];

        // Calculate the time difference between the current time recorded animation and the next one recorded
        float currentAnimTime = currBodyAnimation.timeRecorded;
        float nextAnimTime = nextBodyAnimation.timeRecorded;
        float differenceTime = nextAnimTime - currentAnimTime;

        // Send the body pose list to the provider
        bodyProvider.SetBodyPose(currBodyAnimation.humanPoses);

        float lastRealTime = Time.realtimeSinceStartup;

        // Wait the time between animations
        yield return new WaitUntil(() =>
        {
            // Exit if we want to
            if (!IsAnimationPlaying)
                return true;

            // Calculate how much time has passed since we are waiting
            float counterTime = Time.realtimeSinceStartup - lastRealTime;

            // Add the extra time exceeded from last animation frame
            counterTime += extraTime;

            if (counterTime > differenceTime)
            {
                // Get the extra time
                extraTime = counterTime - differenceTime;

                return true;
            }
            else
            {
                return false;
            }
        });
    }

    // Wait a bit before stop the animation
    yield return new WaitForSeconds(delayBeforeStopAnimation);

}

What could be the problem?
Comment: Just out of curiosity, why not WaitForSeconds(counterTime)?
Comment: either way in a frame-based application you will always have only the precision of frames -> about 17ms for 60 F/s. So it is always possible that you would only need to wait 1ms more but you end up waiting the entire frame => 16ms too much
Answer: I'm not sure I know the answer but you can use :
float time = TIME_TO_WAIT;

while(time > 0)
{
time -= Time.deltaTime;
yield return null;
}

Comment: This is basically the same, except you don't calculate the extra time to complete the frame. Please see the derHugo's comment under my answer to having a better understanding. :)


dynamic binding and dynamic linking

Question:
Quoted from Dynamic Binding
C++,

dynamic binding is orthogonal to
  dynamic linking...

I was wondering how to understand
the meaning of orthogonal"? Is it
because

compilation of source code into  machine code is like going deep, and linkage of various  machine codes is like going horizontal, and so they are orthogonal to each other,
(static/dynamic) name binding  is a concept in compilation
static/dynamic linking is a concept in linkage?

if in dynamic linking, any involved binding, i.e., any involved
association of objects (data and/or
code) with identifiers is dynamic
binding?

Thanks!
Answer: "Orthogonal" means that the presence or status (in a more abstract sense) of the one is not dependent at all on the corresponding status of the other. In this specific case it means that dynamic linking may occur irrespective of whether dynamic binding occurs, and vice versa.
As a practical example, consider that dynamic binding is the resolution at runtime of what piece of code should be executed as a result of a function call present in the source code. That piece of code may be present in a library which is linked into the executable at link time (static linking), or it may be present in a library dynamically loaded at runtime (dynamic linking). The binding part does not care about how the linking was done; therefore, it is orthogonal to the latter.
You also ask:

if in dynamic linking, any involved
  binding, i.e., any involved
  association of objects (data and/or
  code) with identifiers is dynamic
  binding?

This question is meaningless, as there is no binding involved in the linking process. Binding may occur statically (resolved by the compiler and baked into the object code) or dynamically (resolved at runtime), but the decision of how to bind and the logic that resolves the binding does not interact at all with the linking.
Comment: Thanks! I was also wondering if in dynamic linking, any involved name binding, i.e. any involved association of objects (data and/or code) with identifiers, is dynamic binding?
Comment: @Tim: Binding in compilation == **static** binding (compiler decides on the spot). In dynamic binding, of course the compiler has to decide on the spot to call *something*, but that something is in fact code that will decide at runtime what code to execute for a given expression. That code is what we refer to as the result of the binding, so **dynamic** binding happens at runtime. Therefore, name binding (in general) does not happen only in compilation.

dynamic binding and dynamic linking


Taylor-polynomial of function $f(x) = e^{x}*\sin(2x)$

Question: This is not homework, I'm asking to learn for an exam which I'll write in 2.5 months.

Count the Taylor-polynomial 3th grade of the function $f: \mathbb{R}
\rightarrow \mathbb{R}, f(x) = e^{x}\sin(2x)$ in $x_{0} = 0$

3th grade means we will need the derivations $0,1,2,3$ of $f$:
$$\begin{align}
&f^{(0)}(x) = e^{x}\sin(2x)\\
&f^{(1)}(x) = e^{x}(\sin(2x)+2\cos(2x))\\
&f^{(2)}(x) = e^{x}(-3\sin(2x)+4\cos(2x))\\
&f^{(3)}(x) = e^{x}(-11\sin(2x)-2\cos(2x))
\end{align}$$
which implies
$$\begin{align}
e^{x}\sin(2x) &= \frac{f^{0}(0)}{0!}(x-0)^{0}+\frac{f^{1}(0)}{1!}(x-0)^{1}+\frac{f^{2}(0)}{2!}(x-0)^{2}+\frac{f^{3}(0)}{3!}(x-0)^{3}+\cdots\\
&= \frac{0}{1}\cdot 1+ \frac{2}{1}x + \frac{4}{2}x^2 - \frac{2}{6}x^{3}+\cdots\\
&= 2x +2x^{2}- \frac{x^{3}}{3}+\cdots
\end{align}$$
Now my questions:
1) Did I do it correctly?
2) If it says 3rd grade in the task, am I only allowed to derivate 3 times then?
3) How can I create the series in the end with $2x +2x^{2}- \frac{x^{3}}{3}+\cdots$ if there is much info missing (without more derivations, I cannot see what will come next and thus I cannot create the complete series. BUT the task only said 3th grade, so it should have been enough, no?
Comment: You could also calculate $\left(1+x+\frac{x^2}{2}+\frac{x^3}6\right)\cdot\left(2x-\frac{8x^3}{6}\right)$ and skip all terms that turn out to be $x^4$ and higher.
Comment: don't use $\ast $ for the multiplication, write $e^x \sin(2x)$ instead
Comment: You can also use $2\sin x= e^{ix}-e^{-ix}$
Answer: For starters, you have a mistake, this is how things should be: $$f'(0)=2 \quad \text{and} \quad f''(0)=4$$
$\textbf{Another way to proceed}$: if you know the series expansion of  both $e^x$ and $\sin(2x)$:
$$e^x=1+x+\frac {x^2}{2}+\frac {x^3}6+\cdots$$
$$\sin(2x)=2x-\frac {4x^3}3+\cdots$$
Then $$e^x\sin(2x)=\left(1+x+\frac {x^2}{2}+\frac {x^3}6+\cdots\right)\left(2x-\frac {4x^3}3+\cdots\right)$$
$$=2x-\frac {4x^3}3+2x^2-\frac{4x^4}3+{x^3}-\frac{4x^5}6+\cdots$$
$$=2x+2x^2-\frac13x^3+\cdots$$
$\textbf{If you want to find the general expression}:$
We're only interested in the coefficient of the $\cos(2x)$ in the $n^{th}$ derivative so let $a(n)$ be that coefficient and $b(n)$ the coefficient of $\sin(2x)$. We notice that if $g^{(n)}(x)=e^xf(x)$ then $g^{(n+1)}(x)=e^x(f(x)+f'(x))$ this implies that the coefficients in the $(n+1)^{st}$ derivative  are related to those of the previous as follows:
$$a(n+1)=a(n)+2b(n)$$$$b(n+1)=b(n)-2a(n)$$
If we multiply the second equation by two, then subtract it from the first, we get:
$$a(n+1)-2b(n+1)=5a(n)$$
or $$a(n)-2b(n)=5a(n-1)$$
Replacing $2b(n)$ in the first equation yields $$a(n+1)=2a(n)-5a(n-1)$$
with $a(0)=0$ and $a(1)=2$. This is a way of generating each coefficient in the Taylor series. Solving the recurrence relation using the characteristic equation results in:
$$a(n)=\frac 12i((1-2i)^n-(1+2i)^n)$$
So that generally $$\color{blue}{\boxed{\quad e^x\sin(2x)=\sum_{k=0}^\infty \frac 12i((1-2i)^k-(1+2i)^k)\frac{x^k}{k!}\quad}}$$
But honestly, I don't think they were asking for this general solution.
Comment: Thanks, just realized and corrected that :)
But what comes now? I don't need to make this sum symbol?
I'm finished now?
Comment: @cnmesr Since it says "3rd grade" then you should stop here I suppose
Comment: Alright.
No need to make sum symbol for the end result?
Comment: @cnmesr I have found the general form of the Taylor expansion, but I don't think they asked for it...
Comment: Ouch this is so complicated and time consuming, and it's one of many tasks in the exam (120 min!).
But you are saying that this wasn't asked, right?
Comment: @cnmesr No, it is not asked! do not worry...
Comment: Thank you so much GeorgSaliba!! :)
Answer: You miscalculated the first and second order terms, remember that $sin(0) = 0$ and $ cos(0) = 1$.
Answer: Based on your work above $f''(0) = 4$  check this.
Where did the $x^1$ term go?
$f(x) = \frac {0}{0!} + \frac {2}{1!}x + \frac {4}{2!}x^2 + \frac {-2}{3!} x^3 \cdots$
I would say $3^{rd}$ degree polynomial, and not "grade."  But that would be correct, the highest exponent of $x = 3.$  And, the highest derivative you would need is 3.
What about the remaining terms of the polynomial?
If $x$ is small, then $x^2$ is smaller and the higher degree terms are smaller than that.  Depending on the size of your interval, the higher degrees of the polynomial are irrelevant.
Or, more precisely, we can find a bound for the error, and decide if our estimate is sufficiently precise for our needs.


How to extract accountId from oauth2 token in webfilter

Question: Im using webflux in my program and oauth2 security (keycloack as UAA server) I want to extract some information from oauth2 jwt and I do it well . but i need to get some information in filter .
when I use my old method it not work in filter (WebFilter) .
Is there any way to parse token and get information from it ?
Is my way correct or I should extract it using springSecurityFilterChain instead of WebFilter?
I want check accountId in token with accountId in url that client send using filter.
Hear is my code to extract accountId it not work in WebFilter but it work when i use it services or controller
  public class SecurityFilter implements WebFilter {

        @Override
        public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
           ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).map(Principal::getName).filter((accountId) -> accountId.equals(clientAccountId)

.switchIfEmpty(Mono.error(new SystemException("401 ERROR")));;
          return webFilterChain.filter(serverWebExchange);

    }

Hear is my second way to extract accountId :
public class SecurityFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
      serverWebExchange.getPrincipal().map(Principal::getName).filter((accountId) -> accountId.equals(clientAccountId). .switchIfEmpty(Mono.error(new SystemException("401 ERROR")));;
      return webFilterChain.filter(serverWebExchange);

}

and my security config is :
 @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
                .authorizeExchange()
                .pathMatchers("/api/**").authenticated()
              //  .pathMatchers("/**").permitAll()
                .anyExchange().authenticated()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new HttpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST))
                .and()
                .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(grantedAuthoritiesExtractor());
        return http.build();
    }

I think i should have another SecurityWebFilterChain method that do this for me ??
Comment: What is your problem here ? Is your problem that your filter never returns 401?
Comment: one is that i can not get pathVariable in  filter and last on is that my filter does not return 401
Comment: I am not sure but i think you also need to have defaultIfEmpty after exchange.getPrincipal() so just test it when you dont pass token what happen
Answer: You are looking for smth like this
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    var clientAccountId = "clientId";
    return exchange.getPrincipal()
            .map(Principal::getName)
            .flatMap((accountId) -> {
                if (accountId.equals(clientAccountId) && exchange.getRequest().getPath().value().equals("/my/api")) {
                    return Mono.just(accountId);
                }
                return Mono.error(new IllegalArgumentException("401 ERROR"));
            })
            .flatMap(tokenJwt -> chain.filter(exchange))
            .onErrorResume(r -> {
                exchange.getResponse().setRawStatusCode(HttpStatus.UNAUTHORIZED.value());
                return exchange.getResponse().setComplete();
            });
}

Note: that when you are using reactive then until you or spring subscribe to it it wont be executed.


Cox regression with lasso regression

Question: Is it possible to perform lasso regression (glmnet with "cox") for variable selection and then conduct Cox regression using selected variables?
What is the difference between analyzing with lasso regression only AND Cox regression with selected variables? I want to use Cox regression which has more functions in post-prediction.
Can anyone provide an example of the predict of the glmnet Cox model? In the glmnet vignette on CRAN, there are linear and logistic examples, but there is no example of Cox.
Comment: Please say more about the scale of your study (numbers of cases and events, number of potential predictors) and the nature of the "post-prediction" you wish to perform. The best answer to your question might be different depending on those details.
Comment: Dear Mihai Chelaru, Thank you for your comments.
I have 208 cases and 35 events (6months to 10years survival data). The number of potential predictors is about 40. I just want to get Harrel's C index with confidence interval.
Answer: If you simply take the predictors returned by LASSO and use them in a fresh Cox model, you have ignored the fact that you used the data to select the predictors. The model thus may be overfit; p-values and such will not be reliable. You will have removed LASSO's penalization of regression coefficients that minimizes overfitting. See this answer for some more details.
The vignette for Cox modeling with the glmnet package claims that "the Cox Model is rarely used for actual prediction" so the authors haven't provided prediction functionality for Cox models beyond the linear-predictor values and the related "relative-risks." There seems to be no way to extract a full Cox model object or its baseline cumulative hazard from glmnet.
You have a few ways to proceed.
First, if all you care about is the C-index as suggested by your comment, you can get the information you need to calculate it from the linear-predictor values returned by predict.glmnet. The C-index is simply the fraction of pairs of comparable cases for which the event order matches the order of linear-predictor values. Although censored cases can't be compared against each other, all cases with events can be compared against each other (in your data, 35*17 = 595 pairs) and any case with an event can be compared against censored cases having later censoring times. This page shows some ways to do this calculation yourself.
Second, you can force coxph to provide a Cox model with the coefficients returned by glmnet. This link outlines how. Instead of using the default coxph settings, you provide a vector of the glmnet coefficient values with the init= argument, and then prevent any additional fitting with an iter.max=0 argument, which is passed on to the coxph.control function. The output will be a coxph.object suitable for many purposes but it will not have a coefficient covariance matrix, so you may get error messages in some applications and functionality for things like confidence intervals (questionable in any event for a model fit by LASSO) is limited.
Third, if you don't need anything beyond simple LASSO you could try the glmpath package. It might be slower than glmnet but with a small study like this that shouldn't make much difference. Its predict function for coxpath objects has a type="coxph" argument option that returns a coxph.object for which "the components of a coxph object such as coefficients, variance, and the test statistics are adjusted to the shrinkage." So that might be the most generally useful approach for simple LASSO. I haven't used this myself, and I don't know how those adjustments for shrinkage are made. You will need to make sure that the shrinkage value specified by the s= argument matches the mode= argument for specifying the single point along the regularization path for which you want the Cox model.
With your original question answered, however, do think more about whether LASSO is the best approach to answering your scientific question. With only 35 events LASSO is probably only returning (at the optimal cross-validated partial likelihood) about 3 non-zero coefficients among your 40 possible predictors. In clinical data there are often highly correlated predictors, so the particular predictors chosen can depend heavily on the particular data sample at hand (which you can examine by repeating your modeling on multiple bootstrap sample of your data). And if you have a multi-category predictor simple LASSO might just choose one category, which might not always make sense.
You might be better off using your knowledge of the subject matter to combine similar predictors and/or select predictors that are most likely related to outcome. If you have a specific hypothesis about one predictor that you would like to test but need to correct for other covariates, look at the recommendations in this paper; in that case, using ridge-regression penalties for all predictors except for that one might be better.
Comment: I really want to express my gratitude for your kind and profound answer!!

Cox regression with lasso regression


Geometric problem with angle bisectors

Question: We have a triangle $\Delta ABC$ ($AC$ is not equal to $BC$ and thus the triangle is not isosceles) with angle bisectors $AA_1$, $BB_1$ and $CC_1$ ($A_1$, $B_1$ and $C_1$ are on the sides $BC$, $AC$ and $AB$ respectively). If angle $AA_1C_1$ is equal to angle $BB_1C_1$, find out angle $BCA$.
I know that the answer is 120 degrees but I couldn't prove much.
Comment: In any isosceles triangle you have $AA_1C_1 = BB_1C_1$, so the information you currently have is not enough to determine the angle $BCA$
Comment: Yes, I forgot to mention that the triangle can't be isosceles. But now I add that to the statement.
Comment: Are $A_1,B_1$ and $C_1$ on the sides of the triangle?
Comment: Yes, they are in the sides of the triangle.
Answer: This problem was given to me by my maths teacher. He gave me the following hint: let point X lie on $CB_1$ and $CX=CA_1$. After some time i finally managed to solve the task. Here is the solution:
Without loss of generality we can have $AC>BC$ ($\Delta ABC$ is not isosceles). It's easy to prove that $CB_1 > CA_1$, so point X lies on the $segment$ $CB_1$. Next we show that $\Delta CIX$ is congruent to $\Delta CIA_1$ and therefore $\Delta C_1IX$ is congruent to $\Delta C_1IA_1$. From this we have angle $C_1XI$ is equal to angle $IA_1C_1$ which is equal to angle $IB_1C_1$ (from the statement). Now we can prove that quadrilateral $B_1C_1IX$ is inscribed. $=>$ (angle $XB_1C_1$ $+$ angle $XIC_1$) is equal to $180$ degrees. By using simple angle expressions we find that angle $IB_1C_1$ is equal to $\gamma$ $-$ $90$ degrees.
After knowing this by making more angle expressions we find that angle $AC_1B_1$ is equal to $90$ degrees $- \alpha - \beta/2$ and angle $B_1C_1C$ is equal to $\alpha/2 + \beta$. Now we use three sinus theorems and get this equality: $AB_1/B_1C=(sin(\gamma/2)/sin(\alpha))*(cos(\alpha+\beta/2)/sin(\alpha/2+\beta))$. Now using the fact that $BB_1$ is angle bisector in $\Delta ABC$ and another sinus theorem for $\Delta ABC$ we obtain only trigonometric equality: $sin(\gamma)/sin(\alpha)=(sin(\gamma/2)/sin(\alpha))*(cos(\alpha+\beta/2)/sin(\alpha/2+\beta))$. After some simplification we have this: $2*cos(\gamma/2)=sin(\gamma/2-\alpha/2)/sin(\gamma+\alpha/2)$. Now we use sum and difference trigonometric identities and the equality looks like this: $2*sin(\gamma)*cos(\alpha/2)+2*cos(\gamma)*sin(\alpha/2)=tg(\gamma/2)*cos(\alpha/2)-sin(\alpha/2)$. We make some groping and  then some groping and use a half angle trigonometry formula and we obtain this: $sin(\alpha/2)*(2*cos(\gamma)+1)-tg(\gamma/2)*cos(\alpha/2)*(1-2*(1+cos(\gamma))=0$. Now $2*cos(\gamma)+1$ is a common multiple and either he is $0$ or $sin(\alpha/2)+tg(\gamma/2)*cos(\alpha/2)$ because the product is $0$ if one of the multiples is $0$. The second case is impossible due to $\alpha$ and $\gamma$ being angles in triangle and the trigonometric functions from their halves are always positive. And from the first case we finally found that $\gamma$ is $120$ degrees.
If something in the solution isn't clear, feel free to ask me. I summarized some moments because this text would've been two times bigger.
P.S. I hope that i haven't done any mistakes.

Geometric problem with angle bisectors


Custom TitleView in NavigationBar

Question: I am trying to add a a user's image and name to a navigation bar to look like the following:

I am attempting to do this programmatically, as my codebase doesn't use xibs or storyboards (except for the launch screen).
Here is a brief look at my code:
  guard let prof = self.profile else { return }
    let imageView = ImageView(type: .none, avatar: true, 25)
    let nameLabel = UILabel()
    nameLabel.text = prof.name
    nameLabel.numberOfLines = 0
    imageView.setImage(prof.profileImage?.imageURL)
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 300))
    view.addSubview(nameLabel)
    view.addSubview(imageView)
    nameLabel.snp.makeConstraints { make in
        make.bottom.equalToSuperview().inset(5)
        make.left.right.equalToSuperview()
    }

    imageView.snp.makeConstraints { make in
        make.bottom.equalTo(nameLabel.snp.top).offset(5)
        make.top.equalToSuperview().inset(5)
    }

    self.navigationItem.titleView = view

I use SnapKit for laying out the UI and the ImageView is just a custom UIImageView that handles downloading images, has a built in loading indicator, some formatting options, and by telling the init that it is an avatar image, requests a much smaller size image too.
I used height of 300 for the parent view only as a test to get the navigation bar taller to accommodate my content, but there was no change in the height.
If anyone has a way to accomplish this design, or an alternative that is similar, I'd very much appreciate the assistance on this.
EDIT: Solutions without the use of SnapKit are totally fine.
EDIT: @asanli's description of a solution results in the following below:

code is here:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 300))
view.addSubview(nameLabel)
view.addSubview(imageView)
imageView.snp.makeConstraints { make in
    make.top.equalToSuperview().inset(10)
    make.width.height.equalTo(50)
    make.centerX.equalToSuperview()
}
nameLabel.snp.makeConstraints { make in
    make.top.equalTo(imageView.snp.bottom).offset(10)
    make.centerX.equalToSuperview()
}

Comment: Why don't simply create your own view? UINavigationBar won't have that much space.
Comment: @PGDev Will my own view by in the navigation bar?  The design request and product requirements issued to me is that it needs to be in the navigation bar.  Wouldn't my own view by just below the navigation bar, and hence not the same thing?
Answer: I have found one library which may help you. I have never used it but hope it helps you.
https://github.com/Pircate/EachNavigationBar
Comment: I actually tried this exact answer and it doesn't appear that changing the frame works anymore. not for a few iOS versions now at least
Comment: my confusion, is that clearly iMessage is able to do this all just fine
Comment: Oh, Yes you are right I can see, though iMessage behavior seems different while pushing or pressing on back. Though I have found one library which may help you. https://github.com/Pircate/EachNavigationBar  I have never used it but hope it helps you.

Custom TitleView in NavigationBar