shared_ptr garbage collection when make_shared() is called multiple times

Question: I'm aware that using smart pointers like std::shared_ptr adds garbage collection when the pointer goes out of scope, but I'm unclear as to whether the garbage collection also works if I call make_shared()multiple times on one shared_ptr.
For example:
std::shared_ptr<MyClass> mcPtr;

void assignment(int i)
{
  mcPtr = std::make_shared<MyClass>(i);
}

void main()
{
  assignment(5);

  // Some time later

  assignment(10);  // Does this cause a memory leak?
}

Comment: _"... but I'm unclear as to whether the garbage collection also works ..."_ Yes, it will delete the old value, and replace with the new one. Also note _garbage collection_ is somewhat different than using smart pointers.
Comment: Presented code doesn't exhibit memory leak.
Comment: Only way to leak memory with `shared_ptr` (assuming using it properly, without ugly hacks) is to create circular dependency. Reassigning to it definitely would be handled properly.
Answer: using a std::shared_ptr doesn't add garbage collection but when the shared pointer is destroyed at the end of the scope it is declared in it's destructor will be called.  The destructor of the shared pointer handles releasing the memory.
Now when you call = std::shared_ptr::operator=() is called.  From the standard 220.127.116.11.3.4

Effect: Equivalent to shared_ptr(std::move(r)).swap(*this)

So mcPtr is given the value of the new shared_ptr and the new shared_ptr gets the contents of mcPtr.  Then the new shared_ptr goes out of scope, the destructor is called and the shared_ptr takes care of itself.
Comment: Temporary objects are destroyed at the end of the full expression they're part of.  for more reading: [C++: Life span of temporary arguments?](http://stackoverflow.com/questions/2506793/c-life-span-of-temporary-arguments)
Comment: That's a great explanation, thanks! Am I right in assuming the new shared_ptr will go out of scope immediately because it's an rvalue? Or does it wait until the end of the function? Or to put it another way, would this cause a problem (assuming the optimiser didn't remove it)... `for(;;) { mcPtr = make_shared(); }`
Comment: Just as an aside, how does this actually work behind the scenes? The obvious question would be _"but what calls the shared pointer's destructor?"_ Obviously the compiler reclaims memory on the stack (and other temporary location like registers) when those objects go out of scope, but does it have the sense to call the destructors of those objects too? Is that how smart pointers work?
Comment: @SonicAtom Yes.  When an objects lifetime ends, which is end of scope for named objects or end of expression for temporary objects, the destructor of the object is called.  This is what makes value semantics so attractive as it is like have instant automatic garbage collection


How to add a dependency on a generated source file in Kbuild?

Question: Let generate_testapi.py be a script in my Linux kernel module's source tree, that ingests mymod_test.h and generates a interface source file toward userland (ioctl, debugfs, you name it), and lets name this $(obj)/mymod_test_interfaces.gen.c.
In the Kbuild makefile let mymod-y be the variable containing the list of object files that form the module, i.e.
How does a Kbuild-ish rule look like, that adds the object file compiles from the generates source as a dependency of mymod and describes the generation process.
The following, my first naive attempt on such a rule set does not work.
obj-m := mymod.o

mymod-y := \
    mymod_kmod.o \
    $(obj)/mymod_test_interfaces.gen.o

$(obj)/mymod_test_interfaces.gen.o: $(src)/mymod_test.h $(src)/generate_testapi.py
    $(src)/generate_testapi.py < $(src)/mymod_test.h > $<

Trying to make with that, the resulting error is, that there is no rule to make mymod_test_interfaces.gen.o.
Update (due to comment by Alexandre Belloni)
Yes, I also tried a generator rule of the form
$(obj)/mymod_test_interfaces.gen.c: $(src)/mymod_test.h $(src)/generate_testapi.py
    $(src)/generate_testapi.py < $(src)/mymod_test.h > $<

with the same result, which is, that it does not work.
Comment: Shouldn't the second mymod_test_interfaces.gen.o be mymod_test_interfaces.gen.c ?
Comment: @AlexandreBelloni: That's what I'm trying to find out. Good comment, but of course I also tried that and no, it didn't give the desired result.
Answer: There is another issue: you can't have a C file that has the same name as the module when trying to build a multiple file module. Rename mymod.c to mymod-core.c
Then, the following should work:
obj-m := mymod.o

mymod-objs := mymod-core.o mymod_test_interfaces.gen.o

$(obj)/mymod_test_interfaces.gen.c: $(src)/mymod_test.h $(src)/generate_testapi.py
    $(src)/generate_testapi.py < $(src)/mymod_test.h > $@

I've actually tested the following:
diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile
index 4387ccb79e64..47fdc3a73c75 100644
--- a/drivers/misc/Makefile
+++ b/drivers/misc/Makefile
@@ -71,3 +71,8 @@ OBJCOPYFLAGS_lkdtm_rodata_objcopy.o := \
                        --rename-section .text=.rodata
 $(obj)/lkdtm_rodata_objcopy.o: $(obj)/lkdtm_rodata.o
        $(call if_changed,objcopy)
+
+obj-m := mymod.o
+mymod-objs := mymod-core.o mymod_test_interfaces.gen.o
+$(obj)/mymod_test_interfaces.gen.c:
+       echo "int variable;" > $@
diff --git a/drivers/misc/mymod-core.c b/drivers/misc/mymod-core.c
new file mode 100644
index 000000000000..b39aa4b9ae8d
--- /dev/null
+++ b/drivers/misc/mymod-core.c
@@ -0,0 +1,19 @@
+#include <linux/module.h>
+#include <linux/platform_device.h>
+
+extern int mymod_variable;
+
+static int mymod_probe(struct platform_device *pdev)
+{
+       mymod_variable = 2;
+
+       return 0;
+}
+
+static struct platform_driver mymod_driver = {
+       .driver = {
+               .name = "mymod",
+       },
+       .probe = mymod_probe,
+};
+module_platform_driver(mymod_driver);

It properly results in:
$ make
  CHK     include/config/kernel.release
  CHK     include/generated/uapi/linux/version.h
  CHK     include/generated/utsrelease.h
  CHK     include/generated/bounds.h
  CHK     include/generated/timeconst.h
  CHK     include/generated/asm-offsets.h
  CALL    scripts/checksyscalls.sh
  CHK     include/generated/compile.h
  CC [M]  drivers/misc/mymod-core.o
echo "int variable;" > drivers/misc/mymod_test_interfaces.gen.c
  CC [M]  drivers/misc/mymod_test_interfaces.gen.o
  LD [M]  drivers/misc/mymod.o
  LD      arch/x86/boot/compressed/vmlinux
  ZOFFSET arch/x86/boot/zoffset.h
  AS      arch/x86/boot/header.o
  LD      arch/x86/boot/setup.elf
  OBJCOPY arch/x86/boot/setup.bin
  OBJCOPY arch/x86/boot/vmlinux.bin
  BUILD   arch/x86/boot/bzImage


Keep the URL alias for a node when using href

Question: I am using Drupal 6 and I have set aliases for my nodes under Administer > Site building > URL aliases. This works properly; for example, I have alias = about/faq, node = node/33, and when I click on my menu the page shows up properly on the browser address bar as about/faq.
The problem I have occurs when I want to reference my node from hyperlinks placed in a page on the website (or any other website). I want to use
 instead of
 so that I don't have to change the href if I later decide to change the alias. However, when I do this, the page shows up as http://mywebsite.com/node/33 on the browser address bar.
I was wondering whether it would be possible to have it show up as http://mywebsite.com/about/faq on the address bar instead.
Answer: You can use global redirect so that it does a 301 redirect to the aliased url.
I would recommend you additionally use path redirect so that you can keep old aliases and redirect them to the new one. That way you don't even have to worry about using the unaliased url.


What happens when I include a squared variable in my regression?

Question: I start with my OLS regression:
$$
y = \beta _0 + \beta_1x_1+\beta_2 D + \varepsilon
$$
where D is a dummy variable, the estimates become different from zero with a low p-value.
I then preform a Ramsey RESET test and find that i have some misspesification of the equation, i thus include squared x:
$$
y = \beta _0 + \beta_1x_1+\beta_2x_1^2+\beta_3 D + \varepsilon
$$

What does the squared term explain? (Non-linear increase in Y?)
By doing this my D estimate does not vary from zero any more, with a high p-value.
How do i interpret the squared term in my equation (in general)?
Comment: One thing that might help is to center $x$ *before* creating your squared term (see [here](http://stats.stackexchange.com/questions/29781/when-should-you-center-your-data-when-should-you-standardize/29782#29782)). As for the interpretation of your squared term, I argue that it's best to interpret $\beta_1x_1+\beta_2x_1^2$ *as a whole* (see [here](http://stats.stackexchange.com/questions/28730/does-it-make-sense-to-add-a-quadratic-term-but-not-the-linear-term-to-a-model/28750#28750)). Another thing is that you may need an interaction, that means adding $\beta_4x_1D+\beta_5x_1^2D$.
Comment: Probable reason: $x_{1}^2$ and $D$ seem to explain the same variablility in $y$
Comment: possible duplicate of [Why ANOVA/Regression results change when controlling for another variable](http://stats.stackexchange.com/questions/25605/why-anova-regression-results-change-when-controlling-for-another-variable)
Comment: I don't think it's really a duplicate of that question; the solution is different (centering variables works here, but not there, unless I am mistaken)
Comment: @Peter,  I interpret this question as a subset of "Why is it that when I add a variable to my model, the effect estimate/$p$-value for some other variable changes?", which is addressed in the other question. Among the answers to that questions are collinearity (which gung does allude to in his answer to _that_ question)/content overlap between predictors (i.e. between $D$ and $(x_1,x_1^2)$, which I suspect is the culprit in this case). The same logic applies here. I'm not sure what the controversy is but that's fine if you and others disagree. Cheers.
Comment: @Macro I agree that colinearity is likely the problem here, but when the problem is caused by a squared variable, centering removes the problem. I don't think this works for two related variables (as in the other problem). Am I wrong?
Comment: @Peter, since the answer is collinearity/content overlap, I think that makes it a subset of the other question. Fixes for collinearity may be context dependent but I don't think this makes it a different question. To address your comment directly - centering _may_ alleviate the problem but if $D$ (or $P(D=1)$) is a function of $x_1$, then it almost certainly will not, in which case you're even more closely back to the content conveyed in the linked question. I still don't see the controversy but we don't need to agree on this, so let's end the duplicate vs. not duplicate convo here. Cheers.
Comment: Macro & Peter are both correct. Our policy is to identify *close* duplicates; if there could be any difficulty deciding whether a question truly is a duplicate, then it's not close enough. However, the present question has been answered in many threads on this site: a little more diligence in searching is likely to produce much useful and relevant material.
Comment: **Very** closely related: [Adding both quadratic and interaction terms to the model affects significance](http://stats.stackexchange.com/questions/34488/adding-both-quadratic-and-interaction-terms-to-the-model-affects-significance)...
Comment: See my blog post for a simple step by step guide and how to interpret the age & age squared variable. The example follows the wage equation mentioned in the post above. http://www.excel-with-data.co.uk/blog-1/how-to-regression-analysis-in-excel/
Comment: At this time the link to the blog post just mentioned by @user34889 is no longer active, thus underlining frequent advice here to be wary of posting such links unless known to be stable.
Answer: Well, first of, the dummy variable is interpreted as a change in intercept. That is, your coefficient $\beta_3$ gives you the difference in the intercept when $D=1$, i.e. when $D=1$, the intercept is $\beta_0 + \beta_3$. That interpretation doesn't change when adding the squared $x_1$.
Now, the point of adding a squared to the series is that you assume that the relationship wears off at a certain point. Looking at your second equation
$$y = \beta _0 + \beta_1x_1+\beta_2x_1^2+\beta_3 D + \varepsilon$$
Taking the derivate w.r.t. $x_1$ yields
$$\frac{\delta y}{\delta x_1} = \beta_1 + 2\beta_2 x_1$$
Solving this equation gives you the turning point of the relationship. As user1493368 explained, this is indeed reflecting an inverse U-shape if $\beta_1<0$ and vice versa. Take the following example:
$$\hat{y} = 1.3 + 0.42 x_1 - 0.32 x_1^2 + 0.14D$$
The derivative w.r.t. $x_1$ is
$$\frac{\delta y}{\delta x_1} = 0.42 - 2\times 0.32 x_1 $$
Solving for $x_1$ gives you
$$\frac{\delta y}{\delta x_1} = 0 \iff x_1 \approx 0.66  $$
That is the point at which the relationship has its turning point. You can take a look at Wolfram-Alpha's output for the above function, for some visualization of your problem.
Remember, when interpreting the ceteris paribus effect of a change in $x_1$ on $y$, you have to look at the equation:
$$\Delta y  = (\beta_1 + 2\beta_2x_1)\Delta x$$
That is, you can not interpret $\beta_1$ in isolation, once you added the squared regressor $x_1^2$!
Regarding your insignificant $D$ after including the squared $x_1$, it points towards misspecification bias.
Comment: A partial derivative is still the right way to go here. The interpretation of all coefficients is *ceteris paribus*, i.e., holding everything else constant. That's exactly what you are doing when you take a partial derivative.
Comment: Hi.  If you had several predictors should you use partial derivatives or total derivatives (diferentials)?
Comment: See this [UCLA IDRE page](https://stats.idre.ucla.edu/other/mult-pkg/faq/general/faqhow-do-i-interpret-the-sign-of-the-quadratic-term-in-a-polynomial-regression/) to complement @altabq's great answer.
Comment: @altabq Even though beta 1 is negative, aren't there cases where it isn't an inverse U-shape?
Comment: @chunguc1004, you are right. The shape of the curve depends on beta 1. If beta 1 is positive, we have a U-shape and vice versa for negative beta 1.
Answer: A good example of including square of variable comes from labor economics. If you assume y as wage (or log of wage) and x as an age, then including x^2 means that you are testing the quadratic relationship between an age and wage earning. Wage increases with the age as people become more experienced but at the higher age, wage starts to increase at decreasing rate (people becomes older and they will not be so healthy to work as before) and at some point the wage doesn't grow (reaches the optimal wage level) and then starts to fall (they retire and their earnings starts to decrease). So, the relationship between wage and age is inverted U-shaped (life cycle effect). In general, for the example mentioned here, the coefficient on age is expected to be positive and than on age^2 to be negative.The point here is that there should be theoretical basis /empirical justification for including the square of the variable. The dummy variable, here, can be thought of  as representing gender of the worker. You can also include interaction term of gender and age to examine the whether the gender differential varies by age.


Postestimation test

Question: I have run two regression models. one is GLM with logit link and Binomial family and the other is tobit regression. I want to compare the coefficient of some of my independent variables in each model. I have tried the Wald test '' Test command'' in stata.
But, I am not sure if that is correct to use it for a GLM regression model too. Would you please recommend me an appropriate test of hypothesis to be used after GLM and Tobit.
Comment: Is this question stupid to ask or why no one is pointing any idea.
Comment: Request you to wait for some more time. It's been just two hours since you have posted this question. Patience will yield a good response to this question.
Answer: The Wald test doesn't allow you to "compare the coefficients" of the independent variables across models, as you seem to intend. It is meant to test a restriction on one or more coefficients (say $\beta = 0$) in one specific model.

Postestimation test


uninstall module that depends on relation module, which is disabled

Question: I am a maintainer of the crm_core module. The Drupal7 version depends on the relation module to provide relationships between contacts. The depend module can not be uninstalled while the relation module is disabled.
Is there a solution? Or, is this one of the limitations of disabling modules, which might be why disable was dropped in Drupal8.
2273255 -
Can't uninstall crm_core_relationship when relation module has been disabled
Answer: The issue described in Can't uninstall crm_core_relationship when relation module has been disabled is that crm_core_relationship_uninstall() is calling functions defined in a disabled module. When a module is disabled, Drupal won't load it, and all the module functions won't be available.
Either crm_core_relationship_uninstall() first loads that module file with  drupal_load('module', 'relation'), before calling its functions, or the code in relation_delete() and relation_type_delete() is duplicated in functions accessible from crm_core_relationship_uninstall().
That issue isn't present in Drupal 8, as in Drupal 8 modules can only installed or not installed; they cannot be anymore disabled as in Drupal 7.
Comment: I used the drupal_load function, and it works! [changes](https://git.drupalcode.org/issue/crm_core-2273255/-/compare/7.x-1.x...2273255-unintall-disabled-relation?w=1)


SML: LookSay recursion

Question: I am doing self-study on functional programming and there is no teacher could guide me. Thanks for help me!
(*lookSay:int list=>int*int list
ENSURE: true
REQUIRE: computes the look-and-say sequence, for example list of l=[2,2,2] which would be read as "three twos"  =>[(2,1),(1,2)] *)

here is my code:
    fun lookSay(x:int list)=
    case x of
    []=>[]
      | l::ls =>
    let fun helper(l,l'::ls',acc)=
              if l=l'
              then helper(l,ls',acc+1)
              else (acc,l)::lookSay(ls)
    in
        helper(l,ls,1)
    end

I don't understant why it doesn't work. the solution offered by others is using a helper function runWith(x,L) returns (repeated, tail) :  but I don't know how to come out this solution..
    fun runWith (_:int, [] : int list) : int list * int list = ([], [])
  | runWith (x, y::L) =
    if x = y then
      let
        val (repeats, tail) = runWith(x, L)
      in
        (x::repeats, tail)
      end
    else
      ([], y::L)

Comment: Think about how your `helper` handles the case of the empty list.
Answer: I'd start off by formatting your solution like this:
fun lookSay [] = []
  | lookSay (x::xs) =
    let
      fun helper(y, z::zs, count) =
          if y = z
          then helper(y, zs, count + 1)
          else (count, y) :: lookSay zs
    in
      helper(x, xs, 1)
    end

I've used x, y and z rather than l and l' because I find that l can be hard to read: I can't easily see if it's a lowercase L, an uppercase i, or a 1. Since we're actually using the constant 1 also, this adds to the confusion.
I've also done some variable renaming: You have one pair of l and ls in the scope of the case-of, and another identically named pair of l and ls inside the helper function that shadow the outer variables. While this works, it is extremely confusing the have different things in close proximity named the same.
Similarly I renamed acc into count to clarify what it accumulates.
As molbdnilo hinted, your problem lies in a missing pattern match. The ML compiler should warn you of this:
! Toplevel input:
! ..........helper(y, z::zs, count) =
!           if y = z
!           then helper(y, zs, count + 1)
!           else (count, y) :: lookSay zs
! Warning: pattern matching is not exhaustive

Which hints that helper should also have a [] pattern.
As for the strategy of this solution: The inner helper function does two things that necessitates an inner helper function. First, it has an extra argument for the "current" item, which I called y, and second, it has the accumulating argument, which I called count. Peculiarly, helper calls lookSay rather than itself.
But only the second of these is truly necessary, since you can also use the head of the list argument to keep the "current" item:
fun lookSay xs =
  let
    fun go [] _ = []
      | go (x::y::zs) count =
        if x = y
        then go (x::zs) (count + 1)
        else (count + 1, x) :: go (y::zs) 0
  in
    go xs 0
  end

This strategy looks at the first two elements of a list at once, x and y, and if they're equal, it discards one but increments count. If x and y are not equal, this marks the end of the sequence of xs, so a (count + 1, x) element is emitted and go can call itself recursively on y::zs.
I've preserved the bug that is also present in your example. In my version molbdnilo's hint can be rephrased as "Think about how the go function handles lists with exactly one element."

I think that to make this function slightly more useful, you want to actually emit a plain list:
fun concatMap f xs =
    List.concat (List.map f xs)

fun flatten pairs =
    concatMap (fn (n, x) => [n, x]) pairs

fun lookSay xs =
  let
    fun go [] _ = []
      | go (x::y::zs) i =
        if x = y
        then go (x::zs) (i+1)
        else (i+1,x) :: go (y::zs) 0
  in flatten (go xs 0) end

Assuming that the bug gets fixed, this should give you:
- lookSay [1, 1, 1, 2, 2, 3];
> val it = [3, 1, 2, 2, 1, 3] : int list

SML: LookSay recursion


Como trazer resultado SQL agrupado por ano e dentro os meses

Question: Tenho uma tabela assim:
data               |id
2017-02-01 00:00:00|1
2017-02-01 00:00:00|5
2017-04-01 00:00:00|2
2018-02-01 00:00:00|3
2018-04-01 00:00:00|4

Aí eu faço uma consulta com PHP no Mysql que me traz
SELECT id, data
FROM orders
GROUP BY data

e traz no php
foreach($results as $row){
echo date('m',$row->data).'
';
}

o resultado acima fica:
02
04
02
04

Mas queria que ele trouxesse agrupado por ano tbm:
2017
02
04

2018
02
04

Answer: Bem, sem saber o que está retornando fica bem difícil responder. Você pode tentar com esse código. Ele cria uma matriz para agrupar seus resultados em um array multidimensional.
foreach($results as $row){
    $mes = date('m',$row->data);
    $ano =  date('y',$row->data);
    $dia = date('d', $row->data);
    $intervals[$ano][$mes] = $dia;

}

foreach($intervals as $ano => $meses){
    echo $ano . "

";
    foreach($meses as $mes => $dia){
        echo $mes . "
";
    }
}

Comment: ele tá trazendo os resultados vazio, fiz um echo $mes e $ano, veio certinho, mas no intervals, veio vazio
Comment: na verdade, ele apare como resultado: ano
Comment: Bem testa esse novo (editado). caso dê errado você pode me mostrar qual função ou método você usa para obter `$results`
Comment: Perfeito! deu certinho, valeu!!!
Comment: As manipulações que o PHP tem com arrays são as ferramentas mais poderosas que a linguagem possuí. O programador que dominar bem essas manipulações terá uma produtividade acima da média.  ;)
Comment: vou dar uma estudada nisso, sou iniciante ainda, vlw!!
Comment: Recomento  PHP - Programando com orientação a objetos - Pablo Dall'Oglio. O primeiro capitulo traz uma abordagem prática às ferramentas de manipulação de valores.
Comment: só teve um problema na verdade,  se tiverem 2 meses do mesmo ano só aparece 1 mês, ex: datas 02/2018, 03/2018 e 02/2017, só aparece 02/2018 e 02/2017
Comment: Eu editei a resposta. Bem seria bom se você fornecesse um `var_dump($results)`
Comment: Show, agora deu certinho, muito obrigado!
Answer: Primeiro problema no seu código é que se a data for a mesma e a hora diferente, eles não será agrupados, então o ideal é você agrupar pelo ano e mês da data, o select ficaria assim:
SELECT id, data
FROM orders
GROUP BY YEAR(data), MONTH(data);

Já a impressão na tela ficaria assim:
$anoAnterior = '';
foreach($results as $row){
    $anoAtual = date('Y', $row->data)
    if (($anoAnterior != '') && ($anoAnterior != $anoAtual))
        echo "
";
    if ($anoAnterior != $anoAtual)
        echo $anoAtual.'
';
    echo date('m', $row->data).'
';
}


Compound interest - relationship between $\frac{r}{n}$ and $r$?

Question: The compound interest formula $A=P\left(1+\frac{r}{n}\right)^{nt}$ is usually used in examples where you are given a nominal annual rate and then calculate the accrued amount, where $\frac{r}{n}$ is the "monthly" rate.
e.g. nominal interest rate $= 5\% \,\,\text{p.a}, P = \$100 $ and this is compounded monthly.
So we say $ A= 100\left(1+\frac{0.05}{12}\right)^{12}=\$105.116...$
We have in fact earned $\approx5.116\%$ interest. This is what is called the "effective interest rate".
So which is the "correct" annual rate and what has $\frac{r}{n}$ got to do with $r$? Why do we say $\frac{r}{n}$ is the monthly rate when the "true" monthly rate would be in this example $\sqrt[12]{1.05}-1$, giving us an annual interest of $5\%$. I guess my question is really what logic would lead you to divide $\boldsymbol{r}$ by the number of compounding periods? I can't seem to understand the reasoning behind that. As in the example, the effective rate seems unrelated or somehow arbitrary compared to the nominal rate.
The naive answer would be if you have $5\%$ interest per year, you will get $\frac{1}{12}$ of this rate every month, but given that you know this will be compounded, why would you do this?
Apologies if this has been asked before, this is a question that has occasionally bothered me and I have never found an answer.
Comment: @Tavish why must the annual rate be uniformly distributed? And why is $\frac{r}{n}$ used instead of for example $\sqrt[n]{1+r}-1$ which would give the same accrued amount at the end of the year?
Comment: Note that $\sqrt[n]{1 + r} - 1 = \frac{r}{n} + O(r^2)$ so $\frac{r}{n}$ is the linear approximation of the effective per-period rate, close for small values of $r$.
Comment: The amount is being compounded every month, i.e. being multiplied by a certain factor of the form $(1+r')$. Now since the interest rate for the whole year is $r$, the interest rate must be 'uniformly distributed' into the months giving that the monthly interest rate is $\frac{r}{12}$.
Answer: The answer has as much to do with terminology as anything else.  When we say that the nominal annual interest rate is $5\%$, that means something very specific:

If interest is accrued at a nominal annual rate of $5\%$, compounded $n$ times per year, then on each compounding period the interest rate is $5\%/n$.

Another way of interpreting the nominal rate is that if there were no compounding, i.e. $n = 1$, then the nominal annual rate would tell us the actual (or effective) annual growth rate.
Quoting a nominal rate gives a convenient, if sometimes misleading, way of talking about the interest rate in a way that is independent of the number of compounding periods.  Meaning that whether we are discussing a $5\%$ nominal rate compounded quarterly, daily, continuously, etc., the nominal rate stays the same.
In some sense, then, the nominal rate is more practical to work with, because you need less information to understand it and make informed decisions.  If, for example, you are comparing two loans with nominal annual rates of $5\%$ and $6\%$, respectively, then you clearly want to go with the first, because no amount of compounding is going to raise the effective rate of the first above $6\%$.  In fact, the highest effective rate a $5\%$ nominal rate can have is if it were compounded continuously, in which case the effective rate is $$e^{0.05} - 1 \approx 0.0513 = 5.13\%.$$
The comparison would be more nuanced if, for example, you were comparing a nominal interest rate of $5\%$ compounded daily with a nominal interested rate of $5.05\%$ compounded semiannually.  In the first case, the effective rate is $$\left(1+\frac{0.05}{365}\right)^{365} - 1 \approx 0.0513 = 5.13\%,$$ whereas the effective rate of the second is $$\left(1 + \frac{0.0505}{2}\right)^{2} - 1 \approx 0.0511 \approx 5.11\%.$$  Here the compounding makes a (slight, but appreciable) difference, and you would actually choose the account with the higher nominal rate because it has a lower effective rate.
So, it's important to understand both types of interest rates, as well as when to pay close attention to detail.
Comment: This not only explains the usefulness of a nominal rate, it also explains why I might care about the limit of $\left(1+\frac{r}{n}\right)^{nt}$. Superb.


Why are Galerkin methods/FEMs used for solving PDEs and rather not ODEs?

Question: I have not yet understood Galerkin methods and in general not the structural differences between ODEs and PDEs (of course I know the basics but not why PDEs ist so much different except that they contain partial derivatives w.r.t. several variables).
For instance, I don't understand why and what it means that ODEs can only be a finite-dimensional approximation of PDEs.
I guess, it is related that I don't understand why Galerkin methods or related methods are used for PDEs but never for ODEs (or are there any examples)?
Thanks in advance. I am very new to the theory of solving PDEs.
Comment: Galerkin-like methods are used for boundary value problems in ODE. Only there they are called "multiple shooting".
Answer: Here comes a list of what I think that maybe could be relevant for you:

SUNA41, 1-D introduction to FEM

2-D Elementary Substructures

Circuits on an arbitrary triangular lattice

Quadrilateral Algebra

Resistor Models for Diffusion in 3-D

Background, philosophy and parent website:

The Manifesto

Unified Numerical Analysis
Answer: I would rather say initial value problems are numerically solved by time-stepping and boundary-value problems by Galerkin/FEM.
For example the transient dynamics of a mechanical structure, given by a PDE, is typically discretized in space by finite-elements and in time by time-stepping (e.g. Newmark). On the other hand a beam, string or some one-dimensional structure with BCs on both sides is described by an ODE and solved by FEM-like methods (BVP solvers, which are different from ODE solvers), whereas most ODEs have initial values, e.g. motion of a falling ball or a multibody-system.


How is it a let if the shuttle is caught on/in the net?

Question: I am studying the Laws of Badminton. I am concerned about point 14.2.3 under Law 14 for Lets. The point states that:

14.2.3
  [It shall be a let, if] after the service is returned, the shuttle is:

18.104.22.168
  caught on the net and remains suspended on its top, or
22.214.171.124
  after passing over the net is caught in the net;

I understand the first point. In it, the shuttle is stuck on the top white ribbon of the net. In this scenario, the shuttle is most probably oriented base pointed upwards, with its feathers stuck on the white ribbon.
I however fail to understand how the second point represents any scenario other than the first point. If the shuttle "passed over the net", then it means to me that it "has crossed across the net", and therefore can't be "caught" on it!
I need help visualizing the scenario in the second point (22.214.171.124).
Comment: Similar: [Shuttle getting stuck to the net after crossing](https://sports.stackexchange.com/questions/3671/shuttle-getting-stuck-to-the-net-after-crossing/3678)
Answer: This let is called if the shuttle tumbles over the net and then gets caught in the net. In this situation, the shuttle has passed over the net - albeit not at speed, but tumbling, typically after striking the net cord.
It happens much more often if the net is either very fine, or has holes in it.
Comment: Do you mean something like this https://imgur.com/a/A8Vax ?
Comment: Yup, although in practice I believe it happens more with downwards drop/smash shots then upwards ones.


Getting to wrong day of the week when using the object java.util.Date

Question: I'm trying to retrive a date from a datePicker and create a java.util.Date Object and i don't understand why i'm getting the wrong day of the week in the selectedDate variable. The currentDate variable is correct.
String dateStr =  String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear) + "/" + String.valueOf(year);
String timeStr = String.valueOf(hourOfDay) + ":" + String.valueOf(minute);

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date selectedDate = simpleDateFormat.parse(dateStr + " " + timeStr);
Date currentDate = Calendar.getInstance().getTime();

System.out.println("selectedDate = " + String.valueOf(selectedDate));
System.out.println("currentDate  = " + String.valueOf(currentDate));

Output:
selectedDate = Mon Jun 13 12:44:00 WEST 2016
currentDate  = Wed Jul 13 12:44:04 WEST 2016

Answer: You should check (print or debug) value of monthOfYear - the output shows that its value is 6 when you seem to expect it to be 7 (probably because you haven't accounted for the fact that datePicker.getMonth() returns a value between 0 and 11).
Since you don't show how you obtained the value it's hard to say much more.
Answer: Try this:
Calendar c = Calendar.getInstance();

int[] date = {
        c.get(Calendar.DATE), c.get(Calendar.MONTH),
        c.get(Calendar.YEAR), c.get(Calendar.DAY_OF_WEEK)
};

date[1]+=1;

This setup uses the Calendar class, which is integrated into Android. date[1] += 1 is required in order to get the accurate month as the index on it goes from 0-11. All the others are fine as far as I know.
Answer: it actually looks for me, that a some point you start to count from '0' and on the other from '1'.
maybe try to pass the strings to the console for debugging first.


Passar parametro GET pelo AJAX para ativar pagina

Question: Estou precisando fazer o redirecionamento apos fazer alguns comandos no php preciso carregar um ajax.
O link que envia para pagina PHP:
href="ajax/deletaPessoaVinculo.php?a=1&c=MEMBR&pb=3&p=vinculo.php?c=MEMBR"

Após isto recebo no php do deletaPessoaVinculo.php
$w_COD_IDENT_VINCU = ( isset($_GET['c']) ? $_GET['c'] : "" );
$w_COD_IDENT_PESSO = ( isset($_GET['pb']) ? $_GET['pb'] : "" );
$w_acao = ( isset($_GET['a']) ? $_GET['a'] : "" );
$w_pagina = ( isset($_GET['p']) ? $_GET['p'] : '');

Faço o que preciso fazer na página e no final faço:
header('Location: ajax/'. $w_pagina);

Porém não está retornando.
Na verdade quero deletar algo, e ao remover quero da um reload na página.
Comment: No console do browser, quando você faz essa requisição, ela esta sendo redirecionada? creio eu, que ela faz o `redirect` na requisição ajax que você fez, aconselho a você usar algum retorno em vez do `redirect` e dependendo desse retorno você faz o reload através do `javascript`
Answer: Isso está acontecendo, provavelmente porque o último parâmetro p está com a url p=vinculo.php?c=MEMBR, e há um ?, que significa que irá começar a parte de queryString, porém esta parte já começou, teste deixar o parâmetro da url, ficando:
href="ajax/deletaPessoaVinculo.php?a=1&c=MEMBR&pb=3&p=vinculo"

e ao dar o redirecionar fazer isso:
header('Location: ajax/'. $w_pagina . ".php?c=" . $w_COD_IDENT_VINCU);

Abs.
Comment: A sua indicação resolveu o problema, apesar de não ter utilizado este método para o mesmo, eu fiz dando include na página, pois o request ainda estava acessível.


Cloudbees Jenkins dashboard customization

Question: I would like to know how to customize dashboard on Jenkins under Cloudbees.
In the build execution I'm generating different reports (PMD, Cobertura, etc) but I don't know how to add/publish these reports in the dashboard.
Looking on Jenkins Wiki I've found this topic. It says:

On the create new view page, give your view a name and select the Dashboard type

The problem is that there isn't any "Dashboard type" and only the following options are available:

Groovy Script View
List View
My View

and none of these options allows to add reports.
Answer: "Free" and "Base" cloud plans provides only the essenstial jenkins plugins. Please
Refer: https://grandcentral.cloudbees.com/services/plans/dev.
Comment: Yes, I know. I'm using only "essential plugins" presents in the free plan. The plugins I'm using are generating reports. The problem I'm facing is that the reports are not published!
Answer: Try a "List view" instead. You can make this the default view under using the /configure page.


How to programmatically add a field to all product types?

Question: In Drupal 7, I need to programmatically add a file field to all product types. I've tried the following in the enable hook for my module, but to no avail:
$field = array(
  'field_name' => 'my_name',
  'type' => 'file',
  'cardinality' => -1
);
field_create_field($field);

// Create the instance on the bundle.
$instance = array(
  'field_name' => 'my_name',
  'entity_type' => 'product',
  'label' => 'label',
  'bundle' => 'product',
  'required' => TRUE,
  'settings' => array(),
  'widget' => array(
    'type' => 'file_generic',
  ),
);
field_create_instance($instance);

What am I doing wrong?
Comment: Are you sure about the entity type?
Answer: The entity as defined by drupal commerce should be commerce_product:
function commerce_product_entity_info() {
  $return = array(
    'commerce_product' => array(
      'label' => t('Commerce Product'),
      ...
    ),
  );
  ...

  return $return;
}

Answer: first of all you must get a list of all existing product type, commerce_product_types() is the function which will do the job , next for each product type you can add an instance of the created field. final code looks like this :
$field = array(
  'field_name' => 'my_name',
  'type' => 'file',
  'cardinality' => -1
);
field_create_field($field);
$product_types = commerce_product_types();
// Create the instance on the bundle.
foreach ($product_types as $key => $type) {
  $instance = array(
    'field_name' => 'my_name',
    'entity_type' => 'commerce_product', //commerce_product is true
    'label' => 'label',
    'bundle' => $key', //Bundle name replaces dynamically
    'required' => TRUE,
    'settings' => array(),
    'widget' => array(
      'type' => 'file_generic',
    ),
  );
  field_create_instance($instance);
}


How to alter a custom text field in a block with AJAX

Question: We have a block on a basic form listing several items and each item has a number of PDF files on the server to show by a users request.
Each item has an Id (nnn) which is displayed in a text field wrapped as
item nnn

the object is when a user clicks the link, the div should be replaced by a list showing the links to the corresponding PDF files to download.
There are lots of Ajax examples that create their own form, but none so far that comes close to our application in replacing a div in a block.  We could do the Ajax request in a direct way but prefer to use the Drupal api's for stability and manageability, the only question remains is how to..  so examples or ideas are appreciated.
Answer: You have some examples in "Examples for Developers" https://www.drupal.org/project/examples
If you see in ajax_example module, you have "Ajax Link" which points to the url ajax_link_callback,  (defined by  menu hook ajax_link_callback in file ajax_example.module, line 181).
This menu hook has a callback function (see file ajax_example_misc.inc, line 102), which does the magic.
You can see that the ajax response is made with a few components. First the $commands array with the target div and the content to output. Then this array is wrapped in another array ($page), and delivered by the function: ajax_deliver.
Note that the original link ( which is produced by the menu callback ajax_example_render_link() in file ajax_example_misc.inc, line 22), has a use-ajax class attribute and previously the drupal.ajax library is added to the page.
Comment: Thanks Fernando, I will look in to it, as time was of an essence I made it work with direct AJAX call in a custom script calling a (registered) custom PHP module


how to see pdf files in firefox without downloading it by IDM

Question: when any pdf files are opened in firefox browser, it is captured by IDM .it is not opened in browser. please tell how to see pdf files in brwoser without disabling IDM.
when i click on any link of pdf files , it is automatically captured by iDM
Comment: This is not a programming question.
Answer: View PDF files in Firefox without downloading them
Comment: Nice thanks for finding this article for him. @user10220 the important part is in options under the applications tab: [image](https://support.cdn.mozilla.net/media/uploads/gallery/images/2013-02-23-15-01-33-b3b88b.png)


Are all pure tones that are separated by intervals of greater than a minor third equally consonant?

Question: In this Quora answer
Why do certain musical notes sound good together?
the answerer claims

it is important to distinguish between pure tones, that is, simple sine waves, and real tones, such as those produced by a musical instrument or human voice, which in fact contain a (mostly) harmonic series of overtones of varying amplitudes. Psychoacoustic experiments on untrained listeners involving the perceived consonance of pairs of pure tones yields a surprising result. Consonance decreases rapidly as the pitch interval increases from zero (that is, a single tone), as one might expect from our experience with real tones, reaches a nadir at about one semitone, and then reaches nearly 100% again near a minor third. However, consonance is not perceived to decrease again as the interval is increased. That is, all pure tones that are separated by intervals of greater than a minor third are equally consonant.

I googled a bit and could not find evidence for this claim. It is an interesting claim and I would like to read more about the reasoning behind this.
He says

Why might this be? Johnston suggests that the answer may have something to do with the bandwidth of the frequency-tuned cochlear cells that detect sound in the inner ear. Two tones separated by larger than the bandwidth of a cochlear cell do not interfere in the ear at the site of transduction, whereas tones within the bandwidth do.

But again, I am unsure why a google search did not turn up more information. He cites a book and, if necessary, I will track it down at my library and read it, but I decided to ask here first to see if anyone has further information before resorting to that.
My Question:
Are all pure tones that are separated by intervals of greater than a minor third are equally consonant? Why?
Comment: A key quote from your "quora" link is **it is important to distinguish between pure tones, that is, simple sine waves, and real tones**. Pure tones are almost unheard-of (intentional pun) in western music. The only instrument that comes close is the ocarina. If you do experiments with electronic sounds, you need to be careful to avoid intermodulation distortion - a good way to do that is to use a separate amplifier and speaker system for each pure tone. Any scepticism based on your interacting with "real musical instruments" is very likely to be irrelevant to the scientific question.
Comment: I'm inclined to get a synth going and find out for myself. I'll report back if no great answer is posted.
Comment: Thanks very much! I think I tried this before myself, but I don't remember this effect. But I know nothing really, so do share your findings.
Comment: From a [mathematical standpoint](http://music.stackexchange.com/a/4441/28), it's absurdly false.  I also don't believe for a second that even a tenth of people would perceive a 6th as equally consonant to a perfect fifth, for example.
Comment: I was extremely skeptical.
Comment: @alephzero I am afraid I do not follow. Are you saying that it doesn't matter if I use synthesizers or real instruments?
Comment: @MatthewRead your linked answer contradicts your claim -- note how the 2nd diagram is essentially flat above about a 3rd; this is the phenomenon that this question is about -- degree of consonance between pure (sinusoidal) tones.
Comment: Previous comment refers to the accepted answer; not @MatthewRead 's
Answer: The answer is no, according to William Sethares's Tuning, Timbre, Spectrum, Scale. See Fig 3.8 on Page 47, also reproduced as Figure 1 at http://www.acousticslab.org/learnmoresra/moremodel.html

This figure shows that at lower frequencies (100Hz), significantly more than a single octave is required for dissonance to die down between two pure tones (sinusoidal). Only above 1000Hz is the statement true.
Actually, looking at Kameoka & Kuriyagawa, Consonance theory part I: consonance of dyads, which Sethares claims as evidence, the curves seem to be off, and should be expanded horizontally. So when Sethares claims, "such curves have become widely accepted", that apparently shouldn't mean that they are in any way accurate.
But at least, Kameoka & Kuriyagawa's data also supports the answer: No, you need more than an octave. But after that the statement is roughly true.
Answer: This question gets at the how, but right now I don't have a good explanation of the why.
To my ear: yes they are. For frequency ratios above ~1.25 you just hear two tones "on top of" one another.  Each is identifiable as a separate entity.  It is only at the lower ratios that they merge together into a single, more dissonant, sound.
I tested this by constructing a PureData patch, using two osc~ objects, the first at 440Hz, the other tunable from 440Hz-880Hz.  The PureData source code follows:
#N canvas 1920 0 1918 1049 10;
#X obj 305 531 dac~;
#X obj 365 319 osc~ 440;
#X obj 401 43 hsl 128 15 0 1200 0 0 empty empty empty -2 -8 0 10 -262144
-1 -1 0 1;
#X obj 412 189 pow 2 0;
#X obj 395 125 t b f;
#X obj 361 88 / 1200;
#X floatatom 391 272 5 0 0 0 - - -;
#X floatatom 570 262 5 0 0 0 - - -;
#X obj 291 441 *~ 0.49;
#X obj 393 162 f 2;
#X obj 166 230 osc~ 440;
#X obj 372 238 * 440;
#X connect 1 0 8 0;
#X connect 2 0 5 0;
#X connect 3 0 7 0;
#X connect 3 0 11 0;
#X connect 4 0 9 0;
#X connect 4 1 3 1;
#X connect 5 0 4 0;
#X connect 6 0 1 0;
#X connect 8 0 0 0;
#X connect 8 0 0 1;
#X connect 9 0 3 0;
#X connect 10 0 8 0;
#X connect 11 0 6 0;

Comment: You posted something that looks like a list of commands to some tool, or maybe a file that you can load into some tool. What is this? How can I use it to repeat your experiment?
Comment: @anatolyg it's PureData -- added link in body of answer.
Answer: If true, a possible explanation is that, since the tones are pure, there is no beating between upper harmonics of the tones. Dissonance is certainly more noticeable when there is beating between harmonics. If harmonic-rich 200 Hz and 293 Hz frequencies are played simultaneously, the 3rd harmonic of the 200 Hz tone will be 600 Hz while the second harmonic of the 293 Hz tone will be 586 Hz. There will be beating between these harmonics at a rate of 14 beats per second, the difference between 586 and 600. This will make the interval sound dissonant. If the 200 and 293 Hz tones are pure, there will be no beating since the upper harmonics will not be present. Whether this will sound equally consonant to an interval with pure frequencies of 200 and 300 Hz, I don't know, but the pure tone interval of 200 and 293 will certainly be less dissonant than the harmonically-rich interval of the same frequencies.


.change does not work when element is bound to another?

Question: Not quite sure how to explain this but here goes.
I have a function which hides/shows based on a checkbox:
$("#checkbox").change(change_visibility);
  function change_visibility() {
   if ($("#checkbox").is(":checked")) {
       $("#theForm").fadeTo("opacity", "1", function() {
        //End Animation
     });

     } else {
       $("#theForm").fadeTo("opacity", "0.3", function() {
         //End Animation
     });
   }

Problem is that now I have bound this checkbox to a button elsewhere and change() is not behaving as I would expect.
   $("#myButton").click(function(){
      $("#checkbox").attr("checked", true);
   });

Even though the checkbox is changing, as it should, it doesnt seem to be calling the change_visibility() function as it does when I click on it manually.
Any idea why this would be?
Answer: Whenever you change the status or value of an input element, the change event is not triggered.
But you can trigger it manually:
$("#checkbox").prop("checked", true).change();

Comment: Wow super fast thank you so much! I have seen this change() attached to the end before and never knew what that was all about. Now I know. =)
Comment: Huh answered so fast I actually have to wait to mark it correct.
Answer: The simple way would be to do this
$("#myButton").click(function(){
      $("#checkbox").attr("checked", true);
      $("#checkbox").change();
});

Answer: Sounds like the .change() event doesn't get fired when you change the checkbox manually. But the solution is still very simple. Just call the change_visibility() function yourself:
  $("#myButton").click(function(){
      $("#checkbox").attr("checked", true);
      changeVisibility();
  });

Comment: You know I actually tried this and it did not work either, it didnt even call the function. Any idea why this would not work???
Answer: Attach an event handler to change event and call the change method on button click.
$("#checkbox").change(function() {
   if (this.checked) {
       $("#theForm").fadeTo("opacity", "1", function() {
        //End Animation
     });

     } else {
       $("#theForm").fadeTo("opacity", "0.3", function() {
         //End Animation
     });
   });

 $("#checkbox").attr("checked", true).change();

Answer: Try
$("#myButton").click(function(){
      $("#checkbox").attr("checked", true).trigger('change');
});

That should trigger the change event after you dynamically check the box.


How to programmatically get the location where npm installs global modules

Question: I want to programmatically find out the folder where npm installs global modules. This question is similar, but the answer doesn't work for globally installed modules: How to get details of npm installed modules programatically?
Answer: NPM's primary job is "to put things on your computer."  Their folders documentation details what it puts where
Due to differences between operating systems, the .npmrc config, and the prefix property, it's easiest to rely on npm to determine the global install directory by using npm root like this:
$ npm root -g

You can execute a command line binary with Node.js like this:
const { exec } = require('child_process')
const { promisify } = require('util');

async function main() {
    let execAsync = promisify(exec);
    let { stdout: globalPath } = await execAsync("npm root -g");
    console.log(globalPath);
}

Alternatively, in order to access the npm module programmatically, you'll need to install it locally:
$ npm i npm --save

And then you can run the following code:
const npm = require("npm")
const { promisify } = require('util');

async function main() {
    await promisify(npm.load)()
    let globalPath = npm.root
    console.log(globalPath)
}

Further Reading

Where does npm install packages?
Global npm install location on windows?
Comment: Sadly the programmatic API for NPM was removed in NPM 8.0
Answer: From the nodejs website:

globally - This drops modules in {prefix}/lib/node_modules, and puts executable files in {prefix}/bin, where {prefix} is usually something like /usr/local. It also installs man pages in {prefix}/share/man, if they're supplied.

To get the prefix enter:
npm config get prefix

Edit:
To do it from node use the npm npm module. Something like this will work:
var npm = require("npm")
var myConfigObject = {}
npm.load(myConfigObject, function (er) {
    if (er) return handleError(er)
    console.log(npm.get('prefix'));
})

Comment: Another note, it looks like they did it slightly differently on windows than linux. The global modules are installed at /node_modules in widows, whereas they're installed at /lib/node_modules in linux.
Comment: module.paths.push(/node_modules)
Comment: Thank you sir! Now if I could only figure out how load the global npm module so I could get the correct prefix from javascript rather than from a command execution, I'd be all set!
Comment: So actually tho, mine was in /node_modules - there is no lib or bin folder for me. I'm on windows.
Comment: There's an npm module for npm. Maybe this could help.
Comment: Tried it. Unfortuantely A) the version you wrote up there won't work (it should be `npm.prefix`), and B) the prefix it returns is the prefix of the local module installation, not the global installation
Answer: If you don't want to depend on npm:
const { resolve } = require('path')
const globalPath = resolve(process.execPath, '../../lib/node_modules')

Comment: This won't work when the "prefix" property is set, making global node_modules live somewhere else.
Comment: Don't think this works for [global npm install location on windows](https://stackoverflow.com/q/33819757/1366033)


Is there a robust test for stochastic dominance between two random variables?

Question: I am trying to compare the errors from two statistical models in order to give evidence to one being "better" in terms of lower prediction error than the other.
To formalize this, I thought that a test of stochastic dominance between two collections of random variables (the OOS errors) would be a good idea. Ideally the null hypothesis would be :
$$\mathbb{H}_0: F(x) \ge G(x) \forall x \in \mathbb{R} $$
I have found resources pointing me to the Kruskal-Wallis test, but unfortunately cannot seem to find a paper explicitly stating and proving one of these (or similar) null hypotheses. Many sources I check simply state that the null is that the medians of the two distributions differ, but this is not what I want to check. Any help is appreciated.
Comment: Since you have two samples, I believe the Mann-Whitney test would work for you: https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test.  Look at the first sentence under "Assumptions and formal statement of hypotheses".
Comment: It seems to be a paired sample, right?
Answer: I don't see that you need a special proof for this.  It is foundational that these nonparametric tests are testing for stochastic dominance.  If you need a reference to cite, I would just use a basic nonparametric statistics textbook.  I tend to use Hollander & Wolfe (2013) for that sort of thing.
Regarding your situation, here are a couple additional points:

The Kruskal-Wallis test generalizes the Mann-Whitney U-test to more than two groups, but you only seem to have two, so it's not really necessary.
The Krukal-Wallis, and the Mann-Whitney, are for independent groups, but you presumably have paired data.  That is, you have the prediction error for a given observation from each of two models.  Those two errors are meaningfully paired.  You need to take that into account, so something like the the Wilcoxon signed rank test is presumably appropriate.
These tests are for stochastic dominance, but that isn't quite the same as being tests of medians.  It is common to call them tests of medians, but that is only true under very restrictive circumstances (cf, What exactly does a non-parametric test accomplish & What do you do with the results?).
Lastly, it isn't clear what you mean by "robust test for stochastic dominance" in the title.  Nonparametric tests are already robust in the sense typically meant in statistics.
Comment: One of the well known texts on nonparametric tests, including permutation tests: Conover, W. J. (1998). [*Practical Nonparametric Statistics*](https://www.wiley.com/en-us/Practical+Nonparametric+Statistics%2C+3rd+Edition-p-9780471160687) (3rd ed.). Hoboken, NJ: Wiley.
Answer:
You could rank your observations and report the proportion of ranked values in each of the group and say something like, Proportion of higher ranked values in A > Proportion of higher ranked values in B. Visualising the mean rank helps.
Here is a resource that helped me: Kruskal–Wallis test: compare more then two groups by Dr. Yury Zablotski.

As you can see, the mean (in red) and the median (in blue) of group salaries are showing similar trend, but neither of them catches the high-salaries-bump of "Advanced" education group. The mean-rank (in black) does.

If you are specifically looking to answer a question like this: Is the performance of A better than performance of B, or does A have higher proportion of greater scores (values) than B, then the Vargha Delaney A effect size measure might be one way to go. Here are a couple of resources:

1. A nice blog post talking about when and how to use it

Instead, we could use the Vargha-Delaney A measure, which tells us how often, on average, one technique outperforms the other. When applied to two populations (like the results of our two techniques), the A measure is a value between 0 and 1: when the A measure is exactly 0.5, then the two techniques achieve equal performance; when A is less than 0.5, the first technique is worse; and when A is more than 0.5, the second technique is worse. The closer to 0.5, the smaller the difference between the techniques; the farther from 0.5, the larger the difference.

Vargha and Delaney's paper

Note: It only compares two groups
Comment: Hello, Rohan. That actually can be a useful answer. Could you paraphrase what the blog preached? Once a link rots, it won't be helpful in the future.
Comment: Thank you for the suggestion. I have made some changes now. Added a plot and paraphrased some parts I think are important
Comment: +1 for working on the suggestions.


Prove that $\int_{0}^{+\infty} e^{-tx}\frac{\sin x}{x} dx$ is differentiable

Question: I'm trying to prove that
$$F(t) = \int_{0}^{+\infty} e^{-tx}\frac{\sin x}{x} dx$$ is differentiable in $]0,+\infty [$. First, $F(t)$ is well defined since $F(t) \leq \int_{0}^{+\infty} e^{-tx} dx$ whose integration is finite.
Second, I've tried first to prove that $F(t)$ is continuous using dominated convergence theorem, by that I have to find a domination as an integrable function $g$ so that
$$
\lvert e^{-tx}\frac{\sin x}{x} \rvert \leq g(x)
$$
I've thought of $g(x) = \lvert \frac{\sin x}{x} \rvert$ but it's not a good candidate since it is not Lebesgue integrable. So I've used directly the definition of continuation, it seems good since:
$$
\lvert F(t) - F(t') \rvert \leq \int_{0}^{+\infty} \lvert e^{-tx} - e^{-t'x} \rvert dx \overset{t \to t'}{\to} 0
$$
Third, unfortunately, this direction doesn't help to prove that $F(t)$ is derivable. So, I've came back to the differentiability under domination, it doesn't seem working neither. I've tried to look for a domination of
$$
\lvert (e^{-tx}\frac{\sin x}{x})' \rvert = \lvert t e^{-tx}\frac{\sin x}{x}\rvert
$$
but cannot found any.
Many thanks for any suggestion.
Comment: Is this helpful? https://math.stackexchange.com/questions/84382/show-that-laplace-transform-is-differentiable
Comment: Not sure if helpful but I assume you know this is a laplace transform.
Comment: What about applying the limit form of the derivative to $F$ directly, then proving you can take the resulting limit inside the integral?
Comment: @eyeballfrog it's not possible to applying the limit form without proving it's derivable first.
Comment: @Sorfosh yes, I'know this is a Laplace transform, but it applies on a non Lebesgue integrable function sin(x)/x, so the dominated convergence theorem does not apply.
Comment: @TaThanhDinh That doesn't sound right. If $\lim_{h\rightarrow 0}[F(t + h) - F(t)]/h$ exists at a point, then the function is necessarily differentiable at that point. So all you have to do is show existence of that limit.
Comment: @eyeballfrog I think I've caught your point. The continuity and derivation are local properties, so it's not necessary to look for a domination which works globally with t on R, a domination with local t should be enough.
Answer: Define $F:(0,\infty)\rightarrow\mathbb{R}$ by $F(t)=\int_{0}^{\infty}e^{-tx}\frac{\sin x}{x}\,dx$.
Let $t_{0}\in(0,\infty)$ be arbitrary. We go to show that the derivative
$F'(t_{0})=\int_{0}^{\infty}-e^{-t_{0}x}\sin x\,dx$ . Let $(t_{n})$
be an arbitrary sequence in $(0,\infty)$ such that $t_{n}\neq t_{0}$
and $t_{n}\rightarrow t_{0}$. By Heine's Theorem, to show that $\lim_{t\rightarrow t_{0}}\frac{F(t)-F(t_{0})}{t-t}=\int_{0}^{\infty}-e^{-t_{0}x}\sin x\,dx$,
it suffices that $\lim_{n\rightarrow\infty}\frac{F(t_{n})-F(t_{0})}{t_{n}-t_{0}}=\int_{0}^{\infty}-e^{-t_{0}x}\sin x\,dx$.
Since $t_{n}\rightarrow t_{0}>0$ and $t_{n}>0$ for all $n$, there
exists $t'$ such that $0<t'<t_{n}$ for all $n=0,1,2,\ldots$. (For, choose $\delta>0$
such that $t_{0}-\delta>0$. Then there exists $N$ such that $t_{n}\in(t_{0}-\delta,t_{0}+\delta)\setminus\{t_{0}\}$
whenever $n\geq N$. Take $t'=\frac{1}{2}\min\left(t_{1},t_{2},\ldots,t_{N-1},t_{0}-\delta\right)>0$).
For each $n$, define $\theta_{n}:[0,\infty)\rightarrow\mathbb{R}$
by $\theta_{n}(x)=\frac{e^{-t_{n}x}-e^{-t_{0}x}}{t_{n}-t_{0}}\cdot\frac{\sin x}{x}$.
Define $\theta:[0,\infty)\rightarrow\mathbb{R}$ by $\theta(x)=e^{-t'x}$.
For each $x\in[0,\infty)$, by Mean-Value Theorem, there exists $\xi_{x,n}$
strictly between $t_{0}$ and $t_{n}$ such that
\begin{eqnarray*}
 &  & e^{-t_{n}x}-e^{-t_{0}x}\\
 & = & -(t_{n}x-t_{0}x)e^{-\xi_{x,n}x}.
\end{eqnarray*}
Hence, $\left|\theta_{n}(x)\right|\leq|e^{-\xi_{x,n}x}\sin x|\leq\theta(x)$
because $0<t'\leq\xi_{x,n}$ $\Rightarrow e^{-t'x}\geq e^{-\xi_{x,n}x}$.
Moreover, by direct calculation, $\lim_{n\rightarrow\infty}\theta_{n}(x)=-e^{t_{0}x}\sin x$.
Note that $\theta$ is integrable, so by Lebesgue Dominated Convergence
Theorem, we have that
\begin{eqnarray*}
 &  & \lim_{n\rightarrow\infty}\frac{F(t_{n})-F(t_{0})}{t_{n}-t_{0}}\\
 & = & \lim_{n\rightarrow\infty}\int_{0}^{\infty}\theta_{n}(x)dx\\
 & = & \int_{0}^{\infty}\lim_{n\rightarrow\infty}\theta_{n}(x)dx\\
 & = & \int_{0}^{\infty}-e^{-t_{0}x}\sin x\,dx.
\end{eqnarray*}
We conclude that $F'(t_{0})=\int_{0}^{\infty}-e^{-t_{0}x}\sin x\,dx$.
Answer: You can also follow an elementary approach here based on a well-known theorem for interchanging the derivative and limit of a sequence of differentiable functions. Theorem 7.17 in Principles of Mathematical Analysis by Rudin is

Suppose $(F_n)$ is a sequence of functions, differentiable on $[a,b]$
and such that $(F_n(t_0))$ converges for some point $t_0 \in [a,b]$.
If $(F_n')$ converges uniformly on $[a,b]$, then $(F_n)$ converges
uniformly on $[a,b]$ to a function $F$, and for all $t \in [a,b]$ we
have $F'(t) = \lim_{n \to \infty}F_n'(t)$.

In this case, we have
$$F_n(t) := \int_{0}^{n} e^{-tx}\frac{\sin x}{x} dx, \quad F'_n(t) = -\int_{0}^{n} e^{-tx}\sin x dx$$
Consider any point $t_0 \in [a,b] \subset (0,\infty)$. The improper integral is convergent (by the Dirichlet test) and
$$\lim_{n \to \infty}F_n(t_0) = \int_{0}^{\infty} e^{-t_0x}\frac{\sin x}{x} dx$$
Since
$| e^{-tx} \sin x| \leqslant e^{-ax}$ for all $t \in [a,b]$ and $\int_0^\infty e^{-ax} \, dx = \frac{1}{a} < \infty$, it follows by the Weierstrass M-test that $(F_n')$ is uniformly convergent on the interval and applying the theorem we get for all $t \in [a,b]$
$$F'(t) = \lim_{n \to \infty} F_n'(t) = -\int_0^\infty e^{-tx} \sin x \, dx$$
This holds for every $t \in (0,\infty)$ since the choice of $t_0$ and the interval $[a,b]$ was arbitrary.
Answer: There is a low-tech solution that is instructive because it uses a method that can cope with amplitudes of slow decay. Exploit the fact that  the humps in the sinc function decay steadily and reverse sign with every multiple of $\pi$.
Let $I_n(t)= \int_0^{n \pi} e^{- t x} \frac{ \sin x}{x} dx$ and let $I_{\infty}(t)$ denote the function you wish to show is differentiable.
Regard the integral $I_n$ as the sum of $n$ separate integrals, taken over consecutive intervals of length $\pi$ (the separate humps).
You can use the Leibniz alternating series test to  show  that when $n$ is even,
(i) $ I_{n} (t)\leq I_{\infty}(t)  \leq I_{n+1}(t)$   and
(ii)  the spread between these two endpoints tends to zero as $n\to \infty$.
Consider next $ I'_n(t)=\int_0^{n \pi} -e^{- t x} \sin x dx$ whose integrand also has alternating humps with steadily decreasing mass (because of the exponential decay factor).
By similar reasoning the spread between the derivatives $I'_{n+1}(t)  -I'_n(t)$ tends to zero as $n\to \infty$.
Then use a standard result in  analysis  to show that these Cauchy estimates   are sufficient to justify interchanging limit and derivative.
Answer: The key tool here is the following result which is a consequence of
the dominated convergence theorem of Lebesgue. Let $\varphi:X\times(a,b)\rightarrow\mathbb{R}$
($b$ could be $+\infty$) be such that

the function $x\mapsto\varphi(x,t)$ is a Borel function for every
$t$,

the function $t\mapsto\varphi(x,t)$ is a differentiable in $(a,b)$
for every $x\in X$,

$\frac{\partial\varphi}{\partial t}(x,t)$ is dominated on $X\times(a,b)$
by an integrable function $\psi(x)$,

then $F(t):=\int_{X}\varphi(x,t)\,dx$ with $t\in(a,b)$, is differentiable
for every $t\in(a,b)$ and we have
$$
\frac{dF}{dt}(t)=\int_{X}\frac{\partial\varphi}{\partial t}(x,t)\,dx.
$$
In the considered case we have
$$
\varphi:\underbrace{\left[0,+\infty\right)}_{X}\times\underbrace{\left(0,\infty\right)}_{(a,b)}\longrightarrow\mathbb{R},\qquad\varphi(x,t)=\frac{\sin x}{x}e^{-tx}.
$$
To show that $F$ is differentiable over $\mathbb{R}_{*}^{+}$ we
need to reason as follows. Let $t_{0}\in\mathbb{R}_{*}^{+}$, then
\begin{equation}\label{eq:1}
\left|\frac{\partial}{\partial t}\frac{\sin x}{x}e^{-tx}\right|=\left|\sin xe^{-tx}\right|\leqslant e^{-t_{0}x}\qquad\forall(x,t)\in\left[0,+\infty\right)\times\left[t_{0},+\infty\right).\qquad(1)
\end{equation}
This means that $F$ is differentiable on every interval $\left[t_{0},+\infty\right)$
for every $t_{0}\in\left(0,+\infty\right)$, i.e. it is differentiable
over $\left(0,+\infty\right)$.
N.B. we can not consider directly in (1) $\left(0,+\infty\right)$
because in this case we can not get a dominating function which is
integrable over $\left[0,+\infty\right)$ (indeed, for every $x\in\left[0,+\infty\right),$
$\sup_{t\in\left(0,+\infty\right)}\left|\sin xe^{-tx}\right|=\left|\sin x\right|$).
\medskip
Another possible way to establish the asked differentiability property is related to the fact that the considered integral can be interpret as the Laplace transform of the function $\frac{\sin x}{x}$, i.e., setting $f(x)=\frac{\sin x}{x}$,
$$
F(t)=\mathcal{L}[f(\cdot)](t):=\int_0^{+\infty} \frac{\sin x}{x}e^{-tx}\,dx.
$$ There is a general result guaranteeing that $F$ is differentiable for every $t\in\mathbb{R}^+_*$. It suffices for example that there exists a $n\in\mathbb{N}_*$ such that $\lim_{x\rightarrow+\infty}\frac{f(x)}{x^n}=0$. This requirement guarantees that we can differentiate under the sign of integral. Indeed it is know that (a consequence of the dominated Lebesgue theorem) if $\varphi:X\times(a,b)\rightarrow\mathbb{R}$.
Answer: @Danny has shown a solution which evaluates the derivative of $F(t)$ via its definition. Another approach is to uses directly the differentiability under domination, it is suggested by Sorfosh via a very similar answer.
The idea is that the differentiability is a local property, to prove that $F(t)$ is differentiable at a point $t_0$ it's enough to consider a neighbourhood $]t_0 - \epsilon, t_0+\epsilon[ \subset ]0,+\infty[$. In that interval:
$$
\lvert (e^{-tx} \frac{\sin x}{x})' \rvert = e^{-tx} \lvert \sin x \rvert \leq e^{-(t_0 - \epsilon)x}
$$
Moreover
$$
\int_0^{+\infty} e^{-(t_0 - \epsilon)x} dx = \frac{1}{t_0-\epsilon} < +\infty
$$
then we can apply the theorem of convergence under domination.


Performance Benchmarking of Contains, Exists and Any

Question: I have been searching for a performance benchmarking between Contains, Exists and Any methods available in the List<T>. I wanted to find this out just out of curiosity as I was always confused among these. Many questions on SO described definitions of these methods such as:

LINQ Ring: Any() vs Contains() for Huge Collections
Linq .Any VS .Exists - Whats the difference?
LINQ extension methods - Any() vs. Where() vs. Exists()

So I decided to do it myself. I am adding it as an answer. Any more insight on the results is most welcomed. I also did this benchmarking for arrays to see the results
Answer: The fastest way is to use a HashSet.
The Contains for a HashSet is O(1).
I took your code and added a benchmark for HashSet<int>
The performance cost of HashSet<int> set = new HashSet<int>(list); is nearly zero.
Code
void Main()
{
    ContainsExistsAnyVeryShort();

    ContainsExistsAnyShort();

    ContainsExistsAny();
}

private static void ContainsExistsAny()
{
    Console.WriteLine("***************************************");
    Console.WriteLine("********* ContainsExistsAny ***********");
    Console.WriteLine("***************************************");

    List<int> list = new List<int>(6000000);
    Random random = new Random();
    for (int i = 0; i < 6000000; i++)
    {
        list.Add(random.Next(6000000));
    }
    int[] arr = list.ToArray();
    HashSet<int> set = new HashSet<int>(list);

    find(list, arr, set, (method, stopwatch) => $"{method}: {stopwatch.ElapsedMilliseconds}ms");

}

private static void ContainsExistsAnyShort()
{
    Console.WriteLine("***************************************");
    Console.WriteLine("***** ContainsExistsAnyShortRange *****");
    Console.WriteLine("***************************************");

    List<int> list = new List<int>(2000);
    Random random = new Random();
    for (int i = 0; i < 2000; i++)
    {
        list.Add(random.Next(6000000));
    }
    int[] arr = list.ToArray();
    HashSet<int> set = new HashSet<int>(list);

    find(list, arr, set, (method, stopwatch) => $"{method}: {stopwatch.ElapsedMilliseconds}ms");

}

private static void ContainsExistsAnyVeryShort()
{
    Console.WriteLine("*******************************************");
    Console.WriteLine("***** ContainsExistsAnyVeryShortRange *****");
    Console.WriteLine("*******************************************");

    List<int> list = new List<int>(10);
    Random random = new Random();
    for (int i = 0; i < 10; i++)
    {
        list.Add(random.Next(6000000));
    }
    int[] arr = list.ToArray();
    HashSet<int> set = new HashSet<int>(list);

    find(list, arr, set, (method, stopwatch) => $"{method}: {stopwatch.ElapsedTicks} ticks");

}

private static void find(List<int> list, int[] arr, HashSet<int> set, Func<string, Stopwatch, string> format)
{
    Random random = new Random();
    int[] find = new int[10000];
    for (int i = 0; i < 10000; i++)
    {
        find[i] = random.Next(6000000);
    }

    Stopwatch watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        list.Contains(find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("List/Contains", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        list.Exists(a => a == find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("List/Exists", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        list.Any(a => a == find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("List/Any", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        arr.Contains(find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("Array/Contains", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        Array.Exists(arr, a => a == find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("Array/Exists", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        Array.IndexOf(arr, find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("Array/IndexOf", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        arr.Any(a => a == find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("Array/Any", watch));

    watch = Stopwatch.StartNew();
    for (int rpt = 0; rpt < 10000; rpt++)
    {
        set.Contains(find[rpt]);
    }
    watch.Stop();
    Console.WriteLine(format("HashSet/Contains", watch));
}

RESULTS
*******************************************
***** ContainsExistsAnyVeryShortRange *****
*******************************************
List/Contains: 1067 ticks
List/Exists: 2884 ticks
List/Any: 10520 ticks
Array/Contains: 1880 ticks
Array/Exists: 5526 ticks
Array/IndexOf: 601 ticks
Array/Any: 13295 ticks
HashSet/Contains: 6629 ticks
***************************************
***** ContainsExistsAnyShortRange *****
***************************************
List/Contains: 4ms
List/Exists: 28ms
List/Any: 138ms
Array/Contains: 6ms
Array/Exists: 34ms
Array/IndexOf: 3ms
Array/Any: 96ms
HashSet/Contains: 0ms
***************************************
********* ContainsExistsAny ***********
***************************************
List/Contains: 11504ms
List/Exists: 57084ms
List/Any: 257659ms
Array/Contains: 11643ms
Array/Exists: 52477ms
Array/IndexOf: 11741ms
Array/Any: 194184ms
HashSet/Contains: 3ms

Edit (2021-08-25)
I added a comparison for very short collections (10 items) and also added Array.Contains and Array.IndexOf. You can see that Array.IndexOf is the fastest for such small ranges. That is, because as @lucky-brian said n is so small here, that a for-loop performs better than a somewhat complex search algorithm. However I still advice to use HashSet<T> whenever possible, as it better reflects the intend of only having unique values and the difference for small collections is below 1ms.
Comment: I was looking for exactly such a thing. I was like "Holy Molly" when I saw the performance on the HashSet/Contains. Definitely going to try that out in my environment of 1000 .. 5000 items.
Comment: Would have been nice to see the performance of a HashMap as well here.
Comment: "Arrays do not have Exists" ? `Array.Exists(` https://learn.microsoft.com/en-us/dotnet/api/system.array.exists?view=netframework-4.7.2
Comment: Just a quick point, having order O(1) doesn't necessarily mean that an algorithm is fast, it just means that its speed doesn't depend on the number of elements over which it is applied. It might still take a very long time to complete.
Comment: Do you know if the Any for a HashSet is aslo O(1)?
Comment: Any does not exist on `HashSet` but is an extension Method for `IEnumerable` and is O(1) without a predicate and O(n) with a predicate. Herse is the source: https://github.com/Microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs#L1288
Answer: According to documentation:
List.Exists (Object method)

Determines whether the List(T) contains elements that match the
conditions defined by the specified predicate.

IEnumerable.Any (Extension method)

Determines whether any element of a sequence satisfies a condition.

List.Contains (Object Method)

Determines whether an element is in the List.

Benchmarking:
CODE:
    static void Main(string[] args)
    {
        ContainsExistsAnyShort();

        ContainsExistsAny();
    }

    private static void ContainsExistsAny()
    {
        Console.WriteLine("***************************************");
        Console.WriteLine("********* ContainsExistsAny ***********");
        Console.WriteLine("***************************************");

        List<int> list = new List<int>(6000000);
        Random random = new Random();
        for (int i = 0; i < 6000000; i++)
        {
            list.Add(random.Next(6000000));
        }
        int[] arr = list.ToArray();

        find(list, arr);
    }

    private static void ContainsExistsAnyShort()
    {
        Console.WriteLine("***************************************");
        Console.WriteLine("***** ContainsExistsAnyShortRange *****");
        Console.WriteLine("***************************************");

        List<int> list = new List<int>(2000);
        Random random = new Random();
        for (int i = 0; i < 2000; i++)
        {
            list.Add(random.Next(6000000));
        }
        int[] arr = list.ToArray();

        find(list, arr);
    }

    private static void find(List<int> list, int[] arr)
    {
        Random random = new Random();
        int[] find = new int[10000];
        for (int i = 0; i < 10000; i++)
        {
            find[i] = random.Next(6000000);
        }

        Stopwatch watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 10000; rpt++)
        {
            list.Contains(find[rpt]);
        }
        watch.Stop();
        Console.WriteLine("List/Contains: {0:N0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 10000; rpt++)
        {
            list.Exists(a => a == find[rpt]);
        }
        watch.Stop();
        Console.WriteLine("List/Exists: {0:N0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 10000; rpt++)
        {
            list.Any(a => a == find[rpt]);
        }
        watch.Stop();
        Console.WriteLine("List/Any: {0:N0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 10000; rpt++)
        {
            arr.Contains(find[rpt]);
        }
        watch.Stop();
        Console.WriteLine("Array/Contains: {0:N0}ms", watch.ElapsedMilliseconds);

        Console.WriteLine("Arrays do not have Exists");

        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 10000; rpt++)
        {
            arr.Any(a => a == find[rpt]);
        }
        watch.Stop();
        Console.WriteLine("Array/Any: {0:N0}ms", watch.ElapsedMilliseconds);
    }

RESULTS
***************************************
***** ContainsExistsAnyShortRange *****
***************************************
List/Contains: 96ms
List/Exists: 146ms
List/Any: 381ms
Array/Contains: 34ms
Arrays do not have Exists
Array/Any: 410ms
***************************************
********* ContainsExistsAny ***********
***************************************
List/Contains: 257,996ms
List/Exists: 379,951ms
List/Any: 884,853ms
Array/Contains: 72,486ms
Arrays do not have Exists
Array/Any: 1,013,303ms

Comment: "Arrays do not have Exists" ? `Array.Exists(` https://learn.microsoft.com/en-us/dotnet/api/system.array.exists?view=netframework-4.7.2
Comment: What do you mean: "Arrays do not have Exists"? I think it has Exists(): https://stackoverflow.com/a/22928748/4608491
Comment: Just keep in mind that though Contains seem to be the fastest, LINQ 2 SQL has a limitation of ~2100 objects in the list, so it would be good for shorter lists.
Comment: @jyparask Even for the larger lists Contains seems good. However, I have updated the code and timings for the shorter list too. The result is as you predicted.
Comment: I ran your benchmark and I obtained that List.Exists was actually slightly faster than List.Contains, 45ms vs 55ms. The rest seemed consistent with your results. Tested on .NET 4.5 using Visual Studio 2013 in 32-bit in Release mode with optimizations.
Comment: It would have been interesting to compare these performances with traditional loop search (`for` or `foreach`).
Answer: It is worth mentioning that this comparison is a bit unfair, since the Array class doesn't own the Contains() method. It uses an extension method for IEnumerable<T> via a sequential Enumerator, hence it is not optimized for Array instances. On the other side, HashSet<T> has its own implementation fully optimized for all sizes.
To compare fairly you could use the static method int Array.IndexOf() which is implemented for Array instances, even though it uses a for loop slightly more efficient that an Enumerator.
Using a fair comparison algorithm, the performance for small sets of up to 5 elements of HashSet<T>.Contains() is similar to the Array.IndexOf() but it is much more efficient for larger sets.


Does this sum of two Euler products converge for $s=1$?

Question: The following sum of two Euler products is always real for real $s$:
$$A(s):=\prod_{p=prime} (1 - (i\,p)^{-s})^{-1}+\prod_{p=prime} (1 - (-i\,p)^{-s})^{-1}$$
ADDED:
Some (trivial) closed forms that I found so far:
$A(2) = \frac{4}{5}\zeta(2)$
$A(4) = 2\,\zeta(4)$
$A(6) = \dfrac{2\,\zeta(12)}{\zeta(6)}$
$A(8) = 2\,\zeta(8)$
$A(10) = \dfrac{2\,\zeta(20)}{\zeta(10)}$
$A(12) = 2\,\zeta(12)$
$A(14) = \dfrac{2\,\zeta(28)}{\zeta(14)}$
$A(16) = 2\,\zeta(16)$
$\cdots$
Numerical evidence suggests that this sum also converges at $s=1$ (edit: I used $\lim_{s\to 1^+}$), albeit slowly. Could this be proven/falsified ?
Comment: This seems like a pretty hard question to me. This is asking for something like the behavior or partial sums $\sum_{n \leq N} (-i)^{\Omega(n)}$, where $\Omega(n)$ is the number of prime divisors of $n$ with multiplicity. I guess you're really asking about $\sum_{n \leq N, \Omega(n) \equiv 0 \bmod 2} (-1)^{\Omega(n)/2}$. This is asking about the distribution of numbers of divisors (mod $4$). I would guess that it does converge, but this might not be currently provable (though this is a bit out of my typical area).
Comment: @Rivers McForge No, I was not referring to the Euler product of a Dirichlet series.
Comment: @davidlowryduda Thanks for your response. It seems pretty hard indeed. I have added some of the trivial closed forms at even integers, however have not found any for the odd integers yet.
Comment: As it is your question doesn't make sense, edit to make clear what **limit** you are considering.
Comment: @Agno Did you want $i$ to be raised to the power $s$ in the Euler products $$A(s):=\prod_{p=prime} \left(1 - \frac{i^{-s}}{p^s}\right)^{-1} + \prod_{p=prime} \left(1 -\frac{(-i)^{-s}}{p^s}\right)^{-1}?$$
Typically in an Euler product or Dirichlet series, the coefficients in the product or sum have no dependence on $s$. I'm wondering if this question was supposed to be about the superficially similar $$A^*(s):=\prod_{p=prime} \left(1 - \frac{i}{p^s} \right)^{-1} + \prod_{p=prime} \left(1 -\frac{(-i)}{p^s}\right)^{-1},$$ which would have the Dirichlet series David's comment was referencing.
Comment: Your "trivial" cases are represented by $$ A(2n) = 2 \: \zeta(2n)^{\cos(\pi n)} \zeta(4n)^{\sin^2(\frac{\pi n}{2} )} $$
Comment: @reuns Updated the question.
Answer: $$\lim_{x\to \infty} \quad\prod_{p\le x} \frac1{1 +i p^{-1}}+\prod_{p\le x} \frac1{1 -i p^{-1}}$$ diverges, this follows immediately from Mertens thoerem $$\sum_{p\le x} p^{-1}=\log \log x+M+o(1)$$ so that $$\sum_{p\le x} \log(1+ip^{-1})=i\log \log x+a+ib+o(1)$$
$$\prod_{p\le x} \frac1{1 +i p^{-1}}+\prod_{p\le x} \frac1{1 -i p^{-1}}=2 e^{-a} \cos(b+\log\log x)+o(1) $$
Then $$\lim_{s\to 1^+} \Re(\prod_p \frac1{1 -e^{-i\pi s/2}  p^{-s}})$$ diverges as well, this is because as $s\to 1^+$,
$$-\sum_p \log(1 -e^{i\pi s/2}  p^{-s})= C+o(1)+e^{-i\pi s/2} \log \zeta(s)= C+o(1)+i\log (s-1) $$
$$\Re(\prod_p \frac1{1 -e^{i\pi s/2}  p^{-s}})=e^{\Re(C)} \cos(\Im(C)+\log(s-1))+o(1)$$
Comment: Thanks reuns. Hope you don't mind that I have accepted Rivers' broader answer.
Answer: The boring/trivial answer is no
$A: \Bbb{R} \to \Bbb{C}$ doesn't converge at $x = 1$ in its original definition $$A(x):=\prod_{p \, \text{prime}} (1 - (i\,p)^{-x})^{-1}+\prod_{p \, \text{prime}} (1 - (-i\,p)^{-x})^{-1}$$ because the individual products $F(x) := \prod_{p \, \text{prime}} (1 - (i\,p)^{-x})^{-1}$ and $\overline{F(x)} := \prod_{p \, \text{prime}} (1 - (-i\,p)^{-x})^{-1}$ don't converge at $x = 1$. This can pretty easily be checked via taking logs: $$\log F(x) = \sum_{p \, \text{prime}} \sum_{n \geq 1} \frac{i^{nx}}{n p^{nx}} \sim \sum_{p \, \text{prime}} \frac{i}{p} + \mathcal{O}(1) \text{ as } x \to 1, $$ and we know $\sum_{p \, \text{prime}} \frac{i}{p}$ is divergent. Clearly the product $\overline{F(x)}$ converges at $x = 1$ iff $F(x)$ does.
The interesting answer is also no
Since we're on the real axis, $A(x) = F(x) + \overline{F(x)} = 2 \operatorname{Re}(F(x))$. Even though $F$ and $\overline{F}$ diverge as $x \to 1^+$, we might surmise that the divergence happens "mostly" in the imaginary part, and cancelling that out leaves a real part that converges. Indeed (and this will be relevant shortly), we can show that $\lim_{x \to 1^+} |F(x)| = \frac{\pi}{\sqrt{15}}$ despite the fact that $\lim_{x \to 1^+} F(x)$ DNE by an analogous method, because
\begin{align*}
|F(x)|^2 &= F(x) \overline{F(x)} \\
 &= \prod_{p \, \text{prime}} \left(1 - \frac{i^{-x}}{p^x}\right)^{-1} \left(1 - \frac{i^{x}}{p^x}\right)^{-1} \\
 &= \prod_{p \, \text{prime}} \left(1 - \frac{2 \cos( \pi x/2)}{p^x} + \frac{1}{p^{2x}}\right)^{-1} \\
 &\to \prod_{p \, \text{prime}} \left(1 + \frac{1}{p^{2}}\right)^{-1} =  \frac{\pi^2}{15} \text{ as } x \to 1^+. \
\end{align*}
The final step (demonstrating the stated convergence as $x \to 1^+$) requires us to argue that $$\lim_{x \to 1^+} \cos( \pi x/2) P(x) = 0,$$ where $P(x)$ is the prime zeta function. As $x \to 1^+$, $P(x) \sim \ln (x-1)$, while $\cos(\pi x/2) \sim -(x-1)$, and so we can replace these two complicated functions with their simpler asymptotic equivalents and use L'Hopital to demonstrate that this limit is, in fact, zero.
Why is this relevant?
We know that $\lim_{x \to 1^+} |F(x)| = \frac{\pi}{\sqrt{15}}$ despite the fact that $\lim_{x \to 1^+} F(x)$ does not exist.
The OP's question asks if $\lim_{x \to 1^+} A(x) = \lim_{x \to 1^+} 2 \operatorname{Re}(F(x))$ exists.
But if $\lim_{x \to 1^+} |F(x)|$ and $\lim_{x \to 1^+} \operatorname{Re}(F(x))$ both existed, then so would $\lim_{x \to 1^+} F(x)$. Therefore, since $\lim_{x \to 1^+} F(x)$ does not exist, neither does $\lim_{x \to 1^+} A(x)$.
Comment: Thanks for your comprehensive answer!
Comment: @Agno There are several problems in this answer. We need the $o(1)$ remainder, $O(1)$ is not enough. And I don't see how $\lim_{x \to 1^+} \cos( \pi x/2) P(x) $ is relevant.


R: How to make transformations on subset of a subset fast (optimize or alternative to `ddply`)?

Question: I have a somewhat large data set (784,932 rows/items, 27,492 unique IDs). For each Item in each ID, I am trying to create a dummy variable equal to 1, if the difference between the dates is less than 60 secs.
Stylised data and code:
ID <- c(1,1,1,1,1,1,3,3,3,3,3,3)
Item <- c(10,10,10,20,20,20,10,20,10,10,10,20)
Date <- c("19/11/13 18:58:00","19/11/13 18:58:21","19/11/13 20:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 19:58:00")
df <- data.frame(ID, Item, Date)
df <- df[order(ID, Date), ]
df[, "Date"] = lapply(df["Date"],function(x){strptime(x, "%d/%m/%y %H:%M:%S")})

# less than 60 sec difference = 1 (first item set to 999 -> 0)
fnDummy <- function(date) { ifelse(c(999, diff(date))<60, 1, 0) }

library(plyr)
ddply(df, .(ID, Item), transform, Dummy=fnDummy(Date) )

Output:
   ID Item                Date Dummy
1   1   10 2013-11-19 18:58:00     0
2   1   10 2013-11-19 18:58:21     1
3   1   10 2013-11-19 20:58:00     0
4   1   20 2013-11-19 18:58:00     0
5   1   20 2013-11-19 18:58:00     1
6   1   20 2013-11-19 18:58:00     1
7   3   10 2013-11-19 18:58:00     0
8   3   10 2013-11-19 18:58:00     1
9   3   10 2013-11-19 18:58:00     1
10  3   10 2013-11-19 18:58:00     1
11  3   20 2013-11-19 18:58:00     0
12  3   20 2013-11-19 19:58:00     1

From the output you see that the first and second row have common ID and Item, and the difference in Date is only 21 secs, so the dummy is 1. The second and third row also have common ID and Item, but here the difference in date is much larger than 60 secs, so dummy is 0.
I managed to get the output I wanted, but the operation is slow. For 1000 rows it takes about 40 sec (see system.time results below). This corresponding to approx. 180 minutes for the entire data set (my computer runs out of memory and crashes long before this).
   user  system elapsed
 36.485   3.328  39.800

How can I make this operation faster? Can i accomplish the same output using data.table, and is it faster?
Comment: Why do you use `ifelse`? `c(FALSE, diff(date) < 60)` should be sufficient. Use `as.integer` if you really need 0 and 1.
Comment: I realize you got your answer, but I'm a little baffled. The code in your question doesn't even run for me. I get an error on the `ddply` line.
Answer: You can use data.table as you suggest.  You'll have to convert your POSIXlt to POSIXct though:
library(data.table)
df$Date <- as.POSIXct(df$Date)
DT <- as.data.table(df)

DT[, dummy_date := fnDummy(Date), by=c('ID', 'Item')]

However, a big part of the slowdown is probably in the ifelse function and you don't really need it since you're creating a boolean:
as.integer(c(FALSE, diff(date) < 60))

Comment: tiny note: I'd use `as.data.table(.)` instead of `data.table(.)`. The former is much faster.
Comment: @Arun correct!  But when answering questions three extra characters is too many...
Comment: Thanks a lot. Now running the operation on the entire data set takes 14 sec. This is beautiful!
Comment: @bonna Glad to help.  For posterity, you might want to do a bit of code profiling.  `data.table` is much faster than `plyr`, but a big part of that speedup is coming from avoiding the `ifelse` also.
Answer: You could also use dplyr to solve this problem:
ID <- c(1,1,1,1,1,1,3,3,3,3,3,3)
Item <- c(10,10,10,20,20,20,10,20,10,10,10,20)
Date <- c("19/11/13 18:58:00","19/11/13 18:58:21","19/11/13 20:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 18:58:00","19/11/13 19:58:00")
df <- data.frame(ID, Item, Date = as.POSIXct(Date))

library(dplyr)

df %.%
  group_by(ID, Item) %.%
  mutate(
    lagged = lag(Date, order_by = Date, default = 999),
    dummy = Date - lagged < 60
  )

lag() effectively generalises diff() allowing you to specify an ordering value and a default for the first element.  (It also currently loses the attributes of the vector but that will be fixed in a future version. Track progress at https://github.com/hadley/dplyr/issues/166)


Is it possible to nudge a div that is in the masterpage on load?

Question: I need to have a page take a div that is in the masterpage and move it over like 300px to the right. Is this possible, and how? I figure it would be javascript or jquery. TIA
Comment: Or via a CSS override? In your page you could add inline CSS to the head (assuming you have a Section in the head to do so). The same would apply using jQuery/Javascript but you could put that anywhere on the page.
Comment: Which is your main concern? That you don't know how to move a div or that the div is in the master and not the page?
Answer: Assuming you can get the div (with something like document.getElementById() or getElementsByTagName() or even document.querySelector()), then:
var elem = // some code to get the right div here
elem.style.position = "relative;
elem.style.left = "300px";

This will move the element 300 pixels to the right of its original position, however it won't work too well if the element already has a position other than static.
Answer: In jQuery you can animate the div to move rather easily:
$(document).ready(function () {
    var current_left = $("#myDiv").css('left');
    $("#myDiv").animate({
        "margin-left": "300px", // if #myDiv's position is relative
        "left": current_left + 300 + "px" // if #myDiv's position is absolute|fixed
    }, 400);
});

EDIT: The absolute was assuming to are using LEFT instead of RIGHT. The right would be:
"right": current_left - 300 + "px"


Div inside a canvas

Question: i have a div element containing an interactive chart. Now i want to place it inside a canvas (using context or something) is it possible to do that? if yes, then what will be the solution?
Comment: possible duplicate of [Placing a  within a ](http://stackoverflow.com/questions/5763911/placing-a-div-within-a-canvas)
Comment: You can't place a div inside canvas. You may take a look at EasalJs http://www.createjs.com/#!/EaselJS
Comment: A canvas element can only paint pixels, not html elements.  Is there a way for you to convert that chart into an image?  If so you can easily put the chart image on the canvas using context.drawImage.
Answer: You can't put a div inside a canvas and have it be displayed. It will only be displayed if the browser doesn't recognize the canvas element. There are ways, however, to position the div over the canvas so that the canvas acts as a sort of background to the content.
Comment: This is the way to achieve what you want.

Div inside a canvas


Custom REST Resource POST problem

Question: I want to POST json data to a custom REST resource. I tested with postman and Insomnia but i get the message as if would've done a GET request and returns the get functions result. The GET function works fine btw.
In the logs it says "Switched from post to get".
I just want to return the data the user passes. This is the code of my custom REST resource:
<?php
namespace Drupal\foolzz_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides User Profile REST Resource
 *
 * @RestResource(
 *   id = "profile_resource",
 *   label = @Translation("Profile resource"),
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}"
 *   }
 * )
 */
class ProfileResource extends ResourceBase
{
    /**
     * Responds to entity GET requests.
     * @return \Drupal\rest\ResourceResponse
     */
    public function get($uid = NULL)
    {
        $query = \Drupal::database()->select('foolzz_users_profile', 'data');
        $query->fields('data', array('fk_users_uid','status','displayname','birthdate','biography','gender','realname'));
        $query->condition('data.fk_users_uid', $uid);

        $profile = $query->execute()->fetchAssoc();

        $response = ['profile' => $profile
        ];

        $build = array(
            '#cache' => array(
                'max-age' => 0,
            ),
        );

        return (new ResourceResponse($response))->addCacheableDependency($build);
    }

    /**
     * Responds to POST requests.
     * @return \Drupal\rest\ResourceResponse
     * Returns a list of bundles for specified entity.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post(array $data = []) {

        $response = array(
            "data" => $data,
        );

        $build = array(
            '#cache' => array(
                'max-age' => 0,
            ),
        );

        return (new ResourceResponse($response))->addCacheableDependency($build);
    }
}

Answer: Looks like you've stumbled across the same stumbling block as I have a couple of times. Try with this piece of code - note the create entry after canonical:
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}",
 *     "https://www.drupal.org/link-relations/create" = "/foolzz_rest_api/profile/{uid}"
 *   }
 * )

Read more at:
https://www.drupal.org/node/2811757
and
https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview
Oh and for the post request, I'd use ModifiedResourceResponse instead of fiddling with cache headers by hand (I learned about the existence of that from Drupal Core's EntityResource)
Comment: Thank you for your answer. I use this second line of uri_paths by myself in an extra rest resource which I'm only using to post data, because when I have these 2 lines in my resource with `GET` and `POST` then i receive this error : `{
  "message": "No route found for \"POST /foolzz_rest_api/profile/1\": Method Not Allowed (Allow: GET, HEAD)"
}`
Comment: Hi! Have you remembered to enable POST for your endpoint at `/admin/config/services/rest` (if you use the Rest UI module)?
Comment: Sure. Post is enabled.
Comment: Right, so you have 1. the two urls defined AND 2. post allowed for that rest endpoint AND 3. you have granted permission for the role in question to post to this endpoint? Hmmmm scratching my head here.
Answer: I believe the syntax for your uri_paths annotation should be:
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}"
 *     "https://www.drupal.org/link-relations/create" = "/foolzz_rest_api/profile"
 *   }

The {uid} is not needed on the second line as it is present in the canonical path.
Comment: Dont forget to add comma after route definition `"canonical" = "/foolzz_rest_api/profile/{uid}",`, if you skip then you will get `Fixing an error: Expected Doctrine\Common\Annotations\DocLexer::T_CLOSE_CURLY_BRACES `

Custom REST Resource POST problem