How to Prove : $\frac{2}{(n+2)!}\sum_{k=0}^n(-1)^k\binom{n}{k}(n-k)^{n+2}=\frac{n(3n+1)}{12}$

Question: While I calculate an integral
$$
\int\limits_{[0,1]^n}\cdots\int(x_1+\cdots+x_n)^2\mathrm dx_1\cdots\mathrm dx_n
$$
I used two different methods and got two answers. I am sure it's equivalent, but how can I prove it?
$$\displaystyle\dfrac{2}{(n+2)!}\sum_{k=0}^n(-1)^k\binom{n}{k}(n-k)^{n+2}=\dfrac{n(3n+1)}{12}$$
Sincerely thanks!
Comment: Curious about how to work out the $LHS$ .
Comment: By the way, it is surprising that you get this complicated term while calculating that simple integral.
Comment: @SangchulLee I just...just guess it, and  verify the equality via mathematica.
Comment: That is amazing! I knew that the sum has some nice expression, but have never known that it is given with such a simple look. Oh, and also (+1).
Answer: Here's a fairly straightforward combinatorial argument. Rewrite the equation as
$$\sum_{k=0}^n(-1)^k\binom{n}{k}(n-k)^{n+2}=\frac{n(3n+1)(n+2)!}{24}\;.\tag{1}$$
The lefthand side of $(1)$ is an inclusion-exclusion calculation of the number of surjections from $[n+2]$ to $[n]$ (where as usual $[m]=\{1,\ldots,m\}$ for each $m\in\Bbb Z^+$). We now count these surjections in a different way.
If $f:[n+2]\to[n]$ is a surjection, either there is a $k\in[n]$ such that $|f^{-1}[\{k\}]|=3$, or there are distinct $k,\ell\in[n]$ such that $|f^{-1}[\{k\}]|=|f^{-1}[\{\ell\}]|=2$; call these surjections Type $1$ and Type $2$, respectively.
To construct a Type $1$ surjection we first choose $k$ in $n$ ways, then choose $f^{-1}[\{k\}]$ in $\binom{n+2}3$ ways, and then define $f$ on $[n+2]\setminus f^{-1}[\{k\}]$ in $(n-1)!$ ways, for a total of
$$n(n-1)!\binom{n+2}3=\frac{n(n+2)!}{3!}$$
Type $1$ surjections.
To construct a Type $2$ surjection we first choose $k$ and $\ell$ in $\binom{n}2$ ways, then choose the preimage of the smaller of $k$ and $\ell$ in $\binom{n+2}2$ ways, then choose the preimage of the larger of $k$ and $\ell$ in $\binom{n}2$ ways, and finally define the rest of $f$ in $(n-2)!$ ways, for a total of
$$\binom{n}2^2\binom{n+2}2(n-2)!=\frac{n(n-1)(n+2)!}8$$
Type $2$ surjections.
The total number of surjections is therefore
$$\frac{n(n+2)!}6+\frac{n(n-1)(n+2)!}8=\frac{n(3n+1)(n+2)!}{24}\;,$$
as desired.
Comment: (+1), Thanks for contributing to the remarkable diversity on this page. Interesting to observe that your types of surjections correspond precisely to the two types of coefficients from the integral I presented.
Comment: @Marko: My pleasure; it's good to have some variety, I think. I suspect that the correspondence is no accident, but I don't understand the relevant complex analysis well enough to see just what the connection is.
Comment: The connection can be seen by inspection, namely that the integral is equal to $$n!\times {n+2\brace n}$$ and the sets in these set partitions are precisely the pre-images of the $n$ possible slots in your surjections.
Answer: Fix $n$ and define $f(x)$ by
$$ f(x) = (1 - e^{-x})^n = \sum_{k=0}^{n} \binom{n}{k} (-1)^k e^{-kx}. $$
Then the left-hand side is equal to
$$ \frac{2}{(n+2)!} f^{(n+2)}(0). $$
So it suffices to find the Taylor polynomial of degree $n+2$ for $f(x)$ at $x = 0$. This can be done as follows:
\begin{align*}
f(x)
&= x^n \left( \frac{1 - e^{-x}}{x} \right)^n \\
&= x^n \exp\left[ n \log\left( \frac{1 - e^{-x}}{x} \right)\right] \\
&= x^n \exp\left( -\frac{n}{2} x + \frac{n}{24} x^2 + \cdots \right) \\
&= x^n \left( 1 - \frac{n}{2} x + \frac{(3n+1)n}{24} x^2 + \cdots \right) \\
&= x^n - \frac{n}{2} x^{n+1} + \frac{(3n+1)n}{24} x^{n+2} + \cdots.
\end{align*}
Therefore we have
$$ \frac{2}{(n+2)!} f^{(n+2)}(0) = \frac{2}{(n+2)!} \cdot \frac{(3n+1)n}{24} (n+2)! = \frac{(3n+1)n}{12}. $$
Answer: Suppose we  seek to evaluate
$$\sum_{k=0}^n (-1)^k {n\choose k} (n-k)^{n+2}.$$
We introduce
$$(n-k)^{n+2} =
\frac{(n+2)!}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{n+3}} \exp((n-k)z) \; dz.$$
This yields for the sum
$$\frac{(n+2)!}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{n+3}} \exp(nz)
\sum_{k=0}^n (-1)^k {n\choose k} \exp(-kz) \; dz
\\ = \frac{(n+2)!}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{n+3}} \exp(nz)
(1-\exp(-z))^n \; dz
\\ = \frac{(n+2)!}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{n+3}}
(\exp(z)-1)^n \; dz.$$
This is
$$(n+2)! [z^{n+2}] (\exp(z)-1)^n.$$
Observe that $\exp(z)-1$ starts with $z + \frac{1}{2} z^2 + \frac{1}{6} z^3 +\cdots.$
There  are two possibilities here depending on which term from the series expansion is included in the product of the $n$ terms, the  first is  a single  term with $z^3$ and the rest being $z$ which yields
$${n\choose 1} 1^{n-1} \frac{1}{6} = \frac{1}{6} n.$$
The other possibility is two terms in $z^2$ with the rest being $z$
which yields
$${n\choose 2} 1^{n-2} \frac{1}{2^2} = \frac{1}{8} n (n-1).$$
Adding these we obtain
$$\frac{n(3n+1)}{24}$$
for a final answer of
$$(n+2)! \frac{n(3n+1)}{24}.$$
Answer: Note: This is more a hint than a complete answer providing just some additional information.

If we exchange the order of summation $k \rightarrow  n-k$ in the LHS of OP's identity we obtain
\begin{align*}
\frac{2}{(n+2)!}\sum_{k=0}^n(-1)^{n-k}\binom{n}{k}k^{n+2}
\end{align*}

Note that the Stirling Numbers of the second kind $\begin{Bmatrix}m\\n\end{Bmatrix}$ are defined as
\begin{align*}
\begin{Bmatrix}m\\n\end{Bmatrix}=\frac{1}{n!}\sum_{k=0}^n(-1)^{n-k}\binom{n}{k}k^{m}
\end{align*}

Setting $m=n+2$ we can write OP's expression as
  \begin{align*}
\frac{2}{(n+2)!}\sum_{k=0}^n(-1)^{n-k}\binom{n}{k}k^{n+2}=\frac{2}{(n+1)(n+2)}\tag{1}
\begin{Bmatrix}n+2\\n\end{Bmatrix}
\end{align*}
So, we essentially have to calculate the Stirling number of the second kind $\begin{Bmatrix}n+2\\n\end{Bmatrix}$ in order to prove OP's claim.

These numbers fulfil a lot of nice relations and we could try to prove the claim e.g. using the recurrence relation
\begin{align*}
\begin{Bmatrix}m\\n\end{Bmatrix}=n\begin{Bmatrix}m-1\\n\end{Bmatrix}+\begin{Bmatrix}m-1\\n-1\end{Bmatrix}\tag{2}
\end{align*}
Since $\begin{Bmatrix}m\\n\end{Bmatrix}$ denotes the number of partitioning a set of $m$ elements into $n$ non-empty blocks, the recurrence relation tells us that we can select the $m$-th element and put it into a block by its own or we have $n$ possibilities to put it into one of $n$ already existing blocks.
But this is a little bit cumbersome and we have already answers with nice solutions. So, one additional remark instead. There are different generalisations of the Stirling Numbers of the second kind and one of them are the so-called r-associated Stirling numbers of the second kind, which are denoted as $$\begin{Bmatrix}m\\n\end{Bmatrix}_r$$
They give the number of $n$ different blocks of $m$ elements, each containing at least $r$ elements.

We find in Comtet's classic Advanced Combinatorics in the chapter about Stirling Numbers following relationship of $2$-associated Stirling numbers of the second kind with the Stirling numbers of the second kind
  \begin{align*}
\begin{Bmatrix}n+a\\n\end{Bmatrix}=\sum_{k=a+1}^{2a}\binom{n+a}{k}\begin{Bmatrix}k\\k-a\end{Bmatrix}_2
\end{align*}
  Using this relationship together with given table values in this chapter, we can write OP's expression as
  \begin{align*}
\frac{2}{(n+1)(n+2)}&\begin{Bmatrix}n+2\\n\end{Bmatrix}\\
&=\frac{2}{(n+1)(n+2)}\left[\binom{n+2}{3}\begin{Bmatrix}3\\1\end{Bmatrix}_2
+\binom{n+2}{4}\begin{Bmatrix}4\\2\end{Bmatrix}_2\right]\\
&=\frac{2}{(n+1)(n+2)}\left[\binom{n+2}{3}
+3\binom{n+2}{4}\right]\\
&=\frac{n(3n+1)}{12}
\end{align*}
  and the claim follows.
Comment: E@MarkoRiedel: Thanks, Marko ... and yes, I am aware of it. In fact, I think that with respect to your approach you could *hardly avoid* to use the GF of the Stirling Numbers. :-) Nevertheless I think that explicitly pointing to the Stirling numbers could help OP to get useful associations. (+1)
Comment: Interesting work. (+1). Let me point out that I have those ordinary Stirling numbers in the last integral that I obtained, using the bivariate GF $G(z, u) = \exp(u(\exp(z)-1)).$


F1 Score is giving good value in imbalanced dataset

Question: If I have an imbalanced dataset that consists of 90% positive points and 10% negative points. Now I created a "dumb" model which always predicts every point as a positive point. The confusion matrix of this problem will be -

Now the Precision of the above confusion matrix will be -
Precision = No. of true positive out of the number of points predicted positive by the model.
So, Precision = TP / (TP + FP) = 90 / (90 + 10) = 0.9
And Recall will be -
Recall = No. of true positive out of the number of points that are actually positive.
So, Recall = TP / (TP + FN) = 90 / (90 + 0) = 1.0
As we can see both precision and recall are high and F1score of this model is,
F1-Score = PR / P + R * 2 = 0.94
This is a high score, so according to this, the model is very good. How can the f1 score give good results on an imbalanced dataset?
Answer: In a situation like this, it probably makes more sense to treat your minority class as your positive class. That way your precision number (and f1 score) is more meaningful.


Extra fields in 'manage display' for content types

Question: On my old website, there were extra fields such as 'Author', 'Last modified', 'Tags', 'Post date', 'Read more', 'User picture', and 'Comments' available in the 'manage display' section of content types.
I'd like to have these fields on my new website too, but I really can't remember anymore how they got there. Does anyone perhaps know if they were provided by a certain module?
Answer: When using Display Suite, you have to first save the layout you're going to use, then the fields will appear.
Under the "Current Template" section, "None" is probably selected. For a default display, select the "One Column layout" and click save. These fields should then populate.
Comment: Indeed, the fields appeared after I changed the layout to 'One Column' and saved. Thanks for your help!
Answer: Display Suit provides those extra fields.
Comment: I already thought so, but I wasn't sure. Are they activated automatically when Display Suit is installed? They don't want to appear...


Json file with bash

Question: I need delete space and value kubernetes from json file with use bash script:
Content json file
Input
 "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },

Ouput
 "spec": {
        "finalizers": []
    },

Comment: It's generally recommended to use a JSON parsing tool for JSON data. Can you use [tag:jq]?
Answer: Given "input.json"
{
  "spec": {
          "finalizers": [
              "kubernetes"
          ]
      },
  "other": 42
  }

Then
jq '.spec.finalizers = []' input.json

outputs
{
  "spec": {
    "finalizers": []
  },
  "other": 42
}

Comment: Thank you very much Gleen! It worked
Answer: Lets use some sed magic with regex:
echo 'Input "spec": { "finalizers": [ "kubernetes" ] },' | sed -r 's/Input (.* \[) \".*\" (\].*)/\1\2/'

Which returns:
"spec": { "finalizers": [] },

sed -r uses extended regex (-E on osx), and "()" are used for capture groups, which is what the \1 and \2 refers to, so first we capture everything up to "[", then match everything from the "]" until the end.
The downside of this is that your input doesn't look like complete json, so modifying the regex to match the proper input can be much harder.
I would also recommend you to look at jq, the defacto tool for json parsing in CLI.
Comment: Thank Fredrik for you help.

Json file with bash


What is the value of: $\lim_{n\rightarrow \infty}\sum_{r=1}^{n-1}\frac{\cot^2(r\pi/n)}{n^2}$

Question:
$$\lim_{n\rightarrow \infty}\sum_{r=1}^{n-1}\frac{\cot^2(r\pi/n)}{n^2}$$

How can I calculate the value of this trigonometric function where limits tends to infinity?  I have thought and tried various of methods like using:

Tan(x)/x property
Converting lim to
Integration
Sandwich theorem
Trigonometric series

But none worked out for me.
So please tell me a good and easy approach for this question :)
Comment: Some useful hints [here](https://math.stackexchange.com/questions/2615072/computing-a-2-sum-k-1n-frac1z-k-12-and-sum-k-1n-cot2-left/) and [here](https://math.stackexchange.com/questions/3065615/prove-sum-k-1m-cot2-k-pi-2m1-m2m-1-3/)... and it looks like the limit is $\frac{1}{3}$
Comment: But where exactly are you stuck had you really tried any of these methods? It's way too easy to simply name a few standard methods.
Comment: I m stuck because I cannot use the summation of (1/r^2) which equals to π^2/6 because this is from my exam and therefore I need another approach
Answer: By applying Vieta's formulas to Chebyshev polynomials of the second kind we have
$$ \sum_{r=1}^{n-1}\cot^2\left(\frac{\pi r}{n}\right)=\frac{(n-1)(n-2)}{3} $$
(compare Cauchy's proof of $\zeta(2)=\frac{\pi^2}{6}$ in his Cours d'Analyse) hence the wanted limit is clearly $\frac{1}{3}$.
Comment: It's quite short your answer. We were expecting a little more details.
Comment: @FelixMarin: details can be found in [my notes](https://drive.google.com/file/d/0BxKdOVsjsuEwdjBEM1dpRkhMa2s/view). After a few years on MSE, I am growing tired/lazy about re-writing the exact same things over and over.
Comment: Fine. I'll see your notes. Happy New Year 2019. Thanks.
Answer: It would be naïve and incorrect to proceed as follows
$$\begin{align}
\sum_{k=1}^{n-1}\frac{\cot^2(\pi k/n)}{n^2}&\underbrace{\approx}_{\text{WRONG!}} \frac1n\int_{1/n}^{1-1/n}\cot^2(\pi x)\,dx\\\\
&=\frac1n\left.\left(-x-\frac1\pi \cot(\pi x)\right)\right|_{1/n}^{1-1/n}\\\\
&=\frac2{n^2}-\frac1n +\frac2{n\pi}\cot(\pi/n)\\\\
&\to \frac2{\pi^2}
\end{align}$$

Instead, we use $\cot^2(x)=\csc^2(x)-1$ to write
$$\begin{align}
\sum_{k=1}^{n-1}\frac{\cot^2(\pi k/n)}{n^2}&=\frac1n-\frac1{n^2}+\sum_{k=1}^{n-1}\frac{1}{n^2\,\sin^2(\pi k/n)}\\\\
&=\frac1n-\frac1{n^2}+2\sum_{k=1}^{\lfloor n/2\rfloor-1}\frac{1}{n^2\,\sin^2(\pi k/n)}
\end{align}$$
Next, we note that for $\pi/2>x>0$, $\left(x-\frac16 x^3\right)^2\le \sin^2(x)\le x^2$.  Hence, we have
$$\begin{align}
\frac2{\pi^2}\sum_{k=1}^{\lfloor n/2\rfloor-1}\frac1{k^2} \le \frac2{n^2}\sum_{k=1}^{\lfloor n/2\rfloor-1}\frac{1}{n^2\,\sin^2(\pi k/n)}&\le \frac2{\pi^2}\sum_{k=1}^{\lfloor n/2\rfloor-1}\frac1{k^2\left(1-\frac16\frac{\pi^2k^2}{n^2}\right)^2}\\&=\frac2{\pi^2}\sum_{k=1}^{\lfloor n/2\rfloor-1}\frac1{k^2}+O\left(\frac1n\right)
\end{align}$$
whence letting $n\to \infty$ and applying the squeeze theorem yields the coveted limit
$$\lim_{n\to\infty}\sum_{k=1}^{n-1}\frac{\cot^2(k\pi/n)}{n^2}=\frac13$$
Comment: So, you have $$\frac{\cot^2(k\pi/n)}{n^2}=\frac{1}{n^2\tan^2(k\pi /n)}=\frac{1/(k\pi/n)^2}{n^2 \frac{\tan^2(k\pi/n)}{(k\pi/n)^2}}=\frac{1}{\pi^2k^2}\times \frac{1}{\frac{\tan^2(k\pi/n)}{(k\pi/n)^2}}$$Now what?  While $\tan(x)/x\to 1$ as $x\to 0$, there are many terms in the series such that $k\pi/n$ is not close to zero.  Keep in mind that $1\le k\le n-1$.
Comment: +1. Nice job.${}$
Comment: @FelixMarin Hi Felix!  Happy New Year.  And thank you.  Much appreciated.
Comment: Happy New Year, Mark Viola.
Comment: @MarkViola Then what is the mistake if I write cot(x) in terms of tan(x), use tan(x)/x property with basel problem where sum(1/k^2)= π^2/6 because that eventually results in with a wrong answer :1/6 though the answer is 1/3.What is my mistake here?
Comment: @ShubhamGawri I'd like to help, but I don't know what you mean by "write $\cot(x)$ in terms of $\tan(x)$" and "use the $\tan(x)/x$ property.  Do you mean $\cot(x)=1/\tan(x)$?  Or do you mean $\cot(x)=\tan(\pi/2-x)$?  Or do you mean something else?  And what is the $\tan(x)/x$ property that you referenced?
Comment: @MarkViola Ok sorry I meant to write cot(x) as 1/tan(x) and multiply divide {π^2/n^2,4π^2/n^2,9π^2/n^2.....so on} so as to evaluate limit using property tan(x)/x =1 when x tends to zero. I hope now it's clear.
Answer: Here I came up with a solution involving only elementary calculation, I hope it's appreciable...
(Sorry as it's in image form)


UITextField editing issue - iPhone SDK

Question: I am having an issue with my UITextFields in my iPhone app that I am hoping someone here may have seen before.
I have a few UITextField's on my screen, and when they are tapped and they keyboard appears they are covered.  To overcome this, I animated the view to move up with:
-(void)moveViewUpFromValue:(float)fromOldValue toNewValue:(float)toNewValue keep:(BOOL)keep {

    CABasicAnimation *theAnimation;
    theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    theAnimation.duration=0.25;
    theAnimation.repeatCount=1;
    if(keep) {
        [theAnimation setRemovedOnCompletion:NO];
        [theAnimation setFillMode:kCAFillModeForwards];
    }
    theAnimation.fromValue=[NSNumber numberWithFloat:fromOldValue];
    theAnimation.toValue=[NSNumber numberWithFloat:toNewValue];
    [self.view.layer addAnimation:theAnimation forKey:@"animateLayer"];

}

This, visually, works great, however, when I go to edit (hold the screen down to get the magnifying glass), it doesn't appear.  The interaction are is retained in the position before it moves.
Any ideas what could be going on here?
Many thanks,
Brett
Answer: This is an interesting way to animate such a thing, but not the most common one.
You're actually animating a transformation of a view - not the actual position of the view. Appearantly the magnifying glass doesn't obey the transformation (quite logical, for it would sheer, stretch and skew with the view otherwise).
So rather animate the position, i.e. self.view.frame or self.view.center (which boils down to the same thing). Furthermore I usually use [UIView beginAnimations...] etc but if your approach works, it's probably just as fine.
Comment: That was it. Thanks a bunch! After looking at it a bit more, I do agree that [UIView beginAnimations...] is probably the best way to do it.
Answer: You've made the view appear to be in a different place, but because you haven't actually changed its position it is still effectively in the old location for things like hit testing, etc.
I would start by animating your view's center instead of its transform.  This you can do with just a UIView animation instead of a CABasicAnimation.  Additionally, your view will actually end up at the correct position when the animation is complete so things should work as you expect.

UITextField editing issue - iPhone SDK


Bing Maps PushPin and Zoomin / Zoom out

Question: Question 1
I currently have my Bing Maps set up But I wish to add a zoom in and out buttons, at the moment I press a search button and it takes me to a zoom level of 17, I was wondering what two lines of code I have to write in order to add or take away one from the zoom level each time the button was clicked?
Question 2
I also wish to use pushpin within my application I can set up a simple one set to center at one location, but I would like it to center when a new location is applied and to stay in the same spot instead of when scrolling out it becomes disconnected from its original centered point?
Comment: I believe there's a `ZoomLevel` property that is just a `double`, you can simple increase/decrease that value on your button click.
Answer: Here is a simple navigation bar that provides pan buttons and a zoom slider:
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Height="290">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="30"/>
        <ColumnDefinition Width="30"/>
        <ColumnDefinition Width="30"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="30"/>
        <RowDefinition Height="30"/>
        <RowDefinition Height="30"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Button Content="⇑" Width="25" Height="25" Grid.Column="1" Tag="Up" Click="PanMap_Click"/>
    <Button Content="⇒" Width="25" Height="25" Grid.Row="1" Grid.Column="2" Tag="Right" Click="PanMap_Click"/>
    <Button Content="⇓" Width="25" Height="25" Grid.Row="2" Grid.Column="1" Tag="Down" Click="PanMap_Click"/>
    <Button Content="⇐" Width="25" Height="25" Grid.Row="1" Tag="Left" Click="PanMap_Click"/>

    <Slider Name="ZoomBar" Orientation="Vertical" Height="180" Width="20" Margin="10,10" Grid.ColumnSpan="3" Grid.Row="3"
         HorizontalAlignment="Center" Minimum="1" Maximum="19" SmallChange="1"/>
</Grid>

For the zoom bar I being it to the center property of the map like this:
<m:Map Name="MyMap" ZoomLevel="{Binding Value, ElementName=ZoomBar, Mode=TwoWay}"/>

Here is the code behind for the panning:
private void PanMap_Click(object sender, RoutedEventArgs e)
{
    Button b = sender as Button;
    Point p;

    MyMap.TryLocationToViewportPoint(MyMap.Center, out p);

    if (p != null)
    {
        switch (b.Tag as string)
        {
            case "Up":
                p.Y -= 50;
                break;
            case "Down":
                p.Y += 50;
                break;
            case "Left":
                p.X -= 50;
                break;
            case "Right":
                p.X += 50;
                break;
        }

        Microsoft.Maps.MapControl.WPF.Location l;
        MyMap.TryViewportPointToLocation(p, out l);
        MyMap.SetView(l, MyMap.ZoomLevel);
    }
}

What do you mean with question 2? If you add a pushpin to the map it should stay connected to the coordinate you specified and not the center of the map when you pan as the center of the map will be a different location. Do you simply want to place a control over the map that doesn't move when you pan?

Bing Maps PushPin and Zoomin / Zoom out


Reaction rule throws exception when previewing node

Question: I have very simple reaction rule condition 'Node is Type' in Drupal 8 (8.5.3) Rules module (8.x-3.0-alpha3):
Data selector: @node.node_route_context:node

(Note: the mentioned issue occurs also for simple value node in the data selector.)
Content types: page

It works well when a node is viewed, but the rule causes crash with the error message The website encountered an unexpected error. Please try again later. when a node is previewed (button 'Preview' is clicked on the node form).
Note: To replicate the issue you should clear the cache on node form before hitting the 'Preview' button to ensure the node isn't served from the Drupal cache in which case Rules aren't fired.
The logged Error Message is:
Drupal\rules\Exception\EvaluationException: The context for node is NULL,
but the context node in rules_node_is_of_type requires a value.

Any hints on better Rules condition to catch the node type, or a patch for Rules?
Thank you!
Comment: Unless you need the rule to fire/trigger on the preview page (Can't think of any reason why you would...) you could set the rule to not trigger on `node/preview/*` path.
Comment: Under the hood, you'll probably find some component is trying to load a node with nid 'preview' if that is indeed the path format.
Comment: Thanks @Beebee! However, I see no way how to order the elements in the conditions in D8 Rules GUI (thus the node type condition could throw an exception before the path condition can exclude the Rule from firing), nor I have an option to create a negative condition... :(
Comment: Thanks @AlfredArmstrong - I believe that is the case. That is actually my question: if it is an (unknown) bug, I shall open a ticket on Rules and do the job with entity_view hook (which is safe and much easy to use than Rules API), OR I do something stupid which can be fixed by better condition...
Comment: @MichalGow I'd seen the same bug in custom code written for Drupal 8.
Answer: I have found a workaround.
It seems that this is indeed a bug in the Rules module. The working solution is from here (although it was originally written for different situation, it fits this case as well): https://www.drupal.org/project/rules/issues/2929588#comment-12385257, and basically suggests to use a different condition:
Rule condition: 'Condition: Data comparison'
Data to compare (switched to data selection): node.type.target_id (Content type ID)
Operator (switched to Direct Input mode): ==
Value (switched to Direct Input mode): your_node_type

I hope this helps somebody.


Soloing in Harold Mabern's Edward Lee

Question: I'm looking at the song "Edward Lee" by Harold Mabern, Jr. (as it's presented in The Real Easy Book in C) and I'm trying to understand how to apply scales approach to soloing over its chords. There are two chords that appear problematic.
The chord progression for part A is

| Em7 |  %  |   %   |   A7   |
| B7  | Em7 | Cmaj7 | B7 Em7 |

For part B:
| G7 | Cmaj7 |   E7  | Amaj7 |
| D7 | Gmaj7 | C7sus |   B7  |

The supplemental material page for this song suggests that all the major dominant chords in the song correspond to Mixolydian mode. However, B7 and E7 chords have G natural and C natural respectively in the melody over them, which are 6♭ and aren't in the Mixolydian scale.
So the question is: is simply adding the 6♭ to the Mixolydian scale for these two chords a reasonable approach here? I'm also interested why the 6♭ notes really seem to work well with the harmony in this song.
Answer: In such a functional progression it is not helpful to look at each chord in isolation, so you can't just say "I play mixolydian over each dominant seventh chord". The B7 chord is clearly the dominant in the key of E minor. The B mixolydian scale would be a reasonable choice if it resolved to E major. However, in E minor, the standard choice over B7 would be E harmonic minor (harmonic, because it includes the D#, which is the third of B7). In part B you have three successive V-I cadences. Over G7 you can indeed play G mixolydian (which has the same notes as C major), because it resolves to C (maj7). Over E7 you have several choices. You could anticipate the resolution to A major by playing E mixolydian. However, I would go for E harmonic minor, suggesting a resolution to A minor (the relative minor of C major, where we're coming from). Then the surprise effect of resolving to A major (instead of minor) is stronger. Over D7 I'd just play D mixolydian (it resolves to G major). Finally, you go back to E minor via C7 and B7. Over C7 you can add the Bb, which underlines the bluesy character, and over B7 you again play E (harmonic) minor.
Note that you always have choices, and the above is just a very basic way to get you through the changes.

Soloing in Harold Mabern's Edward Lee


storing nagios configuration data in oneCMDB

Question: I want to store my nagios configuration data into oneCMDB(configuration management database). What i trying to achieve is i will be developing a GUI app in which one can edit the configurations and that configurations will be stored into the database rather than the plain text files. I read it's developer and administrator documentation but there is not tutorial available for it.
If anyone can give a link to such tutorial then it will be a great help to me since there is no such tutorial available.Any suggestions are most welcome.
Answer: Well, as far as I know and understand the term cmdb, there is no real database engine, but instead systems like puppet, chef, or cfengine2 are cmdb's. Like wikipedia explains cmdb: http://en.wikipedia.org/wiki/Configuration_management_database
So, you could program add-ons for these systems that would support your nagios config?


How to add Wishlist/Add to Cart in all products shown in front page in drupal 7?

Question: I am work on commerce_kickstart site. I was created 3 views in my front-page. In each view 3 products are there. I want to add Wishlist/AddToCart below in the list of every product. How can i do this. Please Help. Thanks
Answer: Install and enable the Commerce Wishlist module and in views add the Commerce Product: Add to Cart form field, then you can see Wishlist/AddToCart button. Also Enable the checkbox "Link products added to the cart from this display to the current path the customer is viewing where the View is rendered".
Don't forget to set permission and configuration.

Features

Provides an "Add to Wishlist" button on the display product node;
Creates a customizable list with Views to display all products on the Wishlist – both as a page and as a block;
Recognizes and stores product variations;
Makes it possible for users to easily delete or switch products in their Wishlist to their Shopping Cart with the click of a button;
Comment: I already installed but I have a problem that in my view I am not getting any option "Commerce Product: Add to Cart form"...@Bala
Comment: You have to use relationship under advanced section and then add "Content: Referenced products"
Comment: May u pls first help me to fetch the price. Actually I am unable to fetch the price also... @Bala
Comment: Please check the "Require this relationship" for "Content: Referenced products"
Comment: After doing this... products are going to disable @Bala
Comment: Ok uncheck it, what is the problem your facing actually ? once you added the  "Content: Referenced products" in relationship you can add any product variations fields. and we are going out of topic please try different combinations to achieve your requirement.
Comment: if I check the "Require this relationship" for "Content: Referenced products" then all the products of the view is not visible & if I uncheck the "Require this relationship" & add field i.e "Commerce Product: Price" then nothing show except product image
Comment: Ok uncheck the  "Require this relationship" for "Content: Referenced products"  and then try it
Comment: Plz read my above comment.. @Bala
Comment: I can't understand for what am I add filter criteria for getting Price of every product.
Comment: Its too long unable to comment here. How can i provide you. @Bala
Comment: actually i am working on a development server...
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/17290/discussion-between-samzha-and-bala).
Comment: sent pls check... http://tempsend.com/6D3CDAA381
Comment: I want to discuss with you @Bala


Create a search query and display the results based on the selected checkboxes (difficulty grouping results)

Question: I want to have a php page that display multiple keywords (checkboxes) for example areas such as Narberth, Pembrokeshire, Carmarthenshire etc as well as other things.
So far i have created a way to do this and display the data separately in tables. What I'm having trouble with is showing the rows with multiple keywords associated with them first.
So if the user searched "Narberth" and "Pembrokeshire" the results would show any documents with both those keywords in first then anything with just "narberth" and just "pembrokshire" afterwords.
I listed my code for what I've worked out so far :
<form method="post">

<input type="checkbox" name="keywords[]" value="1">Narberth
<input type="checkbox" name="keywords[]" value="2">James Brothers
<input type="checkbox" name="keywords[]" value="3">Mabinogion

<input type="checkbox" name="keywords[]" value="4">Pembrokeshire
<input type="checkbox" name="keywords[]" value="5">Pubs
<input type="checkbox" name="keywords[]" value="6">Coastal Paths

<input type="submit" name = "submit">

<?php
if (isset($_POST['submit'])) {

foreach( $_REQUEST['keywords'] as $keywordID )
{
$result = mysql_query("SELECT * FROM tbl_index m
inner join tbl_filekeywords r on m.file_id = r.file_id
where r.keyword_id = '".$keywordID."'");

$keywordname = mysql_query ("SELECT keyword FROM tbl_keywords WHERE keyword_id = '".$keywordID."'");
$KeywordName = mysql_fetch_row($keywordname);
$KeywordName = $KeywordName[0];

echo "

".$KeywordName."

File ID
Filename

";

while($row = mysql_fetch_array($result)){
echo "
";
echo "" . $row['file_id'] . "	";
echo "" . $row['file'] . "	";
echo "
";
}
echo "

";
mysql_free_result($result);
}
}?>

P.S There is another alternative that i developed that lumps all the files into one table which is fine but i still want to stop the same files appearing multiple times for each keyword and would rather the ones with more than one keyword to be prioritized and displayed on top.
<?php
if(isset($_POST['keywords']) && !empty($_POST['keywords'])){
foreach($_POST['keywords'] as $key=>$value){
if($value==1) $keywords[] = "keyword_id='".mysql_escape_string($key)."'";
}
$keywords = implode(' OR ', $keywords);
}
$query = "SELECT * FROM tbl_index m inner join tbl_filekeywords r on m.file_id = r.file_id WHERE $keywords";
$result = mysql_query($query);

echo "

File ID
Filename
Keyword_ID

";

while($row = mysql_fetch_array($result)){
echo "
";
echo "" . $row['file_id'] . "	";
echo "" . $row['file'] . "	";
echo "" . $row['keyword_id'] . "	";
echo "
";
}
echo "

";
mysql_free_result($result);
?>

And finally the tables are set up like:
tbl_index : file_id, file

tbl_keywords : keyword_id, keyword

tbl_filekeywords : file_id, keyword_id

Answer: First of all, wellcome to SO. Post answer delay is due to non synthesized question. In next questions remember to include only relevant code to question.
Lets supose that tbl_index and tbl_filekeywords tables are in 1:N relationship.
First of all, in php you can get $keywords as a string list of selected keywords Example:
$keywords = " 1, 5, 12,  24"

Now you can rank tbl_filekeywords in this way. We named rank view:
select
  r.file_id,
  sum( case when r.keyword_id in ( $keywords  ) then 1 else 0 end ) as rank
from
  tbl_filekeywords r
group by
  r.file_id

Last step is to join rank view with tbl_index:
   select t.*
   from
     tbl_index t left outer join
     ( HERE PREVIUS QUERY ) r
          on r.file_id = t.file_id
   order by
     coalesce( r.rank, 0 )

Let us to know if this runs and it is a solution for you. If not, explain how can we improve answer!
Edited due OP Comment
I don't have your database schema, but it seems that file_id is PK for tbl_index. If this is the case, the query don't produce duplicates. Notice that first query, rank view, only has a row for each file_id due to group by clause. Because this, join don't produce duplicates. For me the final query is:
   select t.*
   from
     tbl_index t inner join                 <--No dups
     (
       select
         r.file_id,
         count(*) as rank
       from
         tbl_filekeywords r
       where
         r.keyword_id in ( $keywords  )
       group by
         r.file_id                          <--No dups
     ) r2
          on r2.file_id = t.file_id
   order by
      r2.rank

Comment: Thanks for the swift reply, I've not dealt with ranks before so this is new to me. As far as I can tell this will order the rows in an appropriate way But won't i still get duplicates? For example the tbl_filekeywords looks like this:

file_id :- 1 , 1, 1, 2, 2
keyword_id :- 1, 3, 7, 1 , 2

The problem is i want these to only appear once when the table is generated online. At the moment when i search keywords 1 and 3, file_id appears once for each keyword. Thanks :)
Comment: After testing this it seems to work perfectly, the only thing is that the file_id with the greatest importance is being showed at the bottom  of the list. how would i go about swapping this so it shows at the top? Sorry for the delay and thanks again for your time :)
Comment: Haha never mind i just added desc after the order by :P obvious change on my part :)


Why this function is Riemann integrable?

Question: Let $f:[a,b]\rightarrow \mathbb R$
$$f(x)=0\text{ if x is irrational} $$
$$f(x)=\frac{1}{q}\text{ if }x=\frac{p}{q},\text{gcd}(p,q)=1 $$
When we consider the Dirichlet function, then we are saying that it is not Riemann integrable because the upper and the lower Riemann sums does converge to different values.
Why this can't be applied here at the same way? Because in this case the function does attain also different values for rational and irrational numbers. Hence the set of discontinues is uncountable..
Comment: If you pick some $\epsilon>0$, then $f(x) < \epsilon$ except at a finite number of values. If $f(x) \ge \epsilon$, the corresponding $q$ must satisfy $q \le {1 \over \epsilon}$. There are a finite number of such $q$.
Comment: Because on any non trivial interval, the  Dirichlet function takes the values $0,1$ and so the upper and lower sums are always $(b-a)$, $0$ respectively. With the above $f$, given any $\epsilon$, you can 'isolate' the **finite** number of 'large' values.
Comment: Your $f$ is continuous at every irrational.
Comment: @copper.hat Why can I isolate the finite number of large values? Which finite number?
Answer: Proof:
a, f has a limit everywhere, and it is $0$.
It is enough, to show it on $(-1,1)$. Let us have an arbitary $a \in (-1,1)$.
First, we need, that for every $\epsilon > 0$, such $\delta$ exists, that if $|x-a| < \delta$, then $|f(x)-0| < \epsilon$. Let us have $N > \frac{1}{\epsilon}$, then $|f(x)-0|=|f(x)| \le \frac{1}{N}$. If $x$ is irrational, it is of course, true, if $x$ is rational, we need that, $x=\frac{p}{q}$, where $q > N$. Divide the interval $(-1,1)$ into $\frac{1}{q}$ length areas, and choose one of them, which contains $a$. Choose $\delta$ lower, than the distance between $a$ and the interval.
b, f is contionus in every irrational points.
If $a$ is irrational, $f(a)=\lim_{x\rightarrow a} f(x) = 0.$
c, f isn't contious, whenever $x$ is rational.
If $a$ is rational, $f(a) \ne\lim_{x\rightarrow a} f(x) = 0.$
Consequence: Our function is bounded, and it isn't continous in $\mathbb{Q}$. Since $\mathbb{Q}$'s Lebesgue measure is $0$, it is Riemann-integrable. It can be proven, that there isn't any function which is continous in rational points, and isn't in irrational points.
Hint: This function is called Riemann-function.
Comment: How is "f has a limit everywhere, and it is 0" true? What do you mean by "limit everywhere"?
Comment: I don't understand what is meant by "$f$ has a limit".
Comment: Fermé somme means this: For each $t \in [a,b]$ we have $\lim_{x \rightarrow t}f(x) = 0,$ where $x$ is restricted to belong to the interval $[a,b]$ when the limit $x \rightarrow t$ is taken.


What is non-idempotent memory-mapped I/O meaning?

Question: In RISCV privileged spec page 75 mention a term "non-idempotent memory-mapped I/O". What is non-idempotent memory-mapped I/O? Is it about non side effect?What is design concern about non-idempotent memory-mapped I/O?
Answer: It means writing the same value twice is not the same thing as writing it just once.
e.g. an MMIO register where a write transaction triggers a UART to send the bits out over a serial port.
Unlike for a control register where writing the value that's already there has no effect.  Or e.g. a parallel port where the external pins reflect the bits in the MMIO register, and writing them again doesn't change anything.


Orleans frontend other that ASP.NET

Question: As far as i could find, the only possible frontend for Orleans it is ASP.NET. Is there any way to have not .net frontend?
Answer: The api specification is public, you can implement in the language that you prefer, But as it relies in .net binary serialization and primitives, I don't think is a wise decision. If you want to connect from other languages, the prefered approach it's to use a webapi as a proxy between the orleans cluster and the rest of your services. There is even a automatic API which publishes all orleans public methods as http endpoint in the contributions packages.
What are you trying to do?
Comment: I am want to communicate with Orleans over http from other services. The simplest solution is to make simple front-end with ASP.NET and communicate through it.
Comment: Well, https://github.com/OrleansContrib/OrleansHttp is an automatic bridge between http and your orleans cluster. It's a bit outdated, but maybe its helpful as a starting point.

Orleans frontend other that ASP.NET


Django "SuspiciousOperation" Error While Deleting Uploaded File

Question: I'm developing in Django on Windows XP using the manage.py runserver command to serve files. Apache isn't involved. When I login to the administration and try to delete a file I get a "SuspiciousOperation" error.
Here's the traceback:
http://dpaste.com/123112/
Here's my full model:
http://dpaste.com/hold/123110/
How can I get rid of this "SuspiciousOperation" error?
EDIT: Here are my media settings:
MEDIA_ROOT = 'C:/Server/Projects/postnzb/static/'
MEDIA_URL = '/static/'

Answer: What is your MEDIA_ROOT in settings.py? From the back-trace, it seems you have set your MEDIA_ROOT to /static/.
This error is coming since Django is trying to access /static/ to which it has no access. Put an absolute pathname for MEDIA_ROOT like C:/Documents/static/ and give full permissions to Django to access that directory.
That should solve your problem.
Addendum: Since your MEDIA_ROOT seems to be OK, I am guessing that you are using MEDIA_URL for deleting the file instead of MEDIA_ROOT. Indeed, from the error it seems that Django was trying to access the /static/files/8.nzb and was denied access. Clearly, /static/ is your MEDIA_URL and not your MEDIA_ROOT. The model methods should never try accessing the files using the MEDIA_URL. I am sure a review of your code will spot the error.
Update: I skimmed your code and it seems you are setting File.nzb to %(1)sfiles/%(2)s.nzb' % {'1': settings.MEDIA_URL, '2': self.pk} which uses its MEDIA_URL and then in the delete() method you are calling the delete() method of the super-class of File as super(File, self).delete() which is obviously wrong as it will try deleting File.nzb and will try accessing the file through the MEDIA_URL. Fixing that will get rid of the error. I will leave the exact solution as an exercise to you :)
Comment: I've added my media settings to my question description. MEDIA_ROOT is, in fact, an absolute path.
Comment: Thanks for helping my though this issue. Turns out you were completely  correct. "File.nzb" ether has to be a full path or a relative path that doesn't start with the forward slash. Since I'm going to deploy on a NIX server, I'll use relative paths. Thanks again!


I'm using angularx-social-login with angular11 for login by gmail and I'm gettting accessToken in response but I want authorizationCode in response

Question: I need  authorizationcode

{"code":"4/yU4cQZTMnnMtetyFcIWNItG32eKxxxgXXX-Z4yyJJJo.4qHskT-UtugceFc0ZRONyF4z7U4UmAI"}

like this in response for refresh token
<code>  {
  provide: 'SocialAuthServiceConfig',
  useValue: {
    autoLogin: true,
    providers: [
      {
        id: GoogleLoginProvider.PROVIDER_ID,
        provider: new GoogleLoginProvider(CLIENT_ID, {
          response_type: 'authorization_code',
          access_type: 'offline',
        }),
      },
    ],
   } as SocialAuthServiceConfig,
  }
</code>
Answer: You need to understand how Oauth2 works When the user consents to your access then authorization code is returned.
Your application then recieves the authorization code and exchanges it with the authorization server for an access token and a refreshtoken.
The access token can be used to access Google apis, and private user data. However this token is short lived it will only work for an hour.
The refresh token is long lived and can be used to request a new access token after it has expired.

I need authorizationcode like this in response for refresh token

So in response to this statement the refresh token response will never return an authorization code.  Only the request for consent of the user the first step in the flow will return an authorization code.
If you are interested in seeing how Oauth2 works this may interst you. Understanding Oauth2 with curl.


iOS - Local Notifications independent from time zone

Question: I've got a problem with local notifications in iOS.
I want to schedule a notification at a certain time, but it must be fired regardless of the Time Zone... ie: if I schedule a notification at 03:00 PM it must fire at exactly at 03:00 PM wherever I am...
This is my code but I cannot achieve this result... could you help me?
Thank you!
static func createNotificationNamed(_ notificationName: String, at notificationDate: Foundation.Date, title: String, body: String, delta: UInt32) {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
            if granted {
                let calendar = Calendar(identifier: .iso8601)
                var components = calendar.dateComponents(in: .current, from: notificationDate)
                components.minute = components.minute! + Int(arc4random_uniform(delta))

                var datecomp = DateComponents()
                datecomp.year = components.year
                datecomp.month = components.month
                datecomp.day = components.day
                datecomp.hour = components.hour
                datecomp.minute = components.minute
                datecomp.calendar = components.calendar
                datecomp.timeZone = TimeZone.autoupdatingCurrent

                let trigger = UNCalendarNotificationTrigger(dateMatching: datecomp, repeats: false)
                let content = UNMutableNotificationContent()
                content.title = title
                content.body = body
                content.sound = UNNotificationSound.default()

                let request = UNNotificationRequest(identifier: notificationName, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request) {(error) in
                    if let error = error {
                        print("Uh oh! We had an error: \(error)")
                    }
                }
            }
        }
    }
}

To simulate it I schedule the notification, then change the TimeZone on my phone and I wait for the right time, but nothing happens.
Answer: At the end I've solved this issue setting the specific TimeZone...
datecomp.timeZone = TimeZone.init(abbreviation: "PDT")

Answer: Try this function and pass your date and also give local notification permission on AppDelegate file, also check local permission iOS version wise.
func scheduleNotification(date: Date) {

    var dateComponents: DateComponents = DateComponents()

    let content = UNMutableNotificationContent()
    content.title =  // title
    content.subtitle =  // subtitle
    content.body =  // body
    content.sound = UNNotificationSound.default()

    dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)

    let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger)

    let notiCurrent = UNUserNotificationCenter.current()
    notiCurrent.add(request) { (error) in
        if let error1 = error {
            print(error1.localizedDescription)
        }
    }

}

Comment: It doesn't work.
You also declare the constant calendar but you never use it later.
Comment: I add my function that I used for local notification. Try it's.


What are the 'big problems' in statistics?

Question: Mathematics has its famous Millennium Problems (and, historically, Hilbert's 23), questions that helped to shape the direction of the field.
I have little idea, though, what the Riemann Hypotheses and P vs. NP's of statistics would be.
So, what are the overarching open questions in statistics?
Edited to add:
As an example of the general spirit (if not quite specificity) of answer I'm looking for, I found a "Hilbert's 23"-inspired lecture by David Donoho at a "Math Challenges of the 21st Century" conference: High-Dimensional Data Analysis: The Curses and Blessings of Dimensionality
So a potential answer could talk about big data and why it's important, the types of statistical challenges high-dimensional data poses, and methods that need to be developed or questions that need to be answered in order to help solve the problem.
Comment: Thank you for posting this.  It's an important (and potentially inspiring) discussion to have.
Answer: A big question should involve key issues of statistical methodology or, because statistics is entirely about applications, it should concern how statistics is used with problems important to society.
This characterization suggests the following should be included in any consideration of big problems:

How best to conduct drug trials.  Currently, classical hypothesis testing requires many formal phases of study.  In later (confirmatory) phases, the economic and ethical issues loom large.  Can we do better?  Do we have to put hundreds or thousands of sick people into control groups and keep them there until the end of a study, for example, or can we find better ways to identify treatments that really work and deliver them to members of the trial (and others) sooner?
Coping with scientific publication bias.  Negative results are published much less simply because they just don't attain a magic p-value.  All branches of science need to find better ways to bring scientifically important, not just statistically significant, results to light.  (The multiple comparisons problem and coping with high-dimensional data are subcategories of this problem.)
Probing the limits of statistical methods and their interfaces with machine learning and machine cognition.  Inevitable advances in computing technology will make true AI accessible in our lifetimes.  How are we going to program artificial brains?  What role might statistical thinking and statistical learning have in creating these advances?  How can statisticians help in thinking about artificial cognition, artificial learning, in exploring their limitations, and making advances?
Developing better ways to analyze geospatial data.  It is often claimed that the majority, or vast majority, of databases contain locational references.  Soon many people and devices will be located in real time with GPS and cell phone technologies.  Statistical methods to analyze and exploit spatial data are really just in their infancy (and seem to be relegated to GIS and spatial software which is typically used by non-statisticians).
Comment: @grautur: That's four excellent questions (plus many more, because your response applies to every answer in this thread).  They all deserve elaborate answers, but obviously there's no space for that here: one question at a time, please!
Comment: Concerning the first bullet (drug trials): even people who otherwise might not be interested in medical experimentation should read the NYTimes article *New Drugs Stir Debate on Basic Rules of Clinical Trials* (http://www.nytimes.com/2010/09/19/health/research/19trial.html?pagewanted=1&_r=1&th&emc=th ).  The statistically literate reader will immediately see the unstated implications concerning experimental design and using p-values for decision making.  There is a statistical resolution, somewhere, to the life-and-death conundrum described in this article.
Comment: What are ways in which people are trying to solve these problems?
Answer: Michael Jordan has a short article called What are the Open Problems in Bayesian Statistics?, in which he polled a bunch of statisticians for their views on the open problems in statistics. I'll summarize (aka, copy-and-paste) a bit here, but it's probably best just to read the original.
Nonparametrics and semiparametrics

For what problems is Bayesian nonparametrics useful and worth the trouble?
David Dunson: "Nonparametric Bayes models involve infinitely many parameters and priors are typically chosen for convenience with hyperparameters set at seemingly reasonable values with no proper objective or subjective justification."
"It was noted by several people that one of the appealing applications of frequentist nonparametrics is to semiparametric inference, where the nonparametric component of the model is a nuisance parameter. These people felt that it would be desirable to flesh out the (frequentist) theory of Bayesian semiparametrics."

Priors

"Elicitation remains a major source of open problems."
'Aad van der Vaart turned objective Bayes on its head and pointed to a lack of theory for "situations where one wants the prior to come through in the posterior" as opposed to "merely providing a Bayesian approach to smoothing."'

Bayesian/frequentist relationships

"Many respondents expressed a desire to further hammer out Bayesian/frequentist relationships. This was most commonly evinced in the context of high-dimensional models and data, where not only are subjective approaches to specification of priors difficult to implement but priors of convenience can be (highly) misleading."
'Some respondents pined for non-asymptotic theory that might reveal more fully the putative advantages of Bayesian methods; e.g., David Dunson: "Often, the frequentist optimal rate is obtained by procedures that clearly do much worse in finite samples than Bayesian approaches."'

Computation and statistics

Alan Gelfand: "If MCMC is no longer viable for the problems people want to address, then what is the role of INLA, of variational methods, of ABC approaches?"
"Several respondents asked for a more thorough integration of computational science and statistical science, noting that the set of inferences that one can reach in any given situation are jointly a function of the model, the prior, the data and the computational resources, and wishing for more explicit management of the tradeoffs among these quantities. Indeed, Rob Kass raised the possibility of a notion of "inferential solvability," where some problems are understood to be beyond hope (e.g., model selection in regression where "for modest amounts of data subject to nontrivial noise it is im- possible to get useful confidence intervals about regression coefficients when there are large numbers of variables whose presence or absence in the model is unspecified a priori") and where there are other problems ("certain functionals for which useful con- fidence intervals exist") for which there is hope."
"Several respondents, while apologizing for a certain vagueness, expressed a feeling that a large amount of data does not necessarily imply a large amount of computation; rather, that somehow the inferential strength present in large data should transfer to the algorithm and make it possible to make do with fewer computational steps to achieve a satisfactory (approximate) inferential solution."

Model Selection and Hypothesis Testing

George Casella: "We now do model selection but Bayesians don't seem to worry about the properties of basing inference on the selected model. What if it is wrong? What are the consequences of setting up credible regions for a certain parameter $β_1$ when you have selected the wrong model? Can we have procedures with some sort of guarantee?"
Need for more work on decision-theoretic foundations in model selection.
David Spiegelhalter: "How best to make checks for prior/data conflict an integral part of Bayesian analysis?"
Andrew Gelman: "For model checking, a key open problem is developing graphical tools for understanding and comparing models. Graphics is not just for raw data; rather, complex Bayesian models give opportunity for better and more effective exploratory data analysis."
Answer: I'm not sure how big they are, but there is a Wikipedia page for unsolved problems in statistics.  Their list includes:

Inference and testing

Systematic errors
Admissability of the Graybill–Deal estimator
Combining dependent p-values in Meta-analysis
Behrens–Fisher problem
Multiple comparisons
Open problems in Bayesian statistics

Experimental design

Problems in Latin squares

Problems of a more philosophical nature

Sampling of species problem
Doomsday argument
Exchange paradox
Answer: As an example of the general spirit (if not quite specificity) of answer I'm looking for, I found a "Hilbert's 23"-inspired lecture by David Donoho at a "Math Challenges of the 21st Century" conference:
High-Dimensional Data Analysis: The Curses and Blessings of Dimensionality
Comment: May I suggest that you edit your main question to include this information?
Answer: You might check out Harvard's "Hard Problems in the Social Sciences' colloquium held earlier this year. Several of these talks offer issues in the use of statistics and modeling in the social sciences.
Answer: Mathoverflow has a similar question about big problems in probability theory.
It would appear from that page that the biggest questions are to do with self avoiding random walks and percolations.
Comment: @raegtin - I don't think probability theory is separate from statistics, rather it is the theory.  "Statistics" is the application of probability theory to inferential problems (i.e. the practice).
Comment: I think statistics is a separate area from probability theory, though.
Answer: My answer would be the struggle between frequentist and Bayesian statistics. When people ask you which you "believe in", this is not good! Especially for a scientific discipline.
Comment: There is nothing wrong with a scientist "believing" in something, especially as a Bayesian probability represents the degree of belief or knowledge regarding the truth of some proposition.
Comment: ...The problem arises only when a scientist cannot distinguish between a belief and a fact.  There is nothing unscientific in the belief that Bayesian or frequentist statistics are superior, as there is no objective test that can decide the answer (AFAIK), so the choice is largely subjective and/or a matter of "horses for courses".
Comment: @propofol - I agree that the word "believe" is not an appropriate notion to use in statistics - it carries the wrong sorts of connotations.  Information is a much more appropriate word I think (i.e. "what information do you have?").  It doesn't change the maths or the optimality theorems of Bayesian analysis, but it gives them their proper meaning in terms of how they are actually used.  e.g. knowledge of a physical theory or causal mechanism is information, and not belief.


Oiling a whole guitar body instead of using lacquer/paint/varnish

Question: I have just been making my first guitar over the last few days from scratch and I have just gotten to the point of needing a finish for it. I was wondering if anyone had experience in oiling a whole guitar body instead of varnish. Pros and cons. Any advice?
Edit: it is a solid body slide guitar
Comment: may be a better fit @ woodworking.stackexchange.com
Comment: @Yorik I disagree, unless there are luthiers there.  The finish affects the sound, something that I do not think a cabinet maker needs to worry about.
Comment: What type of guitar? I can see the finish affecting the sound for acoustic ones, but probably not for a solid body electric. For drums, the claim is harder finishes, like polyurethane, brighten the sound ever so slightly. I'm finishing my first kit with tung oil and decided to move to polymerized tung oil to get a glossier, more protective finish. Straight tung oil really doesn't make much of a protective coat at all and looks a bit dull. It'll help with sweat, but not much else. Polymerized tung oil behaves a lot more like wiping varnish...
Comment: Is there more maintenance on an oiled finish? That would be a deal breaker for me.
Comment: @WayneConrad lol the original Martin was from the cabinet makers guild of his country, but I see what you mean, because my father is a cabinet maker and he mostly knows guitar stuff because of me. Tho it is helpful having someone good with tools... I might as at woodworking SE as well to see if anyone there has experience.
Comment: @ZalmanStern I assumed acoustic, but now that you mention it, the OP didn't say.
Comment: I was using pure tung oil originally. (WoodRiver, which is a properly labelled quality product.)"Dull" may not be quite the right word, but it is not glossy. I did a bunch of coats over quite a long time with adequate drying time. Initial coats were mixed with 50% odorless mineral spirits. Finish I got had wood beauty, but not quite right for drums. Sutherland Welles' polymerized tung oil seems to be what it says on the tin. It dries much much faster and makes a coat. Otherwise, about the same as tung oil. The drying makes it less easy to work with. Hard to beat regular pure tung oil for ease.
Answer: It's not unheard of, it's done a lot. It wont effect your tone much, if at all.
Con:

You're going to be re-oiling it from time to time.

Pro:

I find an oiled neck to not be grippy like some of those new Fender necks and therefore I can move faster up and down the neck.

Everything else is personal, like just preferring the look of oiled wood over varnished.


Por que em operações de "reset" de css não é recomendado usar o asterisco?

Question: Eu já vi vários tutorias de internet sobre css reset ensinando que não se deve jamais usar o asterísco para aplicar as modificações.
Por exemplo:
* { margin:0; padding:0; }

Porém, junto com a afirmação de que fazer isso é problemático, eu nunca vi uma explicação de porquê não se pode fazer isso.
Qual é o motivo do uso do asterisco no css não ser recomendado? Existe algum risco?
Comment: Talvez por performance, mas isso varia demais. Tem algum exemplo de onde leu isso?
Answer: Usando " * " você está selecionando TODOS os elementos do HTML, o que não faz muito sentido. Um exemplo: a tag
 por natureza já vem com um margin-top e um margin-bottom setados, se você retirar esses espaços muito provável que você precisará adicioná-los novamente depois, já que são os espaços padrão do parágrafo, e sem eles os textos ficarão colados.
O reset é para deixar os elementos mais "puros" possíveis, retirando qualquer influência do navegador ou algum outro resquício de CSS. Não deve ser aplicado à todos os elementos.
É o que eu acho, né.


Android Listview

Question: i want to Differentiate Listview and perform different action in different position.
This is my Code.
<code>    al.add(new Student("हनुमान चालीसा", "Hanuman Chalisa", R.drawable.omicon, R.drawable.ic_file_download));
    al.add(new Student("श्री बजरंग बाण", "Shri Bajrang Baan", R.drawable.omicon, R.drawable.ic_file_download));
    al.add(new Student("संकटमोचन हनुमानाष्टक", "Sankatmochan Hanumanashtak", R.drawable.omicon, R.drawable.ic_file_download));
    al.add(new Student("श्री हनुमानजी की आरती", "Hamuan Je Ke Arti", R.drawable.omicon, R.drawable.ic_file_download));
    al.add(new Student("हनुमान जन्म कथा", "Hanuman Janam Katha", R.drawable.omicon, R.drawable.ic_file_download));

    adapter = new StudentAdapter();
    list.setAdapter(adapter);

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i(getTag(), "onListItemClick: " + position);
            Toast.makeText(getActivity(), "Click To Play/Download Iocn", Toast.LENGTH_LONG).show();

        }
    });

    return singleview;
</code>
Comment: Show the code of `StudentAdapter` then ?
Comment: post full code or your implementation
Comment: you maybe getting  position in this line Log.i(getTag(), "onListItemClick: " + position);  so what's wrong?
Comment: In  setOnItemClickListener  you getting position,  then what is problem?
Comment: @ShubhamShukla bro i want to perform action on listview not same action in different position
Comment: you have to perform action on whole listview clisk not an item click?
Comment: You can perform action on different position by use of state manage in Student class. so that you can identify which one action to perform, can get object of Student  class.
Comment: can you please send me a Whole Code please.
Comment: You're already getting a position of the clicked item in onItemClick(), so you can use switch(position) inside that function and do whatever action you want. What's the problem exactly?
Comment: @MatveyRybakov hello dude can you please help i want to download song from listview click with service can you plese help me.
Answer: Please use switch statement
<code>            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(getTag(), "onListItemClick: " + position);
                Toast.makeText(getActivity(), "Click To Play/Download Iocn", Toast.LENGTH_LONG).show();
               Switch (position){
                  case 0:
                      //do whatever in 0th position
                  break;
                  case 1:
                      //do whatever in first position
                  break;
                  ..
                  ...
                      //like this use other positions}

        }
    });
</code>

Android Listview


Forecasting optimization techniques in fantasy baseball

Question: I am currently trying to build a better forecasting model for my fantasy baseball roster. I currently am using commonly accepted projected season statistics (ZiPS from Fangraphs) to determine the average fantasy points a player can be expected to contribute per game.  This is problematic, however, because it does not take into account variance in player performance (among other things).

Since baseball involves both luck and skill, I don't think it is a useful exercise to try and predict any particular statistic of a game (i.e. how many hits Prince Fielder will have). Instead, I would like to project average point contributions but take variance into account while doing so.

The first thing that comes to mind is the effect of the opposing pitcher. My hypothesis is that the quality of the pitcher effects opposing player performance. Given two players to choose from which are relatively equal in projected fantasy point averages, how can I quantify the effect of the opposing pitcher and how can I test the hypothesis?

Also, how can I consider variance in a reasonable way even though it is uncertain? How would I actually know if my projections are under performing or over performing? (This seems to be similar to a financial portfolio optimization problem)
Answer: Accounting for variance
There's a lot to think about in optimising a lineup for fantasy sports. You're right that expectation and variance are huge parts of it. Naively it would seem that expected points earned is all that matters. However, certain contests will reward only the first place player out of thousands -- meaning you want very high variance teams so that your tail is fat enough to make a win possible*. Other contests reward all those in the top half equally, in which case you care more about expectation and less about having a tail -- you just want to get the maximum amount of your expected distribution above the halfway cutoff.
For some intuition on how your lineup ties to variance, there are a couple of mechanisms. Certain players have a higher variance than others. Players on teams who never lose, for instance, tend to have pretty low variance. The main effect comes from picking players on the same team or picking players on opposing teams. Players on the same team have very high covariance -- they tend to all win or lose points together. Players facing each other have negative covariance -- either one does well or the other, but rarely both or neither. (This is magnified for certain positions, like striker vs opposing goalie in hockey or, I imagine, pitches vs opposing batters in baseball). Lineups featuring players with a high covariance to one another are lineups with a high variance.
You're right that calculating the variance of a team has analogous to portfolio optimisation. The problem is exactly the same: assets are now players, expected returns are now expected points and variance is variance.
Calculating the variance for a lineup given a set of players with known covariance is easy. If we are considering $N$ players, define $p$ as a binary vector of length $N$ with value 1 if a player is present on a team and 0 otherwise. $\Sigma$ is the $N*N$ covariance matrix of all players, then the variance of the lineup $\sigma$ is given by:
$ \sigma = p^T \Sigma p $
Where $^T$ is the transposition.
Covariance should not be calculated at an individual player level since there will never be enough data. Pitcher A's covariance with Batter B across an entire season is not useful, since they won't play each other in every game. Instead calculate it on a position level: the covariance of home team pitchers versus visiting shortstops, home team shortstops versus visiting pitchers, home team shortstops versus home team pitchers, etc. (Disclaimer: opinion, you could also calculate it purely as home vs away, or purely as home vs away and pitchers vs non-pitchers.)
Effects of opposing players
To the expectation-predicting point of your post, you should absolutely use information from the pitcher to predict the performance of a batter. Fantasy aficionados call this "defense against position" or "fantasy points against". Essentially the idea is to use the historic point earnings of batters who have faced this pitcher to predict future performance for all batters who face them. It's a hugely powerful predictor, and you can validate as you would any other model change.
* There's a really cool paper on a bunch of guys from MIT optimising drafts for very top-heavy fantasy sport contests where they plan to make multiple entries and want to maximize the expectation of their entire multiple entry strategy. They care about having high variance within the lineups they enter, but also low correlation between their entries. They treat it as a max coverage problem and solve it with integer programming. It's a good read.
Comment: I [wrote a post](http://dexgroves.github.io/fantasy-sports/2016/08/17/fantasy-science.html) on things I learned trying to model fantasy performance which goes into more detail. <\plug>
Comment: Wow I didn't expect any other answers after three years... Thanks!
Comment: You got bumped by Community a few days ago.
Answer: Running with your example of picking between two players given the knowledge of an opposing pitcher, I think you could build a reasonable model using historical data to simulate outcomes. For example, suppose you are deciding to whether to start Player A or Player B. Player A is a 31 year old RH batter facing a RH starting pitcher that is the ace in his team's rotation. You could create a sample of observations from the fantasy points Player A generated when he faced a strong RH starting pitcher over the last 200 games. For example, Player A may have faced 30 top ranked RH pitchers over the last 200 games so you would have 30 different fantasy point observations in your sample. 200 is totally arbitrary, you could use more or less history depending on how much of Player A's history you feel is correlated to his recent performance. The more history you use the more games that will match the specifications of your sample, but some of the games might not be as applicable to Player A's current skill. You could also use other players that are comparable to Player A's skills, batting style, and age to increase the number of observations in your sample. Nate Silver talks about using comparable players in his book The Signal and the Noise. Furthermore, you could refine the games you add to the sample based on the ballpark the game is being played at (hitters park v. pitchers park), the weather (wind blowing in or out), the point in the season (early, mid, late), the type and frequency of pitches the pitcher throws, the quality of the team's bullpen, ect…You could make the sample as specific and you like, although you might end up with only a few observations which would degrade the usefulness of simulating outcomes.
Once you have a sample of games to draw from you can create a distribution of fantasy points that Player A might generate by bootstrapping the observations. If you repeat this same process for Player B and the pitcher he is facing you will have two distributions of fantasy points that each player is likely to generate in the upcoming game. You can compare the two distributions using statistical methods for comparing two means (t-test for normal distributions, Mann-Whitney U test for non-normal). If you are comparing multiple players you would need to use methods for comparing more than two means. As far as tracking the performance of your projections, the p-values derived from the comparison of means equate to the likelihood you would expect the player with lower projected fantasy points to outperform the player with higher projected points. If you make 10 projections, each that had a 10% p-value when you did the mean comparison, then you should expect to get about 9 of these projections right. If you are getting a lot more projections wrong then the p-values from your mean comparisons would suggest something might be wrong.
This is a very brute force method for comparing two players and it relies heavily on historical data, but you could always build in some adjustment factors to tweak the ending distributions based on domain specific knowledge. For example, maybe you know that the player who bats right before Player A is on the DL and his replacement is not as good at getting on base. This will likely hamper Player A's RBI production so maybe you want to shift the sample distribution of Player A's expected fantasy points to the left to account for the likelihood that Player A's fantasy point generation will be less due to a lower RBI potential. You could even estimate this adjustment factor from data. All in all, there are a lot of things you can do by bootstrapping historical outcomes that you think are representative of the games you are interested in and comparing the resulting distributions.


What is wrong with the followig proof that $\mathbb{Z}$ is isomorphic to $\mathbb{Z} \times \mathbb{Z}$

Question: Since
$ G =( \prod_{1}^{\infty} \mathbb{Z} )\times  \mathbb{Z}  \times \mathbb{Z}  \cong (\prod_{1}^{\infty} \mathbb{Z}) \times \mathbb{Z}  $,
by taking quotients we get
$\mathbb{Z \times Z} \cong G/ \prod_{1}^{\infty} \mathbb{Z} \cong \mathbb{Z}$.
Therefore
$\mathbb{Z} \cong \mathbb{Z \times Z}$.
But $\mathbb{Z}$ is indecomposable!  What's wrong with above proof?
Comment: The isomorphism from $(\prod \mathbb{Z})\times\mathbb{Z}\times\mathbb{Z}$ to $(\prod\mathbb{Z})\times\mathbb{Z}$ does not map $(\prod\mathbb{Z})\times\{0\}\times\{0\}$ to $(\prod\mathbb{Z})\times\{0\}$; so you do not know that you are taking quotients modulo "the same thing"; that is, you have an isomorphism $\phi\colon G\to K$; and subgroup $N\triangleleft G$ and $M\triangleleft K$ with $N\cong M$; but unless $\phi(N)=M$, you cannot use $\phi$ to conclude $G/N\cong K/M$; yet you are trying to do so here.
Comment: This is basically the same as arguing $\infty +1 = \infty$; subtracting $\infty$ from both sides, $1=0$.
Comment: What's so special about $\mathbb Z$? Haven't you just proved $G\cong G\times G$ for **every** group $G$? If $G$ is a group of order $n$, does that mean that $n^2=n$ for every $n$?
Comment: You are not working within a field structure. This you can't use cancellation.
Answer: Quotienting by isomorphic copy need not preserve isomorphisms.  For a simpler related example: $C_n=\mathbb{Z}/n\mathbb{Z}$ and $m\mathbb{Z}\cong n\mathbb{Z}$ for all $m,n>0$, but obviously the cyclic groups $C_m$ and $C_n$ are not isomorphic if $m\neq n$.
Comment: @student: If you are not using an isomorphic copy, then it is wrong to write $G/ \prod_{1}^{\infty} \mathbb{Z} \cong \mathbb{Z}$, because you only have $G \cong (\prod_{1}^{\infty} \mathbb{Z}) \times \mathbb{Z}$, not $G = (\prod_{1}^{\infty} \mathbb{Z}) \times \mathbb{Z}$
Comment: @student: You already know an example: the one you found in your question!
Comment: Quotient here is not by isomorphic copy. I am using the fact that factors are normal subgroups, and then using the first isomorphism theorem.  The example you gave has no such product structure.
Comment: I think that might be it, but I can't see the subtlety here. What's the difference between $=$ and $\cong$ here? If I have $G\cong H \times K$, can i not say $G/H \cong K$? Why, an example?
Comment: @student: If you have $\varphi\colon G\xrightarrow{\cong}H\times K$, then $G/\varphi^{-1}(H\times\{1\})\cong K$.  However, if you have $\psi\colon H\hookrightarrow G$ or even $\psi\colon H\times K'\xrightarrow{\cong}G$, there is no reason to expect $G/\varphi(H\times\{1\})$ and $G/\psi(H)$ to be isomorphic or even one to be a homomorphic image of the other.
Comment: An example is $G=(C_2)^\omega\times(C_3)^\omega$, where you have $(C_2)^\alpha\times(C_3)^{\beta}$ for every $\alpha,\beta\leq\omega$ as the complement (and quotient) of an isomorphic copy of $G$ in $G$, since $n+\omega=2\omega=\omega$ for all $n<\omega$, but clearly there are no nontrivial homomorphism between $C_2$ and $C_3$.
Comment: However, under some stringent conditions, [$G\times H\cong G\times K$ implies $H\cong K$](https://math.stackexchange.com/questions/1724232/g-times-h-cong-g-times-k-implies-h-cong-k?rq=1).
Answer: Your argument is based on the assumption that $G/N_1\cong G/N_2$ follows from $N_1\cong N_2$. Since $\mathbb Z\not\cong\mathbb Z\times\mathbb Z$, your example shows that the assumption is incorrect. Here is a simpler example.
The non-isomorphic groups $\mathbb Z_4$ and $\mathbb Z_2\times\mathbb Z_2$ are both homomorphic images of the group $G=\mathbb Z_2\times\mathbb Z_4$. Thus there are subgroups $N_1,N_2$ of $G$ such that $G/N_1\cong\mathbb Z_4$ and $G/N_2\cong\mathbb Z_2\times\mathbb Z_2$. The subgroups $N_1$ and $N_2$ are isomorphic, as they are groups of order $2$;
so $N_1\cong N_2$ but $G/N_1\not\cong G/N_2$.
P.S. In other words (considering your comment on another answer, "If I have $G\cong H\times K$, can i not say $G/H\cong K$?"): here we have $G\cong N_2\times\mathbb Z_4$, but $G/N_2\not\cong\mathbb Z_4$.


Distribution of $e$ if $g=\tilde{g}+e$, $g=|f|$, $f \sim \mathcal{N}(0,1)$ and $\tilde{g}$ is the quantization of $g$

Question: Let $f \sim \mathcal{N}(0,1)$ be a normal random variable with zero mean and unit variance.  Let $g=|f|$.
Let $\tilde{g}$ be the quantization of $g$. We suppose that there are $n$ possible levels of $\tilde{g}$, denoted as: $\tilde{g}_1, \ldots, \tilde{g}_n$. These levels are fixed beforehand.
The quantization is performed as the following: if $\tilde{g}_{i} \le g < \tilde{g}_{i+1}$, then the quantized level of $g$ is $\tilde{g}_{i}$. Note that if $g \ge \tilde{g}_{n}$, the quantization is $\tilde{g}_{n}$, and if $g < \tilde{g}_{1}$, then the quantization level is $0$.
We can represent $g$ as $g=\tilde{g}+e$, where $e$ can be seen as the quantization error.
My question: what is the distribution of $e$ in this case ?
Comment: @dln In respect of your earlier comment to whuber, a simple google search on *binning* gives me these as the top two hits: [one](https://docs.tibco.com/pub/spotfire/6.0.0-november-2013/userguide-webhelp/bin/bin_what_is_binning.htm), [two](https://en.wikipedia.org/wiki/Data_binning). We also have a [binning](http://stats.stackexchange.com/tags/binning/info) tag.
Comment: Please explain what you mean by a "quantization." It sounds like the same thing as *binning*. Even then, an important issue is whether the cutpoints between the bins were selected beforehand or are based on data.  Finally, you might be interested in how a "quantized" version of a Normal distribution can be used to generate uniformly distributed variates, as I describe in item (8) of a post at http://stats.stackexchange.com/a/117711.
Comment: @whuber thank you for your valuable comment. Question edited.. I have no idea what is "binning"
Comment: 1. So you have some set of bins and then label the values in each bin by the left end of the bin, except that in the lowest bin you use $0$ instead of $-\infty$ as the label? (which implies you expect half your quantized values will be $0$). $\,$ 2. I think you probably want $n$ instead of $i$ in "Note that if $g\geq \tilde{g}_{i+1}$...."
Comment: @Glen_b I edited the question. Now we use $g=|f|$. Thank you!
Comment: I hope this assumption won't complicate the problem
Comment: are those levels equispaced?
Comment: @Glen_b We can assume that  the levels are equispaced if this can simplify the problem.
Answer: The density of $g$ is indeed $2\phi(x)1(x\geqslant 0)$. Let us agree that $\tilde{g}_0=0$ and that $\tilde{g}_{n+1}=+\infty$. The density of $e$ can then simply be obtained by the law of total probability. For $y\geqslant 0$:
\begin{align*}
 f_e(y)dy & = \text{Prob}[y\leqslant e<y+dy]\\
  & = \sum_{i=0}^n \text{Prob}[y\leqslant e <y+dy, \tilde{g}_i\leqslant g < \tilde{g}_{i+1}]\\
  & = \sum_{i=0}^n \text{Prob}[\tilde{g}_{i} + y \leqslant g < \tilde{g}_{i} +y+dy] \ 1(0\leqslant y < \tilde{g}_{i+1} - \tilde{g}_i)\\
  & = \sum_{i=0}^n 2\phi(\tilde{g}_{i} + y) dy \ 1(0\leqslant y < \tilde{g}_{i+1} - \tilde{g}_i)\,.\\
\end{align*}
So,
$$
  f_e(y) = \sum_{i=0}^n 2\phi(\tilde{g}_{i} + y) \ 1(0\leqslant y < \tilde{g}_{i+1} - \tilde{g}_i)\,.
$$
Answer: So e is the difference of two (dependent) random variables, meaning $f_E(e) = \int_{-\infty}^{\infty} f_{G \tilde{G}}(g, g - e) dg $. The distribution of g is simply $2 \phi(x) \mathbb{1}(x > 0) $ where $\phi$ is the standard normal p.d.f. It gets a little more complicated from there, especially as $g$ and $\tilde{g}$ are dependent, but I figured I'd get it started.


setgid on samba share not working with Mac OS X

Question: I've set the setgid-bit on folders within my samba-share. It works like a charm for windows and linux clients.
Accessing such a folder with a mac-client the setgid is ignored and the group permission of the newly created files/directories is set to the current users default group.
I've tried the the setting unix extensions = no mentioned on this post but this doesn't work.
Answer: One thing you can do to force the created files in a share to always belong to a certain group  is to use the force group = groupname option in the share configuration in smb.conf. If you want to make sure that only users who already belong to that group can create files use a + sign in front of the group name: force group = +groupname.
More info on the samba manual for smb.conf


Determine angle of triangle

Question: Given following problem:

I have 2 solutions:
First is to calculate difference in absolute angles, then renormalize angle. bad idea, 2 x atan2() is slow, renormalisation is inefficient.

angle = clamp_to_range( atan2(P1.y, P1.x) - atan2(P0.y, P0.x));

Second is to calculate dot product, normalize, calculate arccos(). Also bad idea, because angle sign will be incorrect.

angle = acos( dot(P0, P1) / sqrt( dot(P0,P0) * dot(P1, P1) ) );

I feel, that there should be some formula. How to solve given problem efficiently?
Comment: @Yves Daoust My apologies. I was too hurry, missed that you already had given key moments, and wrote my answer automatically. (cannot delete accepted answer now)
Comment: @Mbo Yours is better. It has some illustration code (without one closing bracket at the end). And his answer dont even mention parameter order for cross product, thus was considered lower quality. I asked him to correct, he deleted his answer because of, citing, "setting acceptance conditions was unacceptable" to him.
Answer: It is possible to use only one atan2 but both cross product and scalar product of vectors:
angle = atan2(Cross(P0, P1), Dot(P0, P1);

Answer: Do you really need the angle in radians / degrees, instead of as a unit vector or rotation matrix?
An xy unit vector can represent angle instead of absolute direction; the angle is the angle between the vertical (or horizontal) axis and the unit vector.  Trig functions are very slow compared to simple multiply / add / subtract, and still slow compared to div / sqrt, so representing angles as vectors is usually a good thing.
You can calculate its components using the Cross(P0, P1) and Dot(P0, P1), but then normalize them into an xy unit vector instead of using atan2 on them.
See also Rotate Object Towards Direction in 2D on gamedev.SE, and Is it better to track rotation with a vector or a float?

This is easy to vectorize with SIMD, much moreso than a SIMD atan2.  rsqrtps exists mostly to speed up x *= 1.0 / sqrt(foo) (and reusing the same multiplier for a SIMD vector of y values) for normalization.  But rsqrtps is very low accuracy so you often need a Newton Raphson iteration to refine.  The most recent CPUs (Skylake) have good FP sqrt / div throughput, so you could just normalize the naive way with _mm_sqrt_ps and leave optimization for later.  See Fast vectorized rsqrt and reciprocal with SSE/AVX depending on precision.

Determine angle of triangle


Store and Change dinamically TCP Port in SQL Connection String

Question: I handle Sql 2014 Express and this eventually changes the TCP Dynamic Port. Since the applications of vb.net need to have a connectionString, it would be laborious to be adjusting the already compiled exe programs, each time the TCP port included in the conectionstring of my applications changes in the company network. How can I store a connectionstring in the local network in a single point so I can modify it when I change the tcp port to eventually restart the sql server? In such a way that the vbnet applications access by network to a single point where the connectionstring is stored? What is the best technique in these cases?
Comment: Configure it to use fixed port
Comment: https://learn.microsoft.com/en-us/sql/tools/configuration-manager/tcp-ip-properties-ip-addresses-tab?view=sql-server-2017
Answer: As long as you are running the SQL Server Browser service, you won't need to know the port number, just the instance name.
Comment: The problem is: Some pc don't detect de Instance by name: SERVER\INSTANCE, then in that cases we need to use instead: SERVER, PORT.   So, the problem is that in some cases the only way to connect from certain PCs is to use the specific TCP port, and that is where the inconvenience of the changing port arises.
Comment: you can use fixed port if that is the case but i would double check that the browser service is running, directing to the correct port is its main purpose


From binary image to shapefile

Question: I'm developing a C++ application for image processing. I use OpenCV. I want to detect the coordinates of lines and polygons in my images to generate shape files in .shp format. My images are binary images that contain lines and polygons. My goal is to detect the lines and polygons and then generate a shape file that will contain them. I don't know how to do this so I'm turning to you. Can someone help me?
Answer: I can retrieve the coordinates of my lines and polygons in my image. The problem is that I don't know how to convert them into geographical coordinates (lat/long).

From binary image to shapefile


Question regarding $\int _{-\infty}^{\infty} \cos(ax)\, dx$ and the improper integral of even functions

Question: Consider the integral of the cosine function
$$\int_{-\infty}^{\infty} \cos(ax)\, dx.$$
The property for an even function $f(x)$ is that $$\int_{-a}^{a} f(x)\,dx= 2\int_{0}^{a} f(x)\,dx.$$
However cosine doesn't have a limit at $\infty$ and $-\infty$.  Is it fair to say that it doesn't converge to a constant value?  People don't have problem saying that summing over sine equals zero because it's an odd function, even though it doesn't converge at infinity either:
$$\int_{-\infty}^{\infty} \sin(ax)\, dx = 0$$
Is it true that an even function $f(x)$ must have a limit at infinity for $$\int_{-\infty}^{\infty} f(x)\,dx= 2\int_{0}^{\infty} f(x)\,dx$$ to be true?
Comment: This limit does not converge
Comment: Who are all these people who have "no problem" saying that $\int_{-\infty}^{\infty} \sin(ax) dx$ has a value?
Comment: does that mean the integral doesn't have a value?
Comment: "...doesn't have a value".  Yes it does mean that. By definition, $\int_0^{\infty } ~f(x)dx = \lim_{b \to \infty} ~ \int_0^b ~f(x) dx.$  Consider the integral as the area under the curve.  If, as $b \to \infty$, $f(b)$ does not go to $0$, then the area under the curve **can not stabilize**.  Under this scenario, the integral **can't have a value.**
Comment: Re my previous comment, $f(b)$ going to $0$, as $b \to \infty$, although a *necessary* condition for a "convergent" integral, is **not** in general a **sufficient** condition.  The classic example is $\lim_{b\to\infty} \int_1^b ~(1/x) dx.$
Answer:
People don't have problem saying that summing over sine equals zero because it's an odd function

No, they absolutely do have a problem saying that. There is a fact which may at first glance sound like that (see below), but it's quite different.
I think it's worth going back and thinking about the $\sin$ example. Contra your claim, the expression $$E:\quad\int_{-\infty}^\infty \sin(x)dx$$ is undefined. What is true is that for every real number $a$ we have $$\int_{-a}^a\sin(x)dx=0,$$ and so consequently $$\lim_{a\rightarrow\infty}\int_{-a}^a\sin(x)dx=0.$$ However, that's not enough to conclude that the expression $E$ above actually makes sense. You need to go back to the definition: we have $\int_{-\infty}^\infty f(x)dx=k$ iff for all $\epsilon>0$ there are $a<b$ such that for all $a'<a$ and $b'>b$ we have $\vert k-\int_{a'}^{b'}f(x)dx\vert<\epsilon$. Note how the upper and lower bounds of the integral are not a priori related to each other; the fact that we always get $0$ when they match up is not enough to tell us that $E$ actually makes sense.
So there's no difference between $\sin$ and $\cos$ in this situation: for each of them, none of the various integrals involving $+\infty$ or $-\infty$ are actually well-defined.
Comment: @pico I upvoted and agree with Noah Schweber's answer.  However, I would have expressed it differently.  When considering $\int_{-\infty}^{\infty} ~f(x)dx$, where $f(0)$ is well defined, then **regardless** of whether $f(x)$ is an odd (or even) function, you have to consider the two integrals $\lim_{a \to \infty} \int_{-a}^0 f(x) dx$ and $\lim_{b \to \infty} \int_0^b f(x) dx$ **separately**.  Each (improper) integral is expressed as a limit.  The only way for the *combination* of the two integrals to permit a specific value is if **each** of the two limits are **individually** convergent.
Answer: Recall the definition of improper Riemann integrals:

If $f$ is Rieman integrable in any interval $[0,b]$, then $f$ is (improperly) integrable in $[0,\infty)$ if
$I=\lim_{b\rightarrow\infty}\int^b_0 f(x)\,dx$ exists and in such case, the $\int^\infty_0 f(x)\,dx:=I$

One way to convince yourself that $\int^\infty_0\cos (x)\,dx$ (drop $a$ for simplicity) diverges is as follows:
If the interval existed and had value $I$ (as an improper integral) then in particular we would have
$I=\lim_{n\rightarrow\infty}\int^{n\pi}_0\cos x\,dx$
Now,
$$
\begin{align}
\int^{n\pi}_0\cos x\,dx &=\sum^n_{k=1}\int^{k\pi}_{(k-1)\pi}\cos x\,dx\\
&=\sum^n_{k=1}(-1)^k=(-1)^n
\end{align}
$$
which does not converge.

For a function $f$ to be integrable (as an improper Riemann integral) over an infinite interval, it is not needed for $f$ have a limit as $x\rightarrow\infty$ or $-\infty$. Here is one example:
$f(x)=n$ if $n\leq x\leq n+\frac{1}{n^3}$ for some $n\in\mathbb{N}$, and $0$ anywhere else.
In this case, one can check that
$\int^\infty_{-\infty}f(x)\,dx =\sum^\infty_{n=1}\frac{1}{n^2}<\infty$.
Yet $\lim_{x\rightarrow\infty}f(x)$ noes not exists.
Answer: I think it is best to use the definition of a limit. We say that $\lim_{x\to\infty}f(x)$ exists if $\exists L\in \Bbb{R}$ such that given any $\epsilon>0$, $\exists M\in\Bbb{R}$ such that $|f(x)-L|<\epsilon ~ \forall x>M$. It is easy to show that no periodic function can satisfy that definition. $\sin$ is the antiderivative of $\cos$, so we can conclude $\int_{\Bbb{R}}\cos(x)\mathrm{d}x$ doesn't exist since $\sin$ has no limit.


Is there any common unique id or variable existing in Facebook and Twitter (like email)?

Question: Is there any common unique id or variable existing in Facebook and Twitter like email id? .Currently i developing a social game ,which can login with Facebook , Twitter and  using email id.
Problem is
1.Facebook provide email but Twitter
2.Facebook and Twitter provides id , but both are different not same value
Comment: No, there is no overall identifier. Even the email you get from different platforms might be different, simply because the user might have used  different emails to sign up for those platforms.
Comment: Thank you CBroe  for your reply , anybody have any idea
Answer: There is no unifying link between Facebook accounts and Twitter accounts. As stated in the comment by @Cbroe even using e-mail is not a valid link since they could use different e-mail address on different accounts.
You will have to allow the user to authenticate to both in order for you to internally track which of your users belongs to each Facebook/Twitter account.


How to Handle SSL Certificate in karateUI driver?

Question: When I open my resource, I am faced with notification "Your connection is not private".
   Is there a way to disable the verification of the server certificate in the browser or specify the desired trusted certificate through configuring the karate driver?
  Please, provide the solution for configuration the driver for overcome this notification.
Answer: This is helpful feedback. Can you see if adding this command-line flag helps: --ignore-certificate-errors.
Refer addOptions in the documentation: https://github.com/intuit/karate/tree/develop/karate-core#configure-driver
Else it would be great if you provide a way to replicate and submit an issue: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
This will also work for other chrome options such as --disable-notifications.
Please also see these threads:
a) https://github.com/intuit/karate/issues/1134#issuecomment-638990087
b) https://github.com/intuit/karate/issues/1228
Comment: Thank you, your recommendation helped. I added: configure driver = {type: 'chrome',addOptions:['--ignore-certificate-errors']} .


How to print first child - sibling structure

Question: I am trying to figure out how to print a first-child next sibling tree. What I want is the following:
root
|
firstChild - sibling - sibling
                       |
                       child - sibling - sibling

I have the following code to add childs and siblings :
class Program
{
    static void Main(string[] args)
    {
        GeneralTree<string> tree = new GeneralTree<string>();
        tree.root = new TreeNode<string>
        {
            Data = "Root"
        };
        TreeNode<string> child = tree.addChild(tree.root, "Child");
        tree.addSibling(child, "Sibling");
        tree.print(tree.root);
    }
}
class GeneralTree<T>
{
    public TreeNode<T> root;

    public TreeNode<T> addChild(TreeNode<T> parent, T data)
    {
        parent.FirstChild = new TreeNode<T>
        {
            Data = data,
            NextSibling = parent.FirstChild
        };
        return parent.FirstChild;
    }
    public TreeNode<T> addSibling(TreeNode<T> sibling, T data)
    {
        sibling.NextSibling = new TreeNode<T>
        {
            Data = data,
            FirstChild = sibling.NextSibling
        };
        return sibling.NextSibling;
    }

    int count = 0;
    public void print(TreeNode<T> Node)
    {

        if(Node !=null)
        {
            Console.WriteLine(Node.Data);
            print(Node.FirstChild);
            ++count;
            Console.WriteLine(count);
            print(Node.NextSibling);
        }
    }
}
class TreeNode<T>
{
    public T Data { get; set; }
    public TreeNode<T> FirstChild { get; set; }
    public TreeNode<T> NextSibling { get; set; }
}

Does anyone now how to print that out?
Thanks in advance!
Comment: Just a small example of how to print a tree
Comment: I described it above how i want to print it out
Answer: I choosed to merge TreeNode and GeneralTree in this way :
public class TreeNode<T>
{

    public T data;
    public List<TreeNode<T>> childs;

    public TreeNode<T> firstChild()
    {return childs.get(0);}

    public void appendChild(TreeNode<T> child)
    {childs.add(child);}

    public void print() {/* ... */}

    /* ... */

    public static void main(String args[])
    { /* ... */}
}

Then, a way to write print() recursively :
    public void print()
    {
        print(0);
    }

    public void print(int offset)
    {
        if (node == null) return; // nothing to print anymore

        System.out.println(this.data); // printing the root data

        TreeNode<T> lastChild=null;
        String output = "";
        for(Iterator<TreeNode<T>> i = childs.iterator(); i.hasNext(); )
        {
            lastChild = i.next();
            if (output != "") output += " - ";
            output += lastChild.data;
        }

        // length will be the next line offset
        // (size of the current line output minus last item length

        int length = output.length()-lastChild.toString().length;
        // use a repeat() string function like this one :
        output = org.apache.commons.lang.StringUtils.repeat(" ", length) + (length>0?"|":"") + output;
        System.out.println (output);
        lastChild.print(length);
    }

}

Unfortunately I can't validate my code right now, If you have issues, please let me know.
Comment: For the record, I use C# for coding this. I assume that my code is right qua structure, but the next thing I want to know is how to print it like a first child next sibling tree. If I print tree.root.FirstChild.NextSibling.Data I get the right sibling, so I think the code is not the problem, only the way how to print it out
Comment: Yes, you just have to check the print loop. What I understood is that you want to print all siblings, **then** last sibling's childs. Right? If you understand the process `(next offset = length(current_line) - length (lastSibling))`, you should be able to write your own function.
Comment: But in your case, each node could have more than 2 nodes because you use a list to store all its childs. That's not how a binary tree has to be constructed.
Comment: So why did you set up three childs in your print sample (first + two siblings)? Anyways, you can easily replace my `List` with what you want (`Node left`; `Node right;` for example). Just keep in mind that the main part is the `print` algorithm. (Also : I wrote in Java because you agreed the tag.)