For what values of $\alpha <\frac 12$ occurs $CVaR_{\alpha}(X) \ge VaR_{\alpha} (X)$

Question:
The payoff function for an investment is modeled with a random variable $X$ with a density function $$f(x)=\frac 12 e^{-|x|}$$ For what values of $\alpha <\frac 12$ occurs $$CVaR_{\alpha}(X) \ge VaR_{\alpha} (X)$$

My problems:

I'm not sure if I got the absolute value right - when calculating the distribution function I rejected $x<0$ because $VaR$ is defined for $\alpha \in (0,1)$ (here $\alpha <\frac 12$ )
Assuming my approach to the absolute value was correct, I arrived at an inequality from which it is difficult to derive the relation to $\alpha$

Below is my solution:
$VaR_{\alpha}(X)=-F_X^{-1}(\alpha)$
$CVaR_{\alpha}(X)=-\mathbb E(X | X \le -VaR_{\alpha}(X))=-\mathbb E(X | X \le F_X^{-1}(\alpha))$
For $t> 0$ (other cases are not needed for this task) the distribution function is represented by the formula: $$F_X(t)=\int_{0}^t \frac{1}{2}e^{-x} dx=-\frac 12 e^{-x} \bigg|_0^t =-\frac 12 e^{-t}+\frac 12$$
$F_X^{-1}$:
$$-\frac{1}{2}e^{-t}+\frac 12=y \Rightarrow \frac{1}{2}e^{-t}=\frac 12 -y \Rightarrow e^{-t}=1-2y \Rightarrow -t=\ln (1-2y) \Rightarrow t=-\ln(1-2y), y\in (0,\frac 12)$$
So: $$VaR_{\alpha}(X)=-F_X^{-1}(\alpha)=\ln(1-2\alpha)$$
Calculate $CVAR_{\alpha}$:
\begin{align} CVaR_{\alpha}(X) &=  - \frac{1}{\mathbb P(X \le F_X^{-1}(\alpha ))} \int_{-\infty}^{F_X^{-1}(\alpha)} x \cdot f(x) dx \\ &=  - \frac{1}{F_X \left( F_X^{-1}(\alpha ) \right)} \int_{-\infty}^{-\ln (1-2\alpha) } x \cdot \frac 12 e^{-|x|} dx \\ &= -\frac 1{2\alpha} \left( \int_{-\infty}^0 x e^x dx+ \int_0^{-\ln(1-2\alpha)} x e^{-x} dx\right) \\ &= -\frac{1}{2\alpha} \left( xe^x \bigg|_{-\infty}^0-\int _{-\infty}^0 e^xdx + (-xe^{-x}) \bigg|_0^{\ln(1-2\alpha)}-\int_0^{\ln(1-2\alpha)} (-e^{-x})dx \right) \\ &= -\frac{1}{2\alpha} \left( (0-0)-(1-0) + (-\ln(1-2\alpha)e^{-\ln(1-2\alpha)}-0) -(e^{-\ln(1-2\alpha)}-1) \right) \\ &= \frac 1{2\alpha} e^{-\ln(1-2\alpha)}(1+\ln(1-2\alpha)) \\ &=\frac{1}{2\alpha (1-2\alpha)} (1+\ln(1-2\alpha)) \end{align}
Inequality:
$$CVaR_{\alpha}(X) \ge VaR_{\alpha} (X)$$
$$\frac{1}{2\alpha (1-2\alpha)} (1+\ln(1-2\alpha)) \ge \ln(1-2\alpha)$$
$$ 1+\ln(1-2\alpha) \ge 2\alpha (1-2\alpha) \ln(1-2\alpha)$$
$$(1-2\alpha +4\alpha^2)\ln(1-2\alpha)\ge -1$$
Answer: I will use the definitions you provided of VaR and CVaR. We can see that
$$F(c)=\begin{cases}
\frac{1}{2}\int_{-\infty}^ce^{x}dx=e^c/2&c\leq 0\\
\frac{1}{2}+\frac{1}{2}\int_{0}^ce^{-x}dx=\frac{1}{2}+\frac{1}{2}(1-e^{-c})=1-e^{-c}/2&c>0
\end{cases}$$
Now, the exact inverse exists and for $u \in (0,1)$
$$F^{-1}(u)=\begin{cases}
\ln(2u)&u\leq 1/2\\
-\ln(2(u-1))&u>1/2
\end{cases}\implies \textrm{VaR}(u):=-F^{-1}(u)=\begin{cases}
-\ln(2u)&u\leq 1/2\\
\ln(2(u-1))&u>1/2
\end{cases}$$
Now let $u<1/2$. Then $F^{-1}(u)<0$. We then get
$$\textrm{CVaR}(u):=-\frac{\int_{-\infty}^{F^{-1}(u)}xe^xdx/2}{P(X\leq F^{-1}(u))}=-\frac{\int_{-\infty}^{\ln(2u)}xe^xdx}{2u}=1-\ln(2u)$$
We conclude that $\textrm{CVaR}(u)>\textrm{VaR}(u),\,\forall u <1/2$.


Error in (Require) with J2V8

Question: I'm trying to use Ripple-lib to get client's balance, inside my java application.
To call Ripple javascript API, I use j2v8 as following:
<code>    V8 runtime = V8.createV8Runtime();
    runtime.executeVoidScript(""
            + "const RippleAPI = require('ripple-lib').RippleAPI;\n"
            + "const api = new RippleAPI({\n"
            + "    server: 'wss://s.altnet.rippletest.net:51233'\n"
            + "});\n"
            + "var client = {\n"
            + "    getBalance: function (address) {\n"
            + "        api.connect().then(() => {\n"
            + "            api.getBalances(address).then(balances => {\n"
            + "                return JSON.stringify(balances, null, 2);\n"
            + "            });\n"
            + "        })\n"
            + "    }\n"
            + "};");
    V8Object client = runtime.getObject("client");
    V8Array parameters = new V8Array(runtime);
    parameters.push("rHY6yUsQaEigs867XUgaMp89Hhm2eJs5jQ");
    String result = client.executeStringFunction("getBalance", parameters);
    System.out.println(result);
    parameters.release();
    runtime.release();
</code>
but with exception:
<code>Exception in thread "main" undefined:1: ReferenceError: require is not defined
const RippleAPI = require('ripple-lib').RippleAPI;
                  ^
ReferenceError: require is not defined
    at <anonymous>:1:19
com.eclipsesource.v8.V8ScriptExecutionException
</code>
Could anyone please help me?
Answer: If you are running j2v8, the engine knows only pure js, not even window variable, because window, document, and Dom manipulation api's are provided by browser not just engine. Require is not js function. It won't be recognized by v8 engine
Comment: How is it possible then to use an external package downloaded from npm?
Comment: Is there a way to manually "create" the DOM objects for v8 ?
Comment: @shleimel ASFIK, there is no way to manipulate or create DOM objects from v8.
Comment: One way is you have to mock all the dom functions, like create element, set attribute manually. But it is a herculean task.
Comment: Thanks @GopiS - solved it by manually defining a `window` object like this `V8Object window = runtime.executeObjectScript("window = {};");` . It doesn't actually hold the DOM documented attributes, but it was good enough. Thanks to ChatGPT ;)

Error in (Require) with J2V8


Chrome 10/11 and IE8/9 Issue with Iframe

Question: I'm using iframe with its attribute of designMode set to on and its attribute of isEditable set to true for WYSIWYG text editing.  It works fine with Firefox 3.6x (I would expect fine as well with FF 4.0) and Safari 5.
Code snip:

However, it fails with Chrome 10/11 and IE8/9, that is, the iframe is rendered in read-only mode with these two browsers.
Does it mean these two browsers expect different coding for iframe or do they simply don't support iframe's use in the above scenario?
Thanks.
Answer: It works if you find the element using JavaScript and set designMode to "on".
For example,


Is an exponential family closed under convolution?

Question: Let
$$
y = x_1 + x_2 + x_3
$$
where $x_1, x_2, x_3$ are draws of random variables of the same family and different parameters:  $p(x_1| \theta_1), p(x_2| \theta_2), p(x_3| \theta_3)$
We know that, for some distributions that are closed under convolution, then the distribution over $y$ belongs to the same distribution.
My question concerns the case where $x_i$ belong to some exponential family of distributions: does the sum of random variables from an exponential family also belong to some exponential family?
Comment: @AdamO You and kjetil and alberto appear to be talking at cross-purposes: the issue concerns whether alberto means **the** [family of Exponential distributions](https://en.wikipedia.org/wiki/Exponential_distribution) or **an** [exponential family of distributions.](https://en.wikipedia.org/wiki/Exponential_family)  Notice the distinctions between "the" and "an," as well as the different capitalization.  The meanings are quite different!  Alberto, please edit your question to clarify your meaning.
Comment: @alberto you still aren't grasping. The exponential distribution is a member of the exponential family. As I said, it is an *example*. Your assertion is wrong. In math, a counter example suffices to disprove a claim, so your "other examples" should have discredit the thought immediately.
Comment: Well, the sum of (independent) variables pertaining to *some* exponential family belongs to *some other* exponential family!  This is proved in (from memory) Bickel&Doksum, for instance
Comment: Use the MGF uniqueness theorem
Comment: @ketil that's what I meant, thanks! I'll try to get the book.
Comment: @AdamO I'm not sure how you are interpreting the question where you talk of "counter-example."  One natural interpretation--but not necessarily the only one--is whether *all possible sums of variables taken from a given exponential family* themselves form another exponential family.  As such, if $\theta$ is the parameter in the first family with $\theta\in\Theta$, then the parameter $(\theta_1,\theta_2)$ in the family of sums can be viewed as an element in a quotient space of the product $\Theta\times\Theta$, which may have strictly larger dimension than $\Theta$.
Comment: @Paul I believe you can make short work of this by considering the cumulant generating functions.
Comment: Maybe you should tag this as self-study?  (And, the short answer is YES)
Comment: Not hard to think of some counter examples. 1 parameter exponentials are members of the exponential family.
Comment: @AdamO This is an example rather than a counter example, isn't it?
Comment: @alberto no, iid exponential sums are not exponential.
Comment: @AdamO I know about some counter examples, but does the distributon of the sum at least belong to the Exponential Family? Oh, I see the confusion, I mean the family, not the expontial distribution!
Comment: @whuber Unless I'm mistaken, wouldn't the geometric distribution be yet another counter example? Wouldn't the Bernoulli? I think some conditions need to be imposed about the dimension of the parameter(s).
Comment: I would guess the sum of binomial distributions with different p values might fall outside the exponential family, but lacking the will to investigate/prove right now.
Comment: @whuber ok I see now. Yeah I was reading a slightly different question. Apologies.
Answer: The property that you describe refers to stable distributions
You can study these convolutions of pdf's by products of characteristic functions.  For instance:

The Cauchy-Lorentz distribution is a stable distribution $$E(e^{itX}) = e^{it\mu_X+\sigma_X\vert t\vert}$$ and $$E(e^{itX+Y}) = e^{it\mu_X+\sigma_X\vert t\vert} e^{it\mu_X+\sigma_X\vert t\vert} =e^{it(\mu_X+\mu_Y)+(\sigma_X+\sigma_Y)\vert t\vert} = e^{it\mu_Z+\sigma_Z\vert t\vert} $$ with $\mu_Z=\mu_X+\mu_Y$ and $\sigma_Z=\sigma_X+\sigma_y$
but, for instance, the Gamma distribution is not a stable distribution $$E(e^{itX}) = (1-it\theta_X)^{k_X}$$ and $$E(e^{itX+Y}) = (1-it\theta_X)^{k_X} (1-it\theta_Y)^{k_Y} \neq (1-it\theta_Z)^{k_Z}  $$ where we can not make this final step (unless $\theta_X = \theta_Y$)

So for a particular distribution that is in the exponential family it is not (generally) true that is a stable distribution.
Still you may wonder whether the sum of any two distributions in the exponential family could be any other distribution in the exponential family.

There is no general description of the characteristic function of an exponential family distribution $f(x) = h(x)g(\theta) e^{\eta(\theta) \cdot T(x)}$, and trying to work out the convolution for the general case is messy (and I don't think it works).
Possibly one could work out a particular case to show that a convolution is yielding some distribution that is not a exponential family.
If the sufficient statistic T(x) is a linear function then at least the cumulant generating function for T might be used to proof some stability property:
$$k(u \vert \eta) = A(\eta + u) + A(\eta)$$
by using the property $k(X+Y) = k(X) + k(y)$. However, I am not sure about the inverse step, whether the cumulant generating function $k(X) + k(y)$ is necessarily referring to a valid distribution from the exponential family. But at least this is an interesting notion.


AngularJS $watch root scope variable for changes

Question: I have the following $rootScope variable which I use to save the current logged in user privilege level, then I access this variable from other controllers. Is there a way I can watch the rootScope variable for changes in order to update controllers specific variables with any changes to the root scope variable? Below is the code I am using so far, can someone please tell me what I am doing wrong and how to fix it? Thanks
In app.js under .run:
 $rootScope.uPLevel = 0;

.controller
   $scope.$watch($rootScope.uPLevel, function() {
            $scope.userPLevel = $rootScope.uPLevel;
   }, true);

Answer: The first parameter to $watch should either be a string or a function (docs).  Right now you're passing it the value of $rootScope.uPLevel on controller initialization.
$scope.$watch(function() {
  return $rootScope.uPLevel;
}, function() {
  $scope.userPLevel = $rootScope.uPLevel;
}, true);

Two sidenotes:

It may be prudent to store this value in a service instead of $rootScope.
If uPLevel is only an integer (as your example suggests) then you don't need to pass true as the third parameter - that's only for arrays and objects.  If you do want to watch a collection, then I suggest using $watchCollection instead.
Comment: @SomeKittensUx2666 is right that you should resist putting things on $rootScope, in this case I would suggest that you broadcast an event from $rootScope which all controllers/services could listen to in order to handle the change logic.
Comment: @MChan It's generally a bad idea to clutter up `$rootScope` for the same reasons one doesn't attach lots of variables to `window`.  Something to think about.  Don't forget to upvote!
Comment: Thanks a lot, reason I am using it in rootScope as I need a way to have it accessible from all services / controllers application wide. Do you believe having this variable inside a service is much better? if yes can you please explain why?
Comment: or you could use a single object and store all data inside it. this way you don't clutter the $rootScope
Comment: Plus one more vote because if you have a dynamic value to watch that is not isolated well in a specific scope, even if it's on the $window, this is a good way to go.
Answer: I recommend watching $rootScope variables like that:
$scope.$watch('$root.uPLevel', function() {
    $scope.userPLevel = $rootScope.uPLevel;
});

This way, When current directive/controller is destroyed. It clears the watch as well. In $rootScope.$watch case, the watch stays forever.
Comment: Great idea. Perfect if you're looking for performance optimization


Manter informações do while em variável

Question: Tenho um código onde possui um while dentro de outro, para poder listar produtos dentro do carrinho de compras dividido por lojas. Logo, ao ver listado os produtos, como na imagem 1.
Como na foto acima, o meu problema é o seguinte ao clicar em comprar eu precisaria ter o id da loja que estou finalizando a compra, só que como fiz essa exibição com while ele sempre salva o ultimo id processado no while... vou colocar o código, teria como eu fazer com que ao clicar em comprar ele abrisse o numero respectivo a loja?
while ($linhaaa = mysqli_fetch_array($resultadooo)) {

                        //cria variavel com o numero da loja
                        $codigo_loja = $linhaaa["cod_loja"];
                        //seleciona tudo de compra com join de produtos_clientes com cod_user - essa parte vai exibir os produtos
                        $sintaxesql = "SELECT compra.cod_compra, compra.cod_user, compra.item, compra.tipo_entrega, compra.cod_loja, produtos_clientes.cod_colar,
                        produtos_clientes.nome, produtos_clientes.preco, produtos_clientes.id_cliente, produtos_clientes.modalidade, produtos_clientes.cod_loja
                        FROM compra
                        JOIN produtos_clientes
                        ON compra.item = produtos_clientes.cod_colar && produtos_clientes.cod_loja = compra.cod_loja WHERE compra.cod_user='$cod_user' && compra.cod_loja='$codigo_loja'";
                        $resultado = mysqli_query($link, $sintaxesql);
                        //define a variavel de soma dos produtos
                        $total_pedido_soma = 0;
                        //abre while pra mostrar os itens que ele possui no carrinho
                        echo '

                                Ações
                                Nome do Vendedor
                                Item
                                Nome
                                Preço

';
                        while ($linha = mysqli_fetch_array($resultado)) {
                            //calcula o total do pedido
                            $total_pedido_soma =
                            $total_pedido_soma = $total_pedido_soma + $linha["preco"];
                            //trata a exibição para monetária somente a linha não o resultado final
                            $linha["preco"] = str_replace(".", ",", $linha["preco"]);
                            //verifica o tipo de entrega
                            $tipo_entrega = $linha["tipo_entrega"];
                            //query para buscar nome do vendedor
                            $id_cliente = $linha["id_cliente"];
                            $sintaxesqll = "SELECT nome FROM usuario WHERE cod_user='$id_cliente'";
                            $resultadoo = mysqli_query($link, $sintaxesqll);
                            $linhaa = mysqli_fetch_array($resultadoo);
                            //exibe conforme o tipo de entrega
                            echo'
';
                            echo '

                                      ';
                            echo'
                                ' . $linhaa["nome"] . '
                                ' . $linha["item"] . '
                                ' . $linha["nome"] . '
                                R$: ' . $linha["preco"] . '

                                ';
                        }
                        //resultado final
                        echo 'Total R$:';
                        echo $total_pedido_soma;
                        echo '<button class="btn btn-success" rel="5" onclick="submete();">Comprar</button>';
                        echo '	';
                        echo '
';
                        echo '<form id="envia" method="POST" action="envia.php">';
                        echo '<input type="hidden" name="total" value="'; print $codigo_loja; echo '" />';
                        echo'</form>';
                    }

Answer: É só concatenar o valor da variável com a string do botão 'hidden' que está sendo utilizado, uma vez concatenado na string, não importa se você altera ou não o valor da variável em outro loop.
echo '<input type="hidden" name="total" value="'.$codigo_loja.'" />';

Para concatenar o valor da variável na string com PHP basta utilizar '.', para saber mais sobre concatenação de string: http://php.net/manual/pt_BR/language.operators.string.php
Comment: não resolveu o problema ainda...
Answer: Cara pelo que eu entendi o seu problema é que você não consegue usar a variavel fora do while e isso é obvio se ela foi criada dentro do while ela só vai funcionar la, o que você precisa fazer é criar a variavel fora do while secundario, caso queira usar fora dos dois whiles então cria a variavel como null fora dos dois, a logica é a seguinte:
variavel=null
ao percorrer o while ela vai receber o valor e vai sair de la com o valor, e você vai poder usaa-la fora, seria algo assim
<?php
while (10 < 14){
    $variavel1 = null;
    while (10 < 14){
        $variavel1 = $x['id'];
    }
   echo $variavel1;
}

é obvio que você tem q adequar ao seus codigo, mas a logica é essa

Manter informações do while em variável


Is it acceptable to use code that overflows but gives the correct result?

Question: I want to subtract two user-supplied integers, and store the resulting range length. I obviously can't store it as an integer, as subtracting int.MaxValue and int.MinValue for example will overflow an int.
I wrote this :
uint rangeLength = (uint)max - (uint)min

It works in every case, but you can see that the cast will oveflow the uint type when one of the two integers is negative. However, this line gives the correct result.
This seems to do the same, doing two more operations, but without overflowing :
uint rangeLength = ((uint)max + int.MaxValue) - ((uint)min + int.MaxValue);

Is it acceptable to use the first line it in my code, or is it too confusing ? Should I use the second one just so that it doesn't seem like an error ?
Comment: `uint` and `long` are _different_.
Comment: Yes it is ok.  I've done that lots time when design logic circuits in hardware and simulating results with a c/C# application.  It would help if you added a comment so it is not confusing to reader.   You code make perfect sense to me since I have a BSEE.  The microprocessor is designed to work with signed and unsigned numbers and when doing math operations the overflow underflow bits should be ignored.
Comment: why can't you store it a `long` type then?
Comment: Actually you can even store it as an `int`, just make sure to interpret it correctly later.
Comment: @YdobEmos, really? why not refer the MSDN doc instead of questioning me
Comment: @YdobEmos, *it's an alias for Int64* ... no wrong again. `Int64` coresponds to `long`
Answer: If it works in every case, then I think readability is the only thing you need to worry about.
You seem to have named your variables correctly - rangeLength. And you wrote that it is equal to max - min, so people probably will understand what you are doing. If you named the result a or something like that, then it's bad. If you are really worried, make it a method and abstract away the implementation details:
public uint RangeBetween(int max, int min) {
    return (uint)max - (uint)min;
}

uint rangeLength = RangeBetween(max, min);

Comment: am still bit confused as to what OP asking. Is he asking about overflow on math operation? or is he looking for suggestion?
Comment: The last sentences in the question is exactly what the OP is asking, right? "Is it acceptable to use the first line it in my code, or is it too confusing ? Should I use the second one just so that it doesn't seem like an error ?" @Rahul
Comment: Yes, this last sentence is what I'm asking. I had to wait a bit for SO to allow me to accept your answer. Thank you.


For a graph $C_n$, why do we have $\lvert\operatorname{Aut}(C_n)\rvert \geq 2 |R| = 2n$?

Question: In the book of Algebraic Graph Theory by Godsil, at page 8, it is stated that

However, the group $\langle g\rangle$ is of order $n$ and the group $\langle h\rangle $ is of order 2, so shouldn't we have
$$|Aut(C_n)| \geq n+2$$
 ? I mean I couldn't understand the argument that the author makes. Can some help me to understand the reason why we have
$$|Aut(C_n)| \geq 2 |R| = 2n$$
?
Comment: $\langle g\rangle$ has order $n$, and $h\langle g\rangle$ also has order $n$. They are disjoint subsets of $\text{Aut}(C_n)$, giving the result.
Answer: In addition to the automorphisms
$$
1,g,g^2,\dots,g^{n-1}
$$
there are also
$$
h,hg,hg^2,\dots,hg^{n-1}
$$
making for at least $2n$ automorphisms. The first list is $R$, the second list is the set $hR=\{hr:r\in R\}$. This is called a coset of R, and is the second coset that text mentions.
Comment: And there aren't any more...


Término de uma Thread

Question: Quando é feito o disparo de várias Threads em um loop específico, na finalização de cada uma, a Thread fica em aberto necessitando de um "close" ou é finalizada automaticamente?
for(int i=0;i<=10;i++){
    Process ps = new Process();
    Thread thread = new Thread(ps);
    thread.start();
}

O código acima fica só como exemplo, pois tenho uma lista de processos armazenados no Amazon AWS SQS, e necessito que cada processo encontrado seja executado em uma Thread.
Answer: Quando uma Thread termina, ela "morre" automaticamente, não sendo necessária nenhuma ação para finalizá-la.
Answer: Se cada mensagem dentro do Sqs for uma Thread, ela vai ser encerrada ao final do processamento, ou quando vc chamar o método interrupt.
Porém se o processamento for muito longo e for abrir muitas threads o ideal é usar um executor. Ele irá ajudar a controlar o pool de Threads e impedir que faça mais execuções que sua maquina suporte.
Nesse link tem um exemplo melhor explicado: https://dzone.com/articles/java-concurrency-%E2%80%93-part-7

Término de uma Thread


JOIN two data frames in R based on timestamps that are maximum x minutes apart

Question: I'm trying to JOIN two data frames in R on a Date column (measurements at different timestamps). The date timestamps are not equal at the two frames, so I need to round the timestamps is some way in order to be able to JOIN.
I thought of:

First round the values to the closest minute, then JOIN
The problem with this approach is that the rounding can cause close measurements to be rounded to different minutes, so they can't be JOINed
JOIN a record based on the closest value from the second frame (using "roll" from "data.table")
The problem with this approach is that measurements might be missing at each frame, so the second solution above won't work (the closest next measurement after the missing one is wrong to JOIN with). My question is how can I JOIN two record from two frame with the following condition:
IF the difference between the timestamps is less than 2 minutes - JOIN them to 1 record
ELSE (and in general) - keep all the the records that don't have a match with N/A values at the columns of the JOINed frame

** the two frames can be of different length due to missing measurements
Temperature Table
Name        Date                Value   Unit
Temperature 01/04/2017 00:02:08 14.6    degC
Temperature 01/04/2017 00:20:18 15.5    degC
Temperature 01/04/2017 00:38:29 14      degC
Temperature 01/04/2017 00:54:45 14.5    degC
Temperature 01/04/2017 01:14:44 13.9    degC`

Humidity Table
Name               Date                   Value   Unit
Relative Humidity   01/04/2017 00:02:25    56      %
Relative Humidity   01/04/2017 00:20:34    50      %
Relative Humidity   01/04/2017 00:38:44    59      %
Relative Humidity   01/04/2017 01:15:01    58      %`

result table
Name.x      Date                Value.x Unit.x name.y         value.y unit.y
Temperature 01/04/2017 00:02    14.6    degC   Relative Humidity  56      %
Temperature 01/04/2017 00:20    15.5    degC   Relative Humidity  50      %
Temperature 01/04/2017 00:38    14      degC   Relative Humidity  59      %
Temperature 01/04/2017 00:54    14.5    degC   NA                 NA      NA
Temperature 01/04/2017 01:14    13.9    degC   Relative Humidity  58      %`

Comment: What's the `class` of your `Date` columns? How are you currently rounding the values?
Comment: Date columns are `POSIXct type`, and currently the rounding function used is - `round_date {lubridate}`
Answer: Rolling joins in the data.table package can do this for you. roll = 120 sets it to a max difference of 120 seconds. nomatch = NA to get the missing value for no match.
library("data.table")
library("anytime")    # just to quickly get your strings as times

d1 = data.table(date = anytime(c("01/04/2017 00:02:08","01/04/2017 00:20:18","01/04/2017 00:38:29","01/04/2017 00:54:45","01/04/2017 01:14:44")),
    value = c(14.6, 15.5, 14  , 14.5, 13.9))
d2 = data.table(date = anytime(c("01/04/2017 00:02:25", "01/04/2017 00:20:34", "01/04/2017 00:38:44", "01/04/2017 01:14:40")),
    value = c(56, 50, 59, 58))

d2[, timestamp_d2 := timestamp]

d = d2[d1, on = 'date', roll = 'nearest', nomatch = NA]

d[abs(timestamp - timestamp_d2) <= 120]

Comment: This will work only if assuming that d2 measurements are always taken a few seconds after d1 measurements. I can not assume that. d2 measurements can be taken a few seconds before or a few seconds after d1 measerements
Comment: This could be done by setting `roll = 'nearest' to join to nearest observation and then subsetting on whether the absolute difference between the two timestamps is smaller than 120. I'll edit the answer as it takes a few steps.
Comment: In the current solution there won't be NA values in the result table and some observations will be lost


Java Spring Rest não funciona com pacotes separados

Question: Pessoal minha aplicação spring rest so funciona quando coloco as classes(models,controllers) tudo no mesmo pacote da classe application, dessa forma funciona mas imagine a desorganização disso !!
https://i.stack.imgur.com/FYIav.png
*Dessa forma não funciona, o servidor sobe para a porta 8080 porem não retorna meu metodo, apenas se eu colocar o controller dentro do pacote da application
CONTROLLER
package com.camila.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ClienteController {
    @GetMapping("/clientes")
    public String listar() {
        return "TESTE ";
     }
}

APPLICATION
package com.camila.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringApiApplication.class, args);
    }
}

POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/>
    </parent>

    <groupId>com.camila.web</groupId>
    <artifactId>Spring_API</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring_API</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>2020.0.1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-r2dbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>dev.miku</groupId>
            <artifactId>r2dbc-mysql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.r2dbc</groupId>
            <artifactId>r2dbc-h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Comment: Obrigado pela dica, o site ja me ajudou muito pra resolver outros problemas mas nunca de fato fiz pergunta aqui
Comment: só esta com um comando pra trocar a porta "server.port = 8090"
Answer: Conforme a documentação do Spring Boot a anotação @SpringBootApplication, entre outras coisas, define a raíz da aplicação. Isso é, por convenção a classe anotada com @SpringBootApplication deve estar no pacote mais externo da hierarquia de classes da sua aplicação.
Na prática a anotação @SpringBootApplication "marca" o pacote da aplicação (bem como todos os pacotes dentro desse pacote) para ser escaneado em busca de componentes anotados do Spring.
Pesando que sua classe SpringApiApplication esteja no pacote com.camila.web o Spring Boot consegue encontrar componentes dentro de qualquer subpacote de com.camila.web, por exemplo:

com.camila.web
com.camila.web.controller
com.camila.web.meupacote.meuoutropacote

Como ClienteController não está dentro do pacote com.camila.web o Spring Boot não sabe como encontrá-lo.
Uma solução para o seu problema, que respeita a convenção do Spring Boot sem fazer uma bagunça, é mover o pacote controller para dentro de com.camila.web.
package com.camila.web.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ClienteController {
    @GetMapping("/clientes")
    public String listar() {
        return "TESTE ";
     }
}

Note que você pode organizar seus componentes como e em quantos pacotes quiser sem desrespeitar a convenção do Spring Boot, desde que todos os pacotes estejam dentro de com.camila.web.
Caso você realmente precise usar componentes em outros pacotes, a anotação @SpringBootApplication possui elementos opcionais scanBasePackages e scanBasePackageClasses utilizados para fazer o Spring Boot buscar componentes em outros pacotes. Por exemplo, considerando a sua estrutura de pacotes atual você poderia  modificar a classe SpringApiApplication da seguinte maneira:
package com.camila.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.camila.controller", "meu.outro.pacote"})
public class SpringApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringApiApplication.class, args);
    }
}

Com isso a sua classe ClienteController, bem como quaisquer outros componentes nos pacotes com.camila.controller e meu.outro.pacote são encontrados pelo Spring.
Lendo o código da classe SpringBootApplication fica claro que toda essa "mágica" acontece pois a anotação @SpringBootApplication é por sua vez anotadada com a anotação @ComponentScan (esse é um exemplo de meta anotação). Por consequência a anotação @ComponentScan também pode ser utilizada diretamente para obter o mesmo resultado:
@ComponentScan(basePackages = {"com.camila.controller", "meu.outro.pacote"})

Dito isso, é recomendável seguir as convenções do Spring para evitar ter que fazer configurações manuais desnecessárias. Por exemplo, caso você venha a trabalhar com JPA o Spring Boot detecta automaticamente entidades e repositórios dentro do seu pacote raíz. Se suas entidades não estiverem dentro do pacote raíz será necessário usar @EntityScan para indicar para o Spring onde encontrar suas entidades e @EnableJpaRepositories para indicar onde encontrar os repositórios.
Esse princípio é chamado Convenção sobre configuração e é especialmente válido em opinionated frameworks como Spring Boot.
Comment: Anthony muito obrigado mesmo pelo tempo, a informação por sí ajuda muita. Porem olha que estranho, quando clico em cima do com.camila.web e peço para criar outro pacote, que seria um subpacote do mesmo, ele cria um dentro de com.camila.web como planejado e um fora como se fosse um espelho, bom testando novamente ainda não funciona , será que estou criando sub pacote da forma errada, segue imagem
Comment: Consegui !! Ficou dessa forma que eu expliquei meio que "espelhando" e depois de alguns reboots deu certo (vai entender ne rs), muito obrigado pela ajuda!
Answer: Só colocar a sua classe "SpringApiApplication" na pasta src/main/java, a classe application tem que ter a mesma hierarquia das pastas, assim ela consegue enxergar as pastas, se ela estiver dentro de alguma pasta ela só irá enxergar o que esta no nivel de hierarquia dela.


Prove that a convex set in $\mathbb{R}^n$ has no homology in positive degrees.

Question: I know you can use this fact to prove the Homotopy Theorem but I now want to use the Homotopy Theorem (i.e. If $f\simeq g:X\rightarrow Y$ then $f_∗ =g_∗ :
H_∗(X) \rightarrow H_∗(Y )$) to prove this fact.
I understand that $H_*(X)=Z_*/B_*$ and that the set, $X$ is convex if $\forall x, y\in X$ and $\forall t\in[0,1]$, $tx+(1-t)y\in X$. What I don't understand is how to use the Homotopy Theorem as instructed, what $Z_*$ and $B_*$ might look like for any convex set, and how to involve the definition of convex in this problem. Granted, some of these thoughts may not be necessary.
Answer: Hint: Prove that a convex set is contractible. More specifically, given a convex set $X \subseteq \mathbb{R}^n$, fix some $x_0 \in X$ and prove that $X \simeq \{ x_0 \}$.
Comment: That makes a lot of sense, thank you!


How to add table data to an Android Widget programmatically

Question: I've been searching the web and Stack Overflow and I can't seem to find an answer that explains clearly what I'm trying to do:
I'd like to display a table inside of my widget, I know widgets are limited to only a few layout types, so I thought the easiest way to do this would be to make a vertical linear layout, then add each row as a horizontal linear layout with textviews as cells inside each one. After coding this in a loop, I can't seem to figure out how to put the linearlayout into the widget...
Here's a more visual idea:
<Vertical linear layout>
 <text view "title">
 <some number of LinearLayouts horizontally - H>
   <some number of textviews>
 </ll -h>
 <text view "footer">
</ll - v>

I'm obviously very new to Android so any help would be great.
Answer: Here is a way I got this to work:
rv2 = new RemoteViews(this.getApplicationContext()
                                    .getPackageName(), R.layout.datarow);
                            if(tr.hasClass("title"))
                                i = 1;
                            else
                                i = 0;
                            for (Element td : tds) {
                                if (td.getElementsByTag("a").size() > 0) {
                                    Elements anchors = td.getElementsByTag("a");
                                    td.text(anchors.get(0).text());
                                    rv2.setTextViewText(R.id.textView2,
                                            td.text());
                                } else {
                                    switch (i) {
                                    case 0:
                                        rv2.setTextViewText(R.id.textView1,
                                                td.text());
                                        i++;
                                        break;
                                    case 1:
                                        rv2.setTextViewText(R.id.textView3,
                                                td.text());
                                        i++;
                                        break;
                                    case 2:
                                        rv2.setTextViewText(R.id.textView4,
                                                td.text());
                                        i++;
                                        break;
                                    case 3:
                                        rv2.setTextViewText(R.id.textView5,
                                                td.text());
                                        i++;
                                        break;
                                    case 4:
                                        rv2.setTextViewText(R.id.textView6,
                                                td.text());
                                        i++;
                                        break;
                                    default:
                                        break;
                                    }
                                }
                            }
                            remoteViews.addView(R.id.layout, rv2);

It's not pretty and I don't like using the switch, but I couldn't figure out how to iterate through the textviews.
I'll leave this open a while longer in case someone can give me a better answer.


How to make a sub menu from a parent menu

Question: Fiddle: https://jsfiddle.net/n3tzbn4o/2/
Sample Css:
/* Reset */
.menu, .menu2,
.menu ul, .menu2 ul,
.menu li, .menu2 li,
.menu a, .menu2 a,
ul, li {
    margin: 0;
    padding: 0;
    border: none;
    outline: none;
}

For the parent menu menu 3 sub menu 2015, how come the sub submenu is inheriting from the menu class and not the menu2 class? Also, how come the hover doesn't change color for the second item inside the menu2 class ul.
Please help me resolve the issue
Comment: I suggest you read about [Specificity and Inheritance](https://www.smashingmagazine.com/2010/04/css-specificity-and-inheritance/) in CSS. All the rules that match apply on an element. They just have different importance, based on selectors specificity and order of CSS rules (from a set of equal strength selectors the last one read applies). Between `.parent .child` and `.grand-parent .child` the one with the closer parent applies (so first one).
Comment: Side note: these css only menus can quite hard to use due to the diagonal problem. See for instance [Breaking down Amazon's mega dropdown](http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown)
Answer:
For the parent menu menu 3 sub menu 2015, how come the sub submenu is inheriting from the menu class and not the menu2 class?

Actually, the sub submenu is inheriting from the .menu2 class.

Also, how come the hover doesn't change color for the second item inside the menu2 class `ul.

Because you have a syntax error in your li tags.

Correct the tags from <l1> ... </l1> to
 ...
, and the link will work.


Map an entity based on one of two different attributes (either one or the other)

Question: I'm developing a web app using Java, Spring and JPA. The use case I would like to discuss with you is quite simple, it just consists of two entities, Wallet and Transaction. In particular a Wallet can have two kind of transactions, incoming and outgoing. Let's see the structure of these two classes.
@Entity
public class Wallet{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long walletId;

    @OneToMany(mappedBy="fromWallet", orphanRemoval = true)
    private List<Transaction> outgoingTransactions;

    @OneToMany(mappedBy="toWallet", orphanRemoval = true)
    private List<Transaction> incomingTransactions;

    ....
}

public class Transaction{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long transactionId;

    @ManyToOne
    @JoinColumn(name = "wallet_id_from")
    private Wallet fromWallet;

    @ManyToOne
    @JoinColumn(name = "to_wallet_id")
    private Wallet toWallet;

    ....
}

This is what my code looks like right now, and it works perfectly. My question is, how can I change the code so that instead of having two different lists I would have just one with both incoming and outgoing transactions? So what I would like is something like this:
@Entity
public class Wallet{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long walletId;

    @OneToMany(mappedBy="{'fromWallet' or 'toWallet'}", orphanRemoval = true)
    private List<Transaction> transactions;

    ....
}

Is it possible to do something like this? Or I must stick to the current solution (two different list)?
Answer: I don't think the situation you are describing can be achieved with JPA tools, but you can of course do something like

Remodel your database and merge both join columns so that you end up with a "classical" OneToMany relationship with the downside that you lost the information if the wallet was from or to.
Create a getTransactions method in Wallet that simply returns a merged immutable list of outgoingTransactions and incomingTransactions without having the downside of 1.


Programmatically create panels page including variants and block plugins inside it

Question: I want to be able to programmatically create a panels page, add a variant and add block plugins to it with specified settings for each block plugin. My ultimate goal is to create a clone of a specified panels page.
My current code is
    $page_storage = \Drupal::entityTypeManager()->getStorage('page');
    $variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
    $page = $page_storage->load($page_id);
    $variants = $page->getVariants();
    foreach ($variants as $variant) {
        $blocks = $variant->getPluginCollections()['variant_settings']->getConfiguration()['blocks'];
        foreach ($blocks as $block) {
            //Here I have block data. Not sure how to take advantage of it though
        }
    }
    $newPage = $page_storage->create([
        'id' => $new_page_id,
        'label' => $new_page_id,
        'description' => $new_page_id . ' description',
        'path' => '/' . $path,
    ]);
    $newPage->save();
    $newVariant = $variant_storage->create([
        'id' => 'test',
        'label' => 'test',
        'page' => $newPage->id(),
    ]);
    $newVariant->save();

The page does get created just fine but the variant does not get assigned to the page. So I'm not sure what I'm missing. Also even if the variant assignment did work I'm not sure how I'd be able to add and set the config of all the custom blocks I added in the regions. Also I just realized I'm going to have to figure out how to set the layout as well.
How do I programmatically create a page variant and assign it to a programmatically created page, and then programmatically add the block plugins to the variant based on the config of another panels page?
UPDATE: I tried using
$newVariant->setPageEntity($newPage);

to set the variant but it still doesn't show as a variant in page manager. Thought when I
var_dump($newVariant->getPage());

it does seem to show the proper page like so

object(Drupal\page_manager\Entity\Page)#1959 (28) { ["id":protected]=>
  string(4) "test" ["label":protected]=> string(4) "test"

(that's just a portion) That is when $new_page_id was set to test.

UPDATE 2:
I'm attempting to take advantage of the createDuplicate function instead, and at this point just trying to make the variant show up. Not worrying about the blocks yet. This is my new code.
    $variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
    $page = $page_storage->load($page_id);

    $id = $page->id();
    $label = $page->label();
    $clone = $page->createDuplicate();
    $clone->set('id', $new_page_id);
    $clone->set('path', $path);
    $clone->set('label', 'Test Page ' . $new_page_id);
    $clone->save();
    $variants = $page->getVariants();
    foreach ($variants as $variant) {
        $var_clone = $variant->createDuplicate();
        $var_clone->set('page', $clone->id());
    }
    $var_clone->save();

However like before, the page gets created but the variant does not get applied.
I tried doubling up and trying multiple methods like so
        $var_clone = $variant->createDuplicate();
        $var_clone->set('page', $clone->id());
        $var_clone->setPageEntity($clone);
        $var_clone->save();

but that also had no effect.

UPDATE 3:
I managed to get the variant to show up by setting the id of the variant clone like so
        $hash = bin2hex(random_bytes(8));
        $var_clone = $variant->createDuplicate();
        $var_clone->set('page', $clone->id());
        $var_clone->setPageEntity($clone);
        $var_clone->set('id', $hash);
        $var_clone->save();

It seems like it wasn't saving because an id wasn't set for the variant. However now there are new errors that I receive whenever trying to edit or save the page variant.

Drupal\Core\Config\ConfigDuplicateUUIDException: Attempt to save a
  configuration entity 'test' with UUID
  '5d091883-6667-4aab-9fd8-c8ef77c871f4' when this entity already exists
  with UUID '11066a36-ca97-428f-aa78-f17b034421d8' in
  Drupal\Core\Config\Entity\ConfigEntityBase->preSave() (line 339 of
  /mnt/www/html/mysite/docroot/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php).

UPDATE 4:
I'm now attempting to duplicate the blocks but I can't seem to load the blocks from the variant config.
$conf = $var_clone->getVariantPlugin()->getConfiguration();
$blocks_config = $conf['blocks'];
foreach ($blocks_config as $uuid => $block_data) {
    var_dump($uuid);
    var_dump($block_data);
}

Gives me the UUID but I want to actually have an object instead of an array so I can do
$block_clone = $block->createDuplicateBlock();

But I can't seem to get the block object from the UUID. I've even tried loading by the Uuid specifying every type of entity possible like so.
$conf = $var_clone->getVariantPlugin()->getConfiguration();
$blocks_config = $conf['blocks'];
foreach ($blocks_config as $uuid => $bdata) {
                foreach (array_keys(\Drupal::entityTypeManager()->getDefinitions()) as $etype) {
                    $block = \Drupal::service('entity.repository')->loadEntityByUuid($etype, $uuid);
                    var_dump($block);
                }
}

But I get nothing but NULL when trying to print each attempt at loading the entity by the UUID I got from the variant block configuration. Are config entities loaded a different way? Or does the UUID supplied not refer to something that can be loaded?
Answer: I managed to accomplish this with the following code:
    $path = '/' . $path;
    $page_storage = \Drupal::entityTypeManager()->getStorage('page');
    $variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
    $page = $page_storage->load($page_id);

    $id = $page->id();
    $clone = $page->createDuplicate();
    $clone->set('id', $new_page_id);
    $clone->set('path', $path);
    $clone->set('label', $label);
    $clone->save();
    $variants = $page->getVariants();

    foreach ($variants as $variant) {
        $hash = bin2hex(random_bytes(8));
        $var_clone = $variant->createDuplicate();
        $var_clone->set('page', $clone->id());
        $var_clone->setPageEntity($clone);
        $var_clone->set('id', 'variant_id_' . $hash);
        $var_clone->save();

        $conf = $var_clone->getVariantPlugin()->getConfiguration();
        $blocks_config = $conf['blocks'];
        unset($conf['blocks']);
        foreach ($blocks_config as $uuid => $bdata) {
            $hash = bin2hex(random_bytes(8));
            $bdata['uuid'] = $hash;
            $conf['blocks'][$bdata['uuid']] = $bdata;
        }
        $var_clone->getVariantPlugin()->setConfiguration($conf);
        $var_clone->save();
    }

Edit $conf['blocks'][$bdata['uuid']] = $bdata;
Comment: Thanks for sharing, i edited `$conf['blocks'[$bdata['uuid']]] = $bdata;` to `$conf['blocks'][$bdata['uuid']] = $bdata;` as an anonymous to make it work.


Normal distribution test sample

Question: I am trying to use R to find the probability that 2 randomly selected out of 10 would be within a certain range. I am not sure if I am doing it right. This is with a normal distribution.
prob <- pnorm(4200, mean=3100, sd=600)-pnorm(2800, mean=3100, sd=600)
dbinom(2, size =10, p=prob, log=FALSE)

I'm not sure if I might be overthinking it and that the probability should just be the following because I am only trying to 'probability that two of the ten' being within the range.
pnorm(4200, mean=3100, sd=600)-pnorm(2800, mean=3100, sd=600)
Comment: Can you give more details about the probability you're trying to find? Is the question "What is the probability at least 2 out of the 10 points are within a certain distance of each other", or "at least 2 out of the 10 points are between X and Y", or one of those but with "exactly 2...". Or is the question something else?  Are you looking for an exact solution or is a simulation approximation ok?
Comment: The question is "What is the probability that two of the ten items weigh between 3100 and 4200" They don't elaborate any more on it which has me confused. I have been told there will be no further elaboration at this point.
Answer: Your answer to @DavidLuke does not seem to be consistent with your original Question. What happened to 2800?
Suppose the full question is, "Given that ten observations are taken at random
from $\mathsf{Norm}(\mu=3100,\sigma=600),$ what is the probability that exactly two of the ten lie in the interval $(2800, 4200)?$"  Then you might answer in R as
follows:
p = diff(pnorm(c(2800, 4200), 3100, 600));  p
[1] 0.658086
dbinom(2, 10, p)
[1] 0.0036401

For "at least two of the ten," I get  $0.9995579$ from a slightly different
binomial computation.

Normal distribution test sample


When is this equation true?

Question: For what kind of functions/or for which functions $h(a,b)$ is the below equation true :
assumption is
$\lim_{ x\to\infty }{f(x)}=l_1$,
$\lim_{ x\to\infty }{g(x)}=l_2.$
When is it true that
$\lim_{ x\to\infty }{h(f(x),g(x))}=h(\lim_{ x\to\infty }{f(x)},\lim_{ x\to\infty }{g(x)}) = h(l_1, l_2)$ ?
Comment: The answer is: when the function $h$ is continuous at $(l_1,l_2)$.
Comment: I think you meant to say $f(a,b)$ instead of $h(a,b)$, anyways your counterexample isn't one: $\lim_{x\to\infty} (1+1/x)^{1/x} = 1 = 1^0 = (\lim_{x\to\infty} 1 + 1/x)^{\lim_{x\to\infty} 1/x}$
Comment: Thanks  Anthales, I've made a few mistakes in my question.
Answer: As observed by Rahul Narain, the implication
$$
\lim_{x\to\infty} f(x)=l_1, \lim_{x\to\infty} g(x)=l_2 \implies
\lim_{x\to\infty} h(f(x),g(x))
\tag1$$
holds if and only if the function $h$ is continuous at the point $(l_1,l_2)$. The same is true if $\infty$ is replaced by a number $c$ everywhere in (1).

When is this equation true?


For $\pi$ in the interior of the probability simplex, when is the vector $v$ that solves $v \cdot \pi = 1$ uniquely the vector of ones?

Question: Let $\pi \in \mathbb{R}^K$ be a known element of the interior of the probability simplex:
\begin{equation*}
\pi_k > 0, \qquad \sum_{k=1}^K \pi_k = 1.
\end{equation*}
Let $a \in \mathbb{R}_{++}^K$ be known. The question is: Under what conditions is the vector $b \in \mathbb{R}_{++}^K$ that solves
\begin{equation*}
1 = \sum_k \frac{b_k}{a_k} \pi_k
\end{equation*}
unique?
Clearly $b=a$ is a solution, so another way to state the question is when is $b=a$ the only solution?
One knife-edge case is easy: if $\pi_k = \pi_{\ell} = 1/K$ for all $k, \ell$, then any $b$ that satisfies $K = \sum_k b_k/a_k$ would suffice. But what about for a generic $\pi$?
Answer: We can define the following vector:
$$v := \left[\frac{\pi_1}{a_1} \cdots \frac{\pi_K}{a_K}\right]$$
This is clearly known, since $\pi$ and $a$ are known.
Then the equation can be rewritten as
$$1 = b\cdot v$$
Now the question is, how many $b \in \mathbb{R}^K_{++}$ vectors satisfy this equation?

Exactly $0$, if $v = 0$.
Exactly $1$, if $K = 1$, namely $b = \frac{1}{v}= \frac{a}{\pi} = a$.
Let's say now $K \ge 2$. If there is even one non-zero element in $v$, then there are infinitely many solutions. The zero elements can be multiplied with anything, and at least two non-zero elements can be weighted infinitely many ways to obtain $1$:

For example if $v = [2\ \ 3]$, then $2\cdot \frac{1}{2} + 3\cdot 0 =1$, or $2\cdot 1 + 3\cdot \left(-\frac{1}{3}\right)=1$, or in general, $2c+3\left(\frac{1-2c}{3}\right)=1$, for any $c \in \mathbb{R}$.
Since $c$ changes continuously and the original solution $(b=a)$ is inside the simplex, uncountably infinitely many solutions can also be guaranteed to be inside the simplex.
So $b=a$ is the only solution exactly if $K=1$ (and in this case, $v$ has to be $\ne 0$, which is satisfied by your conditions).
Comment: To keep $b$ strictly positive, I'd need $c \in (0,1/2)$ in that example, but the implication is the same. You didn't use the assumption that $\pi$ is an interior element of the probability simplex, but I guess it imposes no restrictions on the argument because $a$ had no restriction other than being strictly positive? If I add that $a_k > 1$ for all $k$ (true in my case), then $v_k < 1$ for all $k$, but the same logic goes through it seems. Okay, thanks!


Find a constant L for Lipschitz condition

Question: There is a function $f(x) = x^3\sin(\frac{1}{x})$ and I need to do two things:
a) find a constant $L$ that satisfies Lipschitz condition for $x\in[\frac{1}{\pi},\frac{2}{\pi}]$
b) prove that there exists an inverse function to $f: (\frac{1}{\pi},\frac{2}{\pi}) \rightarrow \mathbb R$ and find domain of the inverse function
My attempts:
a) Lipschitz condition claims $\forall_{{x,y} \in (a,b)}$ $|\frac{f(x)-f(y)}{x-y}| \leq L$ . Of course this function is continuously differentiable (on the given interval), so by MVT we know that  $\exists_{c \in (a,b):}\frac{f(a)-f(b)}{a-b} = f'(c)$ so basically I need to find a maximum slope of the function $f$ on the given interval. The first derivative is $x(3x\sin(\frac{1}{x})-\cos(\frac{1}{x})$) and there are two ways: if $f'$ is monotonic on the given interval I only need to check values at the ends of the interval (Weierstrass theorem), and if $f'$ is not monotonic I need to find $c \in (a,b): f'(c) = \max$ so basically look for extrema of $f'$. Neither of these two approaches seems to be easy enough to apply them during the test (I would rather not use wolframalpha or any other drawing tool).
b) of course there exists an inverse function if the given function $f$ is both injective and surjective. But... how to check if this function is injective? I mean, the most obvious condition $f(x) = f(y) <=> x = y$ is not the easiest one to check.
Comment: The derivative is strictly positive on $\left(\frac1\pi,\frac2\pi\right)$ which means $f$ is strictly increasing, and therefore injective.
Comment: That's what I got from wolframalpha, but I don't really know how to prove that. I mean, can I try something like $t = 1/x$ and then take the interval $t \in [\pi, 2\pi]$, but I still don't think that's obvious.
Answer: (a)$f'(x)=x(3xsin(\dfrac{1}{x})-cos\dfrac{1}{x})$,so $f'(x)$is continous on $[\dfrac{1}{\pi},\dfrac{2}{\pi}]$and is bound.$\lvert f'(x)\rvert\le \dfrac{2}{\pi}(3\dfrac{2}{\pi}+1)$.Therefore $L$ can be $\dfrac{2}{\pi}(3\dfrac{2}{\pi}+1)$.
(b)By theorem of inverse function,we only need to find the interval of $f'(x)\ne 0$.$f'(x)=0\Leftrightarrow 3xsin\dfrac{1}{x}=cos\dfrac{1}{x}$.It's easy to know that $cos\dfrac{1}{x}\le 0,3xsin\frac{1}{x}\ge 0$.so $f'(x)\ne 0$ in $[\dfrac{1}{\pi},\dfrac{2}{\pi}].$so there exists a inverse function of $f$on interval $[\dfrac{1}{\pi},\dfrac{2}{\pi}].$
Answer: The way the question is phrased, you're asked to find any constant $L$ that works, not necessarily the optimal one. For $x\in[1/\pi,2/\pi]$, we have
$$\begin{align}
|f'(x)|&=\left|3x^2\sin\left(\frac 1x\right)-x\cos\left(\frac 1x\right)\right| \\
&\leq 3x^2\left|\sin\left(\frac 1x\right)\right|+x\left|\cos\left(\frac 1x\right)\right| \\
&\leq 3x^2+x\leq 4
\end{align} $$
so $L=4$ will work. For part (b), $f'(x)>0$ since $\cos(1/x)<0$, $\sin(1/x)>0$, and $x>0$ when $x\in(1/\pi,2/\pi)$. Hence, $f$ is strictly increasing and injective. Note that $f$ is not surjective on $\mathbb{R}$. You're asked to find the domain of the inverse function which is $f\left[\left(\frac 1\pi,\frac 2\pi\right)\right]=\left(f\left(\frac 1\pi\right),f\left(\frac 2\pi\right)\right)$ since $f$ is increasing and continuous.


Question about Spearman's correlation

Question: I want to measure the associations between a number of variables and all of them are measured on a ratio scale. If I am to run Spearman's correlation, can I just run it on the variables as is? Or do I have to rank them first?
So to give a simplistic example, if variable 1 is IQ score (subject 1 has a 100, subject 2 has a 150, and subject 3 has a 125) and variable 2 is GPA (subject 1 has a 3.1, subject 2 has a 2.9, and subject 3 has a 2.2). Can I just click the button to calculate Spearman's rho based on these numbers… Or for each of the variables do I first need to assign ranks to each of the scores and then click the button to calculate Spearman's rho on the ranks?
I've read online and it's not totally clear. In the link posted below gives an example using variables that are measured on a ratio scale (as mine is) and he/she seems to just be hitting the button to run the correlation without doing any sort of transformation to rank the data first (this person also happens to be using SPSS as I am).
https://statistics.laerd.com/spss-tutorials/spearmans-rank-order-correlation-using-spss-statistics.php
Based on this my guess is that since both of my variables are on a ratio scale, I can simply just run Spearman's on the variables as is without transforming them in any way. But I'm not sure. Any help with answering this question would be appreciated.
Comment: Your question is how to compute Spearman's correlation in SPSS. Purely programming questions are off-topic on Cross Validated; read the guidelines [here](https://stats.stackexchange.com/help/on-topic).
Answer: As @Harvey Motulsky said, software will handle the ranking. But you will probably get the same results even if you rank the variables yourself first. Here is an example using cor.test() in R:
    x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
    y <- c( 2.6,  3.1,  2.5,  5.0,  3.6,  4.0,  5.2,  2.8,  3.8)

    # Converting to ranks
    df <- data.frame(x,y)
    df[] <- lapply(-df,rank,ties.method="min")

    # Raw values
    cor.test(x, y, method = "spearman")

        Spearman's rank correlation rho

    data:  x and y
    S = 48, p-value = 0.0968
    alternative hypothesis: true rho is not equal to 0
    sample estimates:
    rho
    0.6

    # Ranks
    cor.test(df$x, df$y, method = "spearman")

        Spearman's rank correlation rho

    data:  df$x and df$y
    S = 48, p-value = 0.0968
    alternative hypothesis: true rho is not equal to 0
    sample estimates:
    rho
    0.6

Although it does not really matter in this example, how you (and the software) handle the ties could make a difference.
Answer: Any program that purports to run the Spearman test will (presumably) do the ranking itself as a first step. The way to be sure with your program, is to run an example from a text.

Question about Spearman's correlation


Can I import 3d cad model with tree structures to A-frame?

Question: I would like to know if 3d-cad models can be imported to A-frame with keeping it's structure into A-frame.
Thank you in advance!
Answer: Depends what you mean by "3d-cad" models.
A-frame supports a bunch of 3D formats:

https://aframe.io/docs/0.8.0/components/collada-model.html
https://aframe.io/docs/0.8.0/components/gltf-model.html
https://aframe.io/docs/0.8.0/components/obj-model.html

In my experience as long as they are not too complex they render fine.


Linux Kernel delay, below jiffies, without busy-waiting

Question: i need to set a signal high and low by time in a linux kernel, using, timer and mdelay().
hightime: 0.01ms-20.00ms;
lowtime:10ms-1000ms
both are adjustable by userspace.
For the lowtime i use an API timer and for the hightime i use mdelay() and udelay().
Now the problem: if hightime is 9.9ms and lowtime is 10ms the kernel is asleep for the whole time (expect 0.1ms). But my userinterface in the userspace needs to work, while the kernel timer is running.
One jiffie is about 10ms in my system, so i can not use a timer for the lowtime.
Someone got an idea, how i can do these 0.01ms - 10 ms waits in the kernel, so that my userinterface still works properly?
Thanks
Comment: I think you should specify a platform. I see no reason to expect that the kernel should be able to satisfy requirements like this without having some form of dedicated timer hardware you can use.
Answer: You can reduce the 10 ms:
Edit <code>/usr/include/asm/param.h</code> and look for definition of HZ. I guess you'll find 100.
100 Hz presents a period of 10 ms. More modern Linuxes have 250 HZ which would put your time
slice down to 4 ms. You may sqeeze it to 1000 HZ which lets you run at 1 ms slices.
Further reading: Linux kernel map, 7.1. Measuring Time Lapses


Load balance the Load balancer

Question: I am looking to get load balancing for my load balancer.
We are looking to create a fully HA network.
All of our servers are redundant, the databases are redundant, but above them is a single server running nginx as a reverse proxy to distribute requests.
I'm looking for a way to eliminate this danger hotspot, even though the others are all redundant, if this server goes down, no one will receive requests anymore.
And I'm here to get your help on this.
I have found two ways to solve this problem:

FloatingIP: Create a load balancer cluster with Kubernetes = I have a unique cluster IP address that allows me to talk to all nodes. I've done this solution before, so I have a cluster of loadbalancers all running the same nginx service, but our router doesn't allow me to write down the target IP address to send requests to, I can only choose a device. Since the cluster IP address is not attached to a physical machine, I can't use it in our router.

Find a router that directly handles sending a request to multiple servers (like the upstream block in nginx).

I really think that the Floating IP is the best option, but I can't understand why my router cannot use it, so if you have some name of router capable to use Floating IP I would love it.
For several weeks I've been looking for a router that can do both, or find another solution.
Any help would be welcome
Answer: For the sake of explanation let's define the term High Availability which means that we have guarantees that there is always some system that will handle the load. Usually it is implemented by having redundant systems, but it doesn't mean that the load will be distributed between them; it is possible that at every moment of time the single system will process all the load. Load Balancing is a special case of High Availability where the load is distributed between redundant systems, so that could potentially increase the capacity of the service by adding the capacity of all systems in the set.
HAproxy manual states that load balancer typically can outperform around 1000 of application servers it balances (being run on the same hardware), so you don't really have the need to balance it. With that gap in the capacity of the balancer and the service it is hardly useful to load balance the balancer, but that will still increase the complexity of the solution. You'll increase the complexity (increase the cost of the solution and lose some reliability) with no apparent gain.
Usually you balance the load of the servers by making the balancer to know their current load to make educated guesses where to send the next request. The balancer itself is simply made highly available by making it redundant. The floating IP gets assigned to currently performing balancer ("primary") system and if it fails it gets reassigned to the other system ("standby") quickly. All the other time the standby system stands still doing nothing. I understand that the whole system running but doing nothing appears wasteful, but that's not the waste, that's your guarantee that the possible interruption of the service will end very shortly. You may balance some other service on this pair with their roles reversed, so the redundancy will not appear that wasteful, but notice that during outage event both services will be balanced by the same system and therefore it needs the capacity to run them both or both services will degrade, so the "waste" is inevitable. You can also have some randomized load distribution by having two floating IP for the same service and publishing them both in the DNS for the same name, so each client will choose some balancer randomly. Usually you have two balancers and you can manage the floating IPs with the keepalived (which uses VRRP); this is simplest approach with very little setup.
You may also have some static distribution of the load to the balancers by using Netfilter's CLUSTERIP target. In this setup all systems have the same IP address assigned and it's associated with some broadcast MAC address, so all the systems see all the traffic. However, each system only selects a share of the traffic to process and ignores everything else; the selection is made so each request is assigned to one and only one processor. The assignment is made solely on the basis of the source of the request, not making into account the load of systems, so the distribution is "blind". The distribution appears pseudorandom and the it is possible that only one node gets all the load. The algorithm behind it requires that all the participating systems know how many of them are currently online (and each system has an unique individual number) so no request could possibly being lost or processed by more than one system. If any of those clustered processors fails, all other alive systems must reconfigure themselves immediately to account the loss of one processor, otherwise no one of them will consider itself as a valid processor of requests that were previously worked on by that failed system. The Linux's Pacemaker includes the resource agent to use this CLUSTERIP target properly (including the reconfiguration). This configuration is much more complex and therefore it is more brittle and needs much more maintenance and monitoring. It requires Pacemaker which is not very easy to set up, and a cluster messaging layer e.g. Corosync, also proper Pacemaker-based setup needs fencing.
I had a setup with the non-balanced redundant balancers and floating IP managed by the keepalived, I also had a setup with CLUSTERIP managed by the Pacemaker, but I've never tried to marry all of this with Kubernetes.
Answer: Using failover IPs is a horrible solution. It's impossible to check if its working without breaking stuff. It only uses half your capacity. It can take an alarmingly long time to detect that the active node has failed.
Forget trying to recover requests that were being processed at the time a node failed. It is possible but it is really, REALLY difficult and expensive.
Use 2 reverse proxy instances and configure round robin DNS. As they read this, many IT professionals will start reaching for their keyboard, thinking that round robin DNS does not provide high availability. While according to the original specs for TCP the client should wait for a timeout - around 5 minutes. However since at least the turn of millenium, browsers have failed over much faster - in 2005, Chrome and Firefox would failover in less than half a second, while MSIE took around 10-20 seconds. I've not tested this more recently.
Concidentally this is also the simplext way to implement network multipathing to your origin server.
Comment: RR DNS is great only if your clients is browsers only. Failover IP can be a great solution if you configure it correctly - you can easily achieve failover within 1 second. Consider checking out "keepalived"

Load balance the Load balancer


Does this sequence have a convergent subsequence whose natural density is $1$?

Question: Let $(a_n)_n$ be non-negative real sequence and
$$
S_\epsilon = \{n \mid a_n > \epsilon\} \quad (\epsilon > 0).
$$
If the natural density of $S_\epsilon$ is $0$ for all $\epsilon > 0$, does the sequence $(a_n)_n$ have a subsequence that converges to zero and whose natural density is $1$ ?
Comment: You mean a subsequence $a_{n_k}\to 0$ and the natural density of $n_k$ is $1$ ?
Comment: @Ryszard Szwarc Yes !
Answer: Let $S_k=\{n\,:\, a_n\ge {1\over k}\}.$ Consider $R_k=\mathbb{N}\setminus S_k.$ The natural density of $R_k$ is $1.$  Hence there exists $n_1$ such that $${\# \{m\in R_1\,:\, 1\le m< n\}\over n}\ge {1\over 2},\qquad n\ge n_1.$$
Similarly there exists $n_2>n_1$ such that $${\# \{m\in R_2\,:\, n_1\le m< n\}\over n}\ge {2\over 3},\qquad n\ge n_2. $$ By proceeding so on there exists $n_k>n_{k-1}$ such that
$${\# \{m\in R_k\,:\, n_{k-1}\le m< n\}\over n}\ge {k\over k+1},\qquad n\ge n_k. $$
Let $\qquad $ $\displaystyle R=\bigcup_{k=1}^\infty \{m\in R_k\,:\, n_{k-1}\le m<n_{k+1}\}
=\bigcup_{k=1}^\infty R_k\cap [n_{k-1},n_{k+1})$
We claim that  the subsequence  $\{a_n\,:\, n\in R\}$ is convergent to $0$ and the natural density of $R$ is equal $1.$
Observe that for $n\in R$ and $n\ge n_k$ we have $n\in R_l$ for some $l\ge k.$ Hence $a_n<{1\over l}\le {1\over k}.$ Therefore the limit of the subsequence is indeed equal $0.$
Furthermore let  $n_k\le n< n_{k+1}.$ Then
$$ {\# \{m\in R\,:\, 1\le m< n\}\over n}\ge  {\# \{m\in R_k\,:\, n_{k-1}\le m< n\}\over n}\ge {k\over k+1}$$
which implies
$$\lim_n {\# \{m\in R\,:\, 1\le m< n\}\over n}=1$$


Algebra book like Zorich's Analysis?

Question: I was reading a book comparison topic which stated that Zorich's Analysis is a pretty good substitute for spivak+rudin, in that if you don't have the time then reading Zorich's Analysis can compensate for both of these books (and probably more since it's very comprehensive). This makes sense, because seeing as it was written for first year Russian students, it doesn't expect you to have completely mastered calculus, so it starts very concretely with calculus but slowly the abstraction builds up until it's much more abstract than Rudin by the end of volume 2.
Now I was thinking, is there a similar book like that for Algebra? It would be great if I could skip a first year algebra course by reading an Algebra book like Zorich, because I don't enjoy "first courses" too much and even Littlewood discouraged reading "first course" -type books (Fraleigh is a good example of one today) in his Miscellany.
More concretely, the question is this: Is there a comprehensive Algebra book that starts very concretely, say first year material, but then develops to become at least as abstract as say second or third year material? Preferably with hard problems like in Zorich. Such a book would save my time and I'm sure many others'.
Edit: Just to show I've tried answering this, I've found three books so far: Artin's Algebra, Cameron's Intro to Algebra, and Norman's Undergraduate Algebra. Artin could definitely work but I don't know enough about it to make that judgement; Cameron is a bit too slim but apparently covers first, second and even some third year level material in UK universities; Norman is a bit too concrete (many practical applications) so doesn't fit the criteria of being abstract enough, and the problems aren't too challenging.
Thanks
Comment: I used Zorich 1 & 2 in my first year analysis course and hated it. It is rather dense and contains way to much for a first year course. I would compare Zorich with something like Algebra from Lang. A book that I do like is Abstract Algebra from Dummit and Foote. It covers a lot of basic abstract algebra, but with many examples and exercises.
Comment: @Noud: but zorich is actually written for undergraduates.
Comment: yes, I know. Abstract Algebra from Dummit and Foote is also for undergraduates.
Comment: @Noud: thanks I'll check it out
Answer: We use Kostrikin's Introduction to Algebra here in China. We use Zorich for calculus too and I feel they have a somewhat similar style. Try it out, but I think the English version may be fairly old. The latest Russian edition is the 3rd edition.

Algebra book like Zorich's Analysis?


Continuity of homegeneous function

Question: Let $F: R^2_+ \to R$ be positively homogeneous and monotonically increasing.  Is $F$ necessarily continuous?  Here, positively homogeneous means that $F(tx,ty) = tF(x,y)$ for all $(x,y) \in R^2_+$ and $t > 0$.  Monotonically increasing means that if $x_1 \ge x_2$ and $y_1 \ge y_2$, then $F(x_1,y_1) \ge F(x_2, y_2)$, ie, $F$ is increasing in $R^2_+$ when $R^2_+$ has the natural ordering.
Comment: I still have the same question. You would do well to define "positively homogeneous" and "increasing" in this context.
Comment: What does increasing mean in this context?
Answer: So here is a sketch of an approach I think should work. Throughout this post I have written $F(x,y)$ as $f(x+yi)$. I am arguing that $f$ is continuous.
Say you have a sequence of complex numbers $(b_n)_{n=1}^\infty$ that limit to $B\in R^{2}_+$ and you can pick out a subsequence such that $b_n<b_{n+1}$ in the sense that $\operatorname{Re}(b_n) \le \operatorname{Re}(b_{n+1})$ and $\operatorname{Im}(b_n)\le \operatorname{Im}
(b_{n+1})$

Our goal is to show that $\lim_{n\to \infty}{f(b_n)}=f(B)$. This is the definition of $f$ continuous at $B$.

The plan here is to pick out a subsequence of $(b_n)$ such that each point is in between the two lines $L$ and $M$ where line $L$ contains the origin and $e^{i \theta}$ and $M$ is a line that contains the origin and $e^{i(\theta+\epsilon)}$.
Then define $L^x_n$ to be the point on $L$ with the same real part as $b_n$ and $(L^y_n)$ to be the point on $L$ with the same imaginary part as $b_n$. We define $L^x$ to the point on $L$ with same real part as $B$ and $L^y$ as the point on $L$ with the same imaginary part as as $B$.
We define $M^x_n, M_n^y, M^x, M^y$ analogously.

Surely we have
  $$\lim_{n\to\infty} f(L^x_n)= f(L^x), \lim_{n\to\infty} f(L^y_n)= f(L^y), \lim_{n\to\infty} f(M^x_n)= f(M^x), \lim_{n\to\infty} f(M^y_n)= f(M^y) $$
  We get all these limits because along $L$ and $M$ we have that $f$ is continuous along any line through the origin. We know that $f$ is continuous for any fixed $\theta$ because $f(r e^{i \theta})=rf(e^{i \theta})$. So here we have used the homogeneity of $f$.

But now what bounds do we have on $B$? And $b_n$?

For this we use the monotonicity of $f$
$$f(M^x)<f(B)<f(L^x) \mbox{ and } f(L^y)<f(B)<f(M^y)$$
$$f(L^x_n)<f(b_n)<f(M_n^x) \mbox{ and } f(M_n^y)<f(B)<f(L_n^y)$$

And now I think good things happens as we take $\epsilon$ small. We can squeeze $b_n$s towards $f(B)$.
Comment: Thanks for this.  It's very helpful.  However, there seems to be one step missing that I can't fill.  As we take $\epsilon$ to be increasingly small, we hope that $f(L^x) \to f(M^x)$.  If this holds, we are done, because $f(B)$ lies between these two values.  But all we know is that $f$ is monotone, which means that there might be a jump discontinuity at precisely $B$, so that $\lim_{\epsilon \to 0} f(L^x) < f(B) \leq \lim_{\epsilon \to 0} f(M^x)$ (for instance).  Am I missing something? It seems that if $f$ is continuous along rays and along vertical and horizontal lines, $f$ is continuous.

Continuity of homegeneous function


Computing P-value

Question: I am doing a lower-tail test and my z-statistic is  -1.57. Now I have to calculate the p-value. My way of finding the p-value using a z-table is: I looked for row -1.5, then look for column 0.07. The entry is 0.0582. Since the test is a lower-tail form, the p-value is 0.0582. But from this source I found the p-value for the given problem is 0.58051. How was this calculated?
Comment: The significance level is not needed for this question, I removed the somewhat confusing discussion of that part as an unnecessary distraction.
Answer: I see no other explanation to this, than that those guys from the website made a mistake, seeing $0.58051$ in $0.058051$
Comment: That is , I am correct.

Computing P-value


How to define a new class extending standard javascript class like Array?

Question: It is my understanding that the "standard" way to define a new ClassB extending ClassA is as following:
function ClassA() {
   this.a = {};  // ClassA's instance member.
}
ClassA.prototype.meth1 = function () { .. }  // ClassA's method, shared by all instance.

function ClassB() {}
ClassB.prototype = new ClassA()              // <== "standard" way to extend
ClassB.prototype.meth2 = function () {...}   // ClassB's method

When I try to define a new class ArrayX like following:
function ArrayX() {
}
ArrayX.prototype = new Array()
ArrayX.prototype.removeDup = function removeDup() {
     var o = [];
     for(var j=0; j<this.length; j++) {
          if(notExist(this[j])
              o.push(this[j])
     }
     return o
     function notExist(itm) {
         for(var j=0; j<o.length; j++) {
               if(o[j]===itm)return false
         }
         return true;
     }

var x = new ArrayX();
console.log(x.length) // returns 0.  Good
console.log(x)        // returns [].  Good
x[0] = 0;
console.log(x);    // returns [].  No good.  I expect x should have one element.
(new ArrayX([1,1,2,3,3])).removeDup()   // I expect returns [1,2,3]

I know I can define the function-removeDup in following way:
Array.prototype.removeDup = function removeDup() { ...}

However, I just want to define a new class extending some standard javascript class like Array, or, even the DOM classes.
So, how to define a new class extending standard javascript class like Array?
Comment: possible duplicate of [Is this a reasonable way to 'subclass' a javascript array?](http://stackoverflow.com/questions/4761000/is-this-a-reasonable-way-to-subclass-a-javascript-array)
Comment: Basically, you shouldn't try to do this, it won't work well. The definitive treatment of the topic is at http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/. You can also find half-a-dozen related questions on SO by searching for "subclass array javascript". By the way, `Array` is not a "class", it's a "built-in type".
Comment: can you describe some scenario how you gonna use ArrayX? I suppose you just want to create some object which can be applied to Array funcitons?
Comment: It is not a particular scenario to solve question.  Adding new functions to **Array.prototype** is one approach#1.  To create a new class to extend Array like this **ArrayX.prototype = new Array()** is another approach#2.  So, why approach#2 does not work?  In standard DOM classes.  They are all extending from bottom EventTarget class up to.  I just want to know how can I further extending such standard classes?  I believe there must be some way!
Comment: torazaburo, thank you for comment and the link (perfectionkills.com). From the link, it has a lot of content and I get inspiration. I have posted my answer, please have a look. –
Answer: no need to create a very own class:
Array.prototype.myFunction = function(){
   //your custom code
}

Comment: Max, thank you for answer.  I know this approach.  Now, I have changed the question to make sure is answered in the direction I am looking.  Please have a look.
Answer: By referring link#1, link#2 & link#3, I try this, it works as I expected.
function ArrayX() {
     // Array.apply(this, arguments)
                                  // calling Array() has same effect as new Array() according to
                                  // [link#3]
                                  // It is no good here.

     this.push.apply(this, arguments); // <-- this works OK. Suggested by link#2

     debugger;                    // Now, `this` has array of value [1, 1, 2, 3, 3], which is
                                  // found in arguments when running new ArrayX(1,1,2,3,3);
                                  // Good.
}
ArrayX.prototype = new Array();   // Suggested by link#1
ArrayX.prototype.removeDup = function removeDup() {
     var o = [];
     for(var j=0; j<this.length; j++) {
          if(notExist(this[j]))
              o.push(this[j])
     }
     return o
     function notExist(itm) {
         for(var j=0; j<o.length; j++)
              if(o[j]===itm)return false
     }
     return true;
}
var x = new ArrayX(1,1,2,3,3);  // x is now [1,1,2,3,3].  Good
console.log(x.length)           // 5                      Good
var y = x.removeDup();          // y is [1,2,3].  Good
console.log(y);

Comment: Is `length` handled properly?


Merging PDF with pdfforge.dll in VBA on Windows x64

Question: So I'm working around a macro that should merge some pdf. The code is pretty simple and work well using a dll given by PDFCreator setup (pdfforge.dll), but only on Windows 32Bits (XP or 7).
Here is the code
Dim Pdf As Object
Set Pdf = CreateObject("pdfforge.pdf.pdf")

Pdf.MergePDFFiles_2 FR1, Target & "FusionFR1.pdf", True
Pdf.MergePDFFiles_2 FR2, Target & "FusionFR2.pdf", True
Pdf.MergePDFFiles_2 FR3, Target & "FusionFR3.pdf", True
Pdf.MergePDFFiles_2 FR4, Target & "FusionFR4.pdf", True

Note that FR1, FR2, FR3 and FR4 are just some array of string which contains the path of those pdf I'm trying to merge.
So as I said, this code work well on any computer with Windows 32 Bits, as long as the version of PDFCreator provide the pdfforge.dll. But on a Windows 64 Bits, I've got an "Excel Automation Error" on
Set Pdf = CreateObject("pdfforge.pdf.pdf")
I guess this is a dll which work only on a 32 bits system and by default, a windows 64 bits try to work through a 64 bits environment. So I tried to register this dll for the 32 bits environment through two methods without having satisfying result :

Register 32 bit COM DLL to 64 bit Windows 7
http://www.gfi.com/blog/32bit-object-64bit-environment/

Hope you guys could help me :)
PS: I'm working on Excel 2007
Answer: Well I managed to make it work !
I mainly use the Assembly Registration Tool, regasm.exe
First, I've made sure that the dll was not registered anywhere, that is to say both in Framework 32 Bits and 64 Bits, using regasm.exe with the /u argument.
Then I registered the dll in framework\v2.0.50727 using the /codebase argument (I've read from multiple source this argument is the key)
Finally, I've created a text file named excel.exe.config in the root of the excel directory which contains
<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

This should force excel to use framework v2.
Hope this could help someone one day ;)