Lógica: Como funciona um aplicativo de localização de amigos?

Question: estou estudando desenvolvimento mobile e me pintou uma dúvida: como funciona um app que localiza no mapa amigos em tempo real?
Exemplo: Um app que mostra no mapa onde estão seus amigos que tb tem o app, distancia em que eles estão e localização no mapa.
O app envia os dados de cada um para o servidor e este atualiza estes dados de tempos em tempos? Roda em background? Gostaria de entender esta lógica do funcionamento.
Abraços!
Answer: De maneira geral:

O app coleta de tempos em tempos via API de geolocalização as coordenadas de todos os usuários, e envia o resultado para um servidor central. Implementações podem variar, porém em geral um serviço é utilizado para a coleta.
Quando você acessa o app este faz uma requisição ao servidor - envie-me as coordenadas atuais dos usuários A, B, C, ..., Z, assim como suas distâncias relativas à minha.
Comment: Mas aí quando o usuário entra no app, e este solicita as coordenadas, o servidor pega a última localização armazenada dos amigos. Ele fica rodando em background nos dispositivos dos amigos (para enviar os dados nestes intervalos)?
Comment: @user3776181 Exatamente. De tempos em tempos o serviço instalado nos celulares dos amigos obtém um novo conjunto de coordenadas, e envia o resultado para o servidor central.
Comment: Exemplo de implementação: http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Comment: Não tenho experiência com Android/Java, estou programando pelo Phonegap. Mas olhando o código que passou de exemplo, dá pra entender como o sistema funciona! =D

Muito obrigado mesmo!
Comment: @user3776181 Sempre um prazer ajudar!


Need help comparing this series for a limit test

Question: I'm not sure what to compare the following series to. Would $\dfrac{1}{n^{\frac{3}{2}}}$ work?
$$\sum_{n=1}^\infty \frac{n^2-1}{n^4+2n+1}$$
Comment: Try limit comparison with $\sum \frac{1}{n^2}$.
Comment: $\frac{n^2-1}{n^4+2n+1}\le \frac{n^2-1}{n^4}=\frac 1{n^2}-\frac1{n^4}$. follows from comparison test.
Comment: You need to show some of your work.
Answer: I'm assuming you want to prove that the series converges. For $n\geq 1$ we have:
$$n^4+2n+1>n^4-1=(n^2-1)(n^2+1)$$ Hence
$$\sum_{n=1}^k \left|\frac{n^2-1}{n^4+2n+1}\right|=\sum_{n=1}^k \frac{n^2-1}{n^4+2n+1}<\sum_{n=1}^k\frac{n^2-1}{(n^2-1)(n^2+1)}=\sum_{n=1}^k \frac{1}{n^2+1}$$
Now we see that the last sequence converges as $k\to \infty$.
Comment: Ah I forgot I can factor too, thanks! Also is there a chance there can be another series I can compare to my original series?
Answer: Hint: $$\frac{n^2-1}{n^4+2n+1} < \frac{n^2}{n^4+2n+1} <  \frac{n^2}{n^4} = \frac{1}{n^2}.$$


Views removes style attribute in "Rewrite Results"

Question: I've got screenlists for videos and I need to put them into the div tag to as a background and then change bacgkround position with JS to show the preview. I've downloaded Image URL Formatter for this purpose and added code to "Rewrite Results" field of the field in my view:

But there is no such attribute "style" in rendered html of the page. Does Views module block it?
Comment: You could simply do this in a custom view template. I've done this and it works great.
Comment: +1 Indeed @DannyEnglander - as this answer details further: https://stackoverflow.com/a/43131240/227926
Answer: Yes, Views does block style attribute for security reasons. Class attribute is allowed.
Here's one long discussion about it https://drupal.org/node/853880 and some other ideas for workarounds Add style attribute to view fields.


What should we do when changing SGD optimizer to Adam optimizer?

Question: Adam is one popular method of the optimization policies with adaptive learning rate. I'm focusing on a image segmentation project using fully convolutional networks. All weights were initialized by truncated normal distributions. Initially, I used the Adam optimizer, and got some convergence of loss on both training sets and test sets with reasonable accuracies (say 0.8). But when I tried to use the SGD optimizer, the loss seems converged, but the accuracy is nearly zero. So my question is, when we adopted different optimizers, what do we need to change for successful network training? Weight initialization?
Answer: In my experience, changing optimizers is not a simple matter of swapping one for the other. Instead, changing optimizers also interacts with several other configuration choices in the neural network.

The optimizer interacts with the initialization scheme, so this might need to be changed.
The learning rate may need to be changed.
The learning rate schedule may need to be adjusted.
In some cases, SGD with momentum can be a big improvement over Adam. See: "The Marginal Value of Adaptive Gradient Methods in Machine Learning" by
Ashia C. Wilson, Rebecca Roelofs, Mitchell Stern, Nathan Srebro, Benjamin Recht

Adaptive optimization methods, which perform local optimization with a metric constructed from the history of iterates, are becoming increasingly popular for training deep neural networks. Examples include AdaGrad, RMSProp, and Adam. We show that for simple overparameterized problems, adaptive methods often find drastically different solutions than gradient descent (GD) or stochastic gradient descent (SGD). We construct an illustrative binary classification problem where the data is linearly separable, GD and SGD achieve zero test error, and AdaGrad, Adam, and RMSProp attain test errors arbitrarily close to half. We additionally study the empirical generalization capability of adaptive methods on several state-of-the-art deep learning models. We observe that the solutions found by adaptive methods generalize worse (often significantly worse) than SGD, even when these solutions have better training performance. These results suggest that practitioners should reconsider the use of adaptive methods to train neural networks.


Probability with two IID random variables

Question: Assume $X$ and $Y$ are two IID random variables with infinite support, I am interested in $P(X>a , X>Y+b)$ where $a$ and $b$ are two constants. Is there any family of distribution for X and Y where this probability has a close-form solution? I am a simple solution without integrals.
I tried Normal and Gumbel Distributions with no success. In both cases, $P(X>Y+b)$ is relatively simple, especially in Gumbel case, but not $P(X>a , X>Y+b)$.
Comment: Not to rain on your parade, but the uniform distribution satisfies your requirements. Whether or not that helps you depends on whether you're trying to prove non-existence or you're actually trying to do meaningful modeling.
Comment: My bad, I forgot to add that I am looking for a distribution with infinite support, just added that, I am really sorry for confusion
Answer: It depends on what you regard as as a family and as a closed form.
For example if $X,Y \sim U(0,k)$ and $0 < b < a< k$ then $$P(X>a,X>Y+b) = \frac { (k-b)^2}{2k^2} -\frac { (a-b)^2}{2k^2} = \frac{(k-a)(k+a-2b)}{2k^2}$$  as should be clear from
Comment: @AnonA Microsoft Paint
Comment: I agree with you completely. I am looking for a family in the non-precise way, e.g. normal or exponential. And the ones interesting here are the ones with infinite support. I had forgot to add that, terribly sorry
Comment: btw, a very beautiful graph, which software do you use?


jquery Mobile Upgrading

Question: I purchased a theme online, and I believe its using the older jquery mobile instead of the new one.
Right now in my header it looks like this:

    <meta content="initial-scale=1.0, user-scalable=no, minimum-scale=1, maximum-scale=1" name="viewport" >
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="apple-mobile-web-app-capable" content="yes">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/images/touch/apple-touch-icon-144x144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/images/touch/apple-touch-icon-114x114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/images/touch/apple-touch-icon-72x72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="assets/images/touch/apple-touch-icon-57x57-precomposed.png">
    <link rel="shortcut icon" href="assets/images/touch/apple-touch-icon.png">

    <link href="assets/images/splashscreens/apple-touch-startup-image-320x460.png" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 1)" rel="apple-touch-startup-image">

    <link href="assets/images/splashscreens/apple-touch-startup-image-640x920.png" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image">

    <link href="assets/images/splashscreens/apple-touch-startup-image-640x1096.png" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image">

    <link href="assets/images/splashscreens/apple-touch-startup-image-768x1004.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 1)" rel="apple-touch-startup-image">
    <link href="assets/images/splashscreens/apple-touch-startup-image-748x1024.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 1)" rel="apple-touch-startup-image">

    <link href="assets/images/splashscreens/apple-touch-startup-image-1536x2008.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image">
    <link href="assets/images/splashscreens/apple-touch-startup-image-1496x2048.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image">

    <link rel="stylesheet" href="assets/css/jquery.mobile.structure-1.0.1.min.css" type="text/css">

    <link rel="stylesheet" href="assets/css/jquery.mobile.1.0.1.min.css" />
    <link rel="stylesheet" href="assets/css/add2home.css">
    <link rel="stylesheet" href="assets/css/icons/icons.css" type="text/css" >
    <link rel="stylesheet" href="assets/css/icons/nav-icons.css" type="text/css" >
    <link rel="stylesheet" href="assets/css/flexslider.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="assets/css/style.css" type="text/css" >
    <link rel="stylesheet" href="assets/css/normalize.css">
    <link rel="stylesheet" href="assets/css/main.css">

    <link rel="stylesheet" type="text/css" href="assets/css/icons/nav-icons-black.css">

To upgrade it to the latest jquery mobile I tried adding these lines to the bottom part of the head but I I messed something up cause buttons became double. It seemed to mess with the css really baldy:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />

Answer: Of course you've to delete all the link to the older version of jQuery Mobile like:
<link rel="stylesheet" href="assets/css/jquery.mobile.1.0.1.min.css" />

Moreover, note that the ajax-loader image is no more a .png but a .gif

jquery Mobile Upgrading


Trace of log of matrix

Question:
How to prove that $$\operatorname{Tr}(\log B) = \sum_i \log b_i \tag{1}$$ where the $b_i$ are the eigenvalues of matrix $B$?

Question background:

This question arises from quantum field theory in particle physics. Where $B$ is $i\not\partial - m$ in continuous Hilbert space(this space of four dimensional spacetime). And $\not\partial=\partial_{\mu}\gamma^{\mu}$, $\gamma^{\mu}$ is four dimensional Dirac Gamma matrix, there also a four dimensional identity matrix with $m$. You can specify this as each point in Hilbert space, there is a four dimensional matrix, or each element of B is a four dimensional matrix in Hilbert space;

About logarithm of matrix definition, I use Peskin and Schroeder's QFT book, they define the logarithm of matrix as Taylor series expansion.

Below is my navie attempt (sorry for my insufficient math knowledge), suppose $B$ can be diagonalized as:
$$B = U^{-1}\Lambda U \tag{2}$$
where $U$ is some unitary matrix and $\Lambda$ is diagonal matrix. Then
$$\operatorname{Tr} (\log B) = \operatorname{Tr} (\log (U^{-1}\Lambda U)) \tag{3}$$
I expect that
$$ \operatorname{Tr} (\log (U^{-1}\Lambda U)) = \operatorname{Tr} (\log (\Lambda)) \tag{4}$$
But how to proceed from ($3$)?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: @JoséCarlosSantos Thank you very much, I re-edit my question!
Comment: How are you defining $\log B$? Also, is $B$ normal, self-adjoint, positive-definite? Real, or complex? I notice that you assume $U$ is unitary, so it suggests normality at least, and probably a complex matrix, but it would be good to confirm.
Comment: I'm still not sure how you're defining the logarithm of a matrix. If it's in the [continuous functional calculus](https://en.wikipedia.org/wiki/Continuous_functional_calculus) sense, then one can show that the process of diagonalising a normal matrix, applying $\log$ to each eigenvalue, and stitching the matrix back up satisfies the definition of the continuous functional calculus. This would $\log(U^{-1} \Lambda U) = U^{-1} \log(\Lambda) U$ follows immediately. Or maybe you're defining $\log B$ with a Taylor series? In that case, there are questions of convergence to worry about.
Comment: If $\{b_k\}$ are the eigenvalues of $B$ then the eigenvalues of $f(B)$ are given by $\{f(b_k)\}$ for any analytic function $f$.  The definition of the trace is the sum of the eigenvalues, therefore
$$Tr\big(f(B)\big) = \sum_kf (b_k)$$ The only issue to worry about is whether the function is single-valued on the original eigenvalues.
Comment: @TheoBendit Thanks for your comment, I will re-edit my question!
Comment: @TheoBendit Thanks for your comment, actually, this come from a theoretical physics question. I apologize not offer enough information. I will re-edit my post!
Answer: Let's say you have a complex function $f$ defined by a power series centred at some point $z_0 \in \Bbb{C}$, converging on some open disc $D$ centred at $z_0$. That is,
$$f(z) = \sum_{n=0}^\infty a_n (z - z_0)^n$$
for all $z \in D$, for some sequence of coefficients $(a_n)$. We can then extend this definition to certain $m \times m$ matrices, by defining:
$$f(B) = \sum_{n=0}^\infty a_n (B - z_0I)^n.$$
Now, there is a matter of convergence here. The above will not necessarily converge for all matrices; it depends on the original series, or more precisely, its region of convergence. But, let's brush over that, and suppose that $f$ is not only well-defined at $B$, it is also continuous (the latter is not an unreasonable assumption).
Then, if $U$ is an invertible $m \times m$ matrix, we have:
\begin{align*}
U^{-1} f(B) U &= U^{-1} \left(\sum_{n=0}^\infty a_n (B - z_0I)^n\right) U \\
&= U^{-1} \left(\lim_{N \to \infty} \left(\sum_{n=0}^N a_n (B - z_0I)^n\right) \right) U \\
&= \lim_{N \to \infty} \left(U^{-1}\left(\sum_{n=0}^N a_n (B - z_0I)^n\right) U\right) &\text{since $A \mapsto U^{-1} A U$ is continuous} \\
&= \lim_{N \to \infty} \left(\sum_{n=0}^N a_n U^{-1}(B - z_0I)^n U\right) &\text{since $A \mapsto U^{-1} A U$ is linear} \\
&= \lim_{N \to \infty} \left(\sum_{n=0}^N a_n \left(U^{-1}(B - z_0I)U \right)^n \right) &\text{since $(U^{-1} A U)^n = U^{-1} A^n U$, by induction} \\
&= \lim_{N \to \infty} \left(\sum_{n=0}^N a_n \left(U^{-1}BU - z_0I \right)^n \right) & \text{linearity again, and $U^{-1} I U = I$}\\
&= \sum_{n=0}^\infty a_n \left(U^{-1}BU - z_0I \right)^n = f(U^{-1} B U)
\end{align*}
This will work when $f$ is any Taylor series for the natural logarithm. All that is assumed is that $f(B)$ exists. If we assume $U$ diagonalises $B$, and take the trace of both sides, we get $(D)$, as required.
Answer: The formula you seek to demonstrate is nothing but the formula for the determinant of the matrix exponential inversed.
Let $A$ be a $n\cdot n$ matrix, then
$$\det(\exp A) = \exp(\operatorname{Tr} A)$$
If we define $B = \exp(A)$, we obtain,
$$\ln(\det B) = \operatorname{Tr}(\ln B)$$
Since the determinant is independent of the base in which it is computed, we can compute it in a diagonal basis of eigenvalues $b_i$ (assuming $A$ is diagonalizable and its eigenvalues have no multiplicities), and then $\det B = \prod_{i= 1}^{n} b_i$, and therefore we obtain your formula.

Trace of log of matrix


Adding a user on .htpasswd

Question: I am using .htpasswd to password protect certain directory on my server. However, I noticed that everytime I do this sudo htpasswd -c /etc/apache2/.htpasswd newuser my current contents of .htpasswd will be overwritten. Every directory of my site has their own user on .htpasswd.
How can I not overwrite instead add a new user on my .htpasswd?
Answer: Exact same thing, just omit the -c option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
Comment: Good gracious! Never thought that switch is the answer, pardon my innocence.
Comment: However, it won't let me modify the existing `.htpasswd` it insists the use of `-c` switch.
Comment: @fishcracker What's the error? `htpasswd /path/to/file username` is perfectly valid (syntactically anyway) and even the first example on the Apache docs.
Comment: My bad. I am trying to do `htpasswd -c /etc/apache2/.htpasswd newuser` in my CentOS server! Sorry, didn't notice I'm at the wrong window. Will accept your answer in 5 mins. Thanks!
Answer: FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.
Comment: Then just append the user:hash to a new line in the old file. This option is also valid for other cases, such as generating from one system to another without apache installed, but which can use apache's htpasswd file (such as lighttpd, for example)

Adding a user on .htpasswd


jquery match several values for data

Question: i'm having a bit of difficulty figuring this out,
i basically have the following:

...

...

...

...

and a list of checkboxes to filter:
<input type='checkbox' value='filter1' /> filter1
<input type='checkbox' value='filter2' /> filter2
<input type='checkbox' value='filter3' /> filter3

i want to be able to filter the LI list based on selected checkboxes, so for example, if I selected filter1+filter3 , I would only see  the 1st and 3rd li,
if i select filter1+filter2+filter3, i would only see the 1st li
i wrote this piece of code, but doesn't seem to do the job since obviously it matches them 1 at a time so starts showing previously hidden ones
thanks!
$('.categoriesOnly input[type=checkbox]').change(function() {
    $('.categoriesOnly input[type=checkbox]').each(function () {
        var filter = $(this);
       $("#category-articles .movie[data-theater*='" + filter.data('theater') + "']" ).show();
        $("#category-articles .movie").not("[data-theater*='" + filter.data('theater') + "']").hide();
}...

Answer: There are several problems  with your approach. The first main problem is your hide/show will only be based on the last checkbox in your loop of the checkboxes.
The next problem is you are only checking one value at a time, but you need to check for multiple matches.
Following creates an array of  the checked checkbox values, then filters out the LI's that match by creating arrays of each LI "filters" to compare to the array of checkbox values
var $checkboxes = $('.categoriesOnly :checkbox').change(function () {
    /* create array of allowed "filters" */
    var allowedFiltersArray = $checkboxes.filter(':checked').map(function () {
        return this.value
    }).get();
    /* hide all li then filter matches to show */
    $('li[data-type]').hide().filter(function () {
        /* if no chechboxes checked show all */
        if (!allowedFiltersArray.length) {
            return true
        }
        /* create array of filters for this li */
        var filters = $(this).data('type').split(' ');
        /* can't be a match if length of both arrays is different  */
        if (filters.length !== allowedFiltersArray.length) {
            return false
        }
        /* now do the matching of each array */
        var inValid = $.grep(allowedFiltersArray, function (filterValue) {
            return $.inArray(filterValue, filters) === -1;
        }).length;
        return !inValid
    }).show();

});

I assumed that if no checkbozes checked you would want to show all
DEMO
Comment: hello, thanks this seems a much better approach...never used map before, but seems you are checking for a match on all filters per item, basically i'd like to show the LI for any match (not all of them)
Comment: that conflicts a bit with example you gave
Comment: ah sorry, my bad, actually that worked perfectly...but i removed the full match when u check the length of both arrays
Answer: I don't know if it is possible in your scenario, but if your filter checkboxes were placed before the list items, you could use a combination of General Sibilings and Attribute selectors.
Then you would get a nice, css-only approach. Something like:
li[data-type] {
    display: none;
}

input[value="filter1"]:checked ~ ul li[data-type~="filter1"] {
    display: block;
}

input[value="filter2"]:checked ~ ul li[data-type~="filter2"] {
    display: block;
}

input[value="filter3"]:checked ~ ul li[data-type~="filter3"] {
    display: block;
}

http://jsfiddle.net/02j4vnc3/1/
No JS means a lighter solution! Less headache for you

jquery match several values for data


Methods of List comprehension, join a list with a different string at set intervals. (language agnostic)

Question: I'm interested in possible ways that different languages can Join an array, but rather than using a single join string, using a different join string at given intervals.
For example (hypothetical language):
Array.modJoin([mod, char], ...)
e.g. [1,2,3,4,5].modJoin( [1, ","], [2, ":"] )

Where the arguments specify an array or object containing a modulo and a join char, the implementation would check which order of modulo took precedence (the latest one), and apply the join char. (requiring that the [mod,char]'s were provided in ascending mod order)
i.e.
if (index % (nth mod) == 0)
  append (join char)
  continue to next index
else
  (nth mod)-- repeat

when complete join with ""

For example, I've come up with the following in Ruby, but I suspect better / more elegant methods exist, and that's what I'd like to see.
#Create test Array
#9472 - 9727 as HTML Entities (unicode box chars)
range       = (9472..9727).to_a.map{|u| "&##{u};" }

Assuming we have a list of mod's and join chars, we have to stipulate that mods increase in value as the list progresses.
mod_joins   = [{m:1, c:",", m:12, c:"
"]

Now process the range with mod_joins
processed = range.each_with_index.map { |e, i|
  m = nil
  mods.reverse_each {|j|
    m = j and break if i % j[:m] == 0
  }
  # use the lowest mod for index 0
  m = mods[0] if i == 0
  m = nil ? e : "#{e}#{m[:c]}"
}

#output the result string
puts processed.join ""

From this we have a list of htmlEntities, separated by , unless it's index is a 12th modulo in which case it's a

So, I'm interested for ways this can be done more elegantly, primarily in functional languages like Haskell, F#, Common Lisp (Scheme, Clojure) etc. but also cool ways to achieve this in general purpose languages that have list comprehension extensions such as C# with Linq, Ruby and Python or even Perl.
Answer: Here's a pure-functional version written in Python. I'm sure it can be adapted easily enough to other languages.
import itertools

def calcsep(num, sepspecs):
  '''
    num: current character position
    sepspecs: dict containing modulus:separator entries
  '''
  mods = reversed(sorted(sepspecs))
  return sepspecs[next(x for x in mods if num % x == 0)]

vector = [str(x) for x in range(12)]

result = [y for ix, el in enumerate(vector)
            for y in (calcsep(ix, {1:'.', 3:',', 5:';'}), el)]

print ''.join(itertools.islice(result, 1, None))

Comment: I'll go out on a limb here and say that Ruby seems to be able to do it a bit cleaner, also I didn't really mean port my implementation to another language, while losing brevity, I meant use novel features of the language to improve the readability of the routine.
Comment: It can do it more concisely and tersely. "Cleaner" is usually a matter of taste.
Comment: Of course, it's definitely a matter of taste, for example, my `do something if condition` is a bit of a perlism. I meant cleaner as in not having to reverse the mods explicitly and then process them.
Comment: I suppose without the usage directly underneath, it's looking better (my initial reaction was at a glance.) Excuse me.
Comment: by the way, it's not a separator, it's a concatenator. So the names  `joinspecs` and `concatentator` (or similar are more on point)
Comment: Equally, `num: array index position`
Comment: [Python calls it a separator](http://docs.python.org/2/library/stdtypes.html#str.join), so I maintained that terminology.
Comment: Ah, I see, the array is passed to the string method.
Comment: As for the "porting" bit, I didn't even look at your code before writing this; call it "homogenous convergence".
Comment: If you've got it in you, I'd love to see a more concise / terse implementation.
Comment: I can make it more concise by inlining everything, but writing terse Python is... harder than it looks.
Comment: I don't doubt it ("homogenous convergence") what I'm really interested in is if a language like Haskell has this sort of thing licked, or if it's still really a `.map` job.
Comment: If it's essentially the same implementation, not to worry. (definitely didn't mean to offend with the porting remark, just trying to clarify what I'm seeking.)
Comment: One could be clever and write code that uses stepped slice assignment to replace the appropriate separators, but I would be hard-pressed to call that an improvement over the functional version.
Comment: I see, the main "clean" part is about semantics when it comes to list comprehension, `for` is appearing a lot, where Ruby (lisp, linq, etc.) have a lot special purpose of enumerators. They all boil down to the same thing of course, although each one method can be optimised for their specific case in the compiler/interpreter. This is the interesting bit, for me at least.
Comment: Yes, that doesn't really sound like an improvement. The functional version is the way to go.
Comment: Hope you see @akuhn's answer, it's things like this that make Ruby very nice.
Comment: It's nothing that couldn't be done in Python, except `each_slice()` becomes [zip-iter](http://stackoverflow.com/q/2233204/20862).
Comment: Oh, very nice. Is this the stepped slice you referred to?
Comment: Have to say, the Ruby is eminently more readable, and also module imports, just core library.
Comment: No, stepped slice assignment is `foo[n::m] = someseq`. `zip()` will take one from whatever is there; 3 will result in 3 taken, 5 will result in 5, etc.
Answer: Here's a simpler and more readable solution in Ruby
array = (9472..9727).map{|u|"&##{u};"}
array.each_slice(12).collect{|each|each.join(",")}.join("
")

or for the general case
module Enumerable
  def fancy_join(instructions)
    return self.join if instructions.empty?
    separator = instructions.delete(mod = instructions.keys.max)
    self.each_slice(mod).collect{|each|each.fancy_join(instructions.dup)}.join(separator)
  end
end

range = (9472..9727).map{|u|"&##{u};"}
instructions = {1=>",",12=>"
"}

puts array.fancy_join(instructions)

Comment: Very nice work, I had no idea `each_slice` existed. This looks like a probably Green tick, I'll wait until tomorrow to see if there's anything better. I think it's unlikely though. And this automatically takes care of the index 0 problem.
Comment: @slomojo `each_slice` and its sibling `each_cons` are very powerful indeed. I've added code to cover the general case.
Comment: Thanks, I was just about to come back and ask for the mulitiple arguments case.
Comment: If you were going to add `instruction.empty?` you should thrown an error, rather than doing a regular join.
Comment: Yes and yes. You need to anchor the recursion, either by testing for being at the end of your instructions or by testing for slices of length 1 using `return self if self.size == 1` (though in that case your instructions MUST provide a separator for mod 1, so for example `array.fancy_join(4=>",",12=>";")` would not work while it works with above code).
Comment: Yep, just noticed the recursion, scuse me.
Comment: That's a slight problem with the mod 1, but not difficult to fix.


Dynamically generate an Action

Question: I'm trying to work out how to dynamically create an Action at runtime but coming up short.
Let's say I want to call a method and pass in a dynamically created Action so I can track whether the Action has been invoked etc (for whatever reason).
void DoSomething(Action<string> action);

That's the method I'm going to invoke and I want to somehow dynamically build an Action that'll satisfy the parameter.
I know I could just build one using new Action<string>((s) => { });
But for this case I don't know at compile-time the signature of the Action and all I want is a super-generic Action that'll let me know if it's been invoked.
This is part of a communication system for a project and I want to be able to support Actions being usable (think an OnCompleted callback).
Proxy.DoSomething((s) => Console.WriteLine("The server said: " + s);

I want to be able to generate a representation, shoot that over the wire, create an Action dynamically on the server, invoke the method on the object and pass in my dynamic action, send the result back to the client and invoke the actual action there.
A little clarification:
Client Side:
var proxy = GetProxyObject(); // Comms proxy
proxy.DoSomething((reply) => Console.WriteLine("Server said: " + reply));

Underneath:

Discover the signature of the Action
Build an internal representation object (easy enough)
Send that over the wire to the server

Server Side:
void ReceivedMessage(msg)
{
   var actParam = msg.Parameters[0]; // This is obviously just for demonstration
   var action = BuildActionWrapper(actParam);
   var result = target.InvokeMethod("DoSomething", action.UnderlyingAction);

   // Send result and Action result back to client
   ReplyToClient(...);
}

void DoSomething(Action<string> act)
{
   act("HELLO!");
}

Then back on the client side the parameters passed into the dynamically generated action on the server, the real action just gets invoked with those.
Answer: Here's an example of how you could build such an expression tree:
var mi = typeof(Console).GetMethod("WriteLine", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
var parameter = Expression.Parameter(typeof(string));
var body = Expression.Call(null, mi, new[] { parameter });
Expression<Action<string>> expression = Expression.Lambda<Action<string>>(body, new[] { parameter });

expression.Compile()("test");

As an alternative you could use Reflection.Emit to generate a delegate at runtime.
For example:
var dynMethod = new DynamicMethod("", null, new[] { typeof(string) });
var il = dynMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
var mi = typeof(Console).GetMethod("WriteLine", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
il.Emit(OpCodes.Call, mi);
il.Emit(OpCodes.Ret);

var dynDelegate = (Action<string>)dynMethod.CreateDelegate(typeof(Action<string>));
dynDelegate("test");

This will generate the following delegate:
(string s) => Console.WriteLine(s)

Comment: Couldn't it made just using expression trees...?
Comment: Sure, you could use expression trees as well. I have updated my answer to include an example of that.
Comment: So don't you find an overkill or even a bad idea using Emit instead of a simple and easy to understand expression tree? :D
Comment: In fact, check the tag in the question!!
Comment: Oops, you are correct. I didn't see the tag. Answer updated. Thanks.
Comment: I'm evil and I think that's a simpler way to get the whole expression tree.
Comment: That would be great if it didn't need the underlying access to the MethodInfo, I'm not looking to invoke a method at runtime, but to supply a standalone Action to one as a parameter.
Comment: Could I perhaps use an Expression.Block in place of the Expression.Call?
Comment: @DarinDimitrov Couldn't be simplified with just `Expression> expr = s => Console.WriteLine(s);`?
Comment: @MatíasFidemraizer, there's nothing dynamic in building the expression that way. You have statically hardcoded it and it must be known at compile-time.
Comment: @DarinDimitrov Yeah, but for the sake of dinamically creating an expression tree that's an action calling `Console.WriteLine`, you can use my suggestion. You get exactly the same expression tree.
Comment: That's true, but I thought that the whole point here was to generate the expression tree at runtime rather than hardcoding it.
Answer: Convert DoSomething signiture to the following;
void DoSomething<T>(Action<T> action, T parameter)
{
    action(parameter);
}

And call it like;
Proxy.DoSomething<string>((q) => Console.WriteLine("The server said: " + q, "some string");

Comment: Not sure if you've completely followed the question, the point isn't for me to be passing the "some string" to the server, that seems quite roundabout doesn't it? The 'q' comes from the server.
Answer: Ok,
So I've appeared to solve the problem to a degree, it's nasty and probably quite a way from how it should look.
    var mi = this.GetType().GetMethod("DoSomething");
    var actArg = mi.GetParameters()[0];
    var args = actArg.ParameterType.GenericTypeArguments;

    var lt = Expression.Label();

    List<object> values = new List<object>();

    var valVar = Expression.Variable(typeof(List<object>), "vals");
    var para = args.Select(a => Expression.Parameter(a))
        .ToArray();

    var setters = new List<Expression>();

    foreach (var p in para)
    {
        setters.Add(Expression.Call(valVar,
            typeof(List<object>).GetMethod("Add", new[] { typeof(object) }), p));
    }

    var block = Expression.Block(
        variables: new ParameterExpression[]
        {
            valVar,
        },

        expressions: Enumerable.Concat(para,
        new Expression[]
        {
            Expression.Assign(valVar, Expression.Constant(values)),
        }.Concat(setters)
        .Concat(new Expression[]
        {
            Expression.Return(lt),
            Expression.Label(lt),
        })));
    var l = Expression.Lambda(block, para).Compile();
    mi.Invoke(this, new object[] { l });

Basically, this builds a list to hold all the Action parameters the method sets in:
public void DoSomething(Action<string> act)
{
    act("Hello");
}

The parameters of the expression are built using the type arguments of the action and a number of setter expressions are built to add that particular parameter into the value list.
When run the expression assigns the values list as a constant to a variable it has, the setter expressions then add their values into the list and the expression returns.
The net result is that any Action can have an action dynamically generated and the results just chucked into a list, the list could then be sent across the wire from server to client and the values would be used on the client as the arguments to the actual action.

Dynamically generate an Action


How to keep URL parameters on subsequent pages after a form is submitted?

Question: I'm sending a referral form out to my email database and I've got it set up so that their email addresses get passed through and appended to the form URL like this:
http://email@example.com
I've got a hidden field in the form that collects the 'emailid' value and stores it with the responses so they can be matched up with our database.
That's working well, but once someone submits their form they're sent to a thank you page (http://www.holbrooktravel.com/referral-form/thank-you) where they can click a button to go back to the form and refer someone else.
I can't figure out how to keep their 'emailid' value on the 2nd referral so those submissions can be matched up as well. If I'm on the right line of thinking then I need to somehow keep the URL parameters on both the thank you page and the link sending them back to the referral form.
Any suggestions would be very much appreciated!
Comment: You can try with cookies. When you assigning email to hidden field at same time store email in cookie also. After that you can retrieve email from cookie on any page.
Answer: If you're able, and willing, to review/rework the current implementation you have for your webform submissions and the related "Thank you" page, you should consider getting the Rules module involved, e.g. to have the Rules module react to Rules event "After submitting a webform".
By doing so, you could then also use the Rules URL Argument module, which you can use to make the value of the URL argument available as new variable to Rules. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Ok so i've fixed it but i want to know how i can have all the value rows to show up if @custref is 9

Question:
Write an SQL command that generates a stored procedure named
  'spCustomerValue' that  returns the total value of orders from the
  OrderDetails table placed b y a customer whose  reference is passed in
  as a parameter.

use SKILLAGEITDB
go

alter proc spCustomerValue
(
@custref as  int
)
as
begin
select sum(value) as "total Value"

from orderdetails
where custref = @custref
end
go

exec  spCustomerValue  9
exec  spCustomerValue

Comment: perhaps try *create* instead of *alter*?
Comment: You will need to look at Itzik Ben-Gan's Books to learn TSQL,most of the things with your query is wrong  :http://tsql.solidq.com/
Comment: The only line after `as` should be `select sum(value) as "toast" from OrderDetails where custref = @custref`  Not the double select/assign thing you currently have.
Comment: Both answers below are correct, when executing the procedure, remember to pass in a custref value. Like this (or which ever custref you want) : `EXEC spCustomerValue 9`
Answer: Both the Select queries inside the procedures are wrong
select  @custref = custref from orderdetails

The above query will re-assign the @custref variable with arbitrary custref from orderdetails table.
select sum(value) as "toast"
from OrderDetails
where @custref = 9

In above query you have hard-coded the value 9 and check it with the @custref which is definitely wrong
You just need this
Alter proc spCustomerValue
(
@custref as  int
)
as
begin
    select sum(value) as "toast"
    from OrderDetails
    where custref  = @custref
End

Update : To show all values when @custref = 9 then change the Where clause like this
select sum(value) as "toast"
from OrderDetails
where custref  = @custref  OR @custref = 9

Answer: CREATE PROCEDURE spCustomerValue
(
@custref int
)
AS
BEGIN
SELECT SUM(value) AS TotalOrderAmount
FROM OrderDetails
WHERE custref = @custref
END

To test this you must pass in a custref value
EXEC spCustomerValue 1

Comment: Long back I wrote similar answer ;)
Comment: Yeah I must not have refreshed the page, didn't see your answer. I commented on the question saying that both answers are correct, but reminded him to pass in the custref when executing the procedure


XML para Colunas do Banco de Dados

Question: Tenho uma tabela que guarda um XML em uma de suas colunas, porém preciso fazer um select colocando cada item do XML em uma coluna. O problema é que não quero criar mais uma tabela, eu quero algo, nem que seja temporário, só pra ficar mais fácil o acesso aos dados.
Exemplo:
<?xml version="1.0" encoding="utf-16"?>
<Viagem xmlns:xsd="http://www.w3.org/2001/XMLSchema" mlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Identificador>111111</Identificador>
   <EstimativaInicio>2015-09-07T23:46:48</EstimativaInicio>
   <EstimativaFim>2015-09-07T23:46:48</EstimativaFim>
   <IdCliente>000</IdCliente>
   <IdEmbarcador>000</IdEmbarcador>
   <IdUnidade xsi:nil="true" />
   <CNPJUnidade>00000000/0000-00</CNPJUnidade>
   <IdCooperativa xsi:nil="true" />
   <IdTransportadora xsi:nil="true" />
   <TemperaturaMinima>0</TemperaturaMinima>
   <TemperaturaMaxima>0</TemperaturaMaxima>
   <Motorista>JOAO DA SILVA</Motorista>
   <Placa>ITO-7457</Placa>
   <FoneMotorista>0000000000</FoneMotorista>
   <Tipo>AAA</Tipo>
   <Peso>0</Peso>
   <Valor>0</Valor>
   <Cubagem>0</Cubagem>
   <ViagemPrioritaria>1</ViagemPrioritaria>
   <Entregas>
       <Entrega>
           <Sequencia>2</Sequencia>
           <Codigo>000000000/0000-00</Codigo>
           <Referencia>AA COMERCIAL DE ALIMENTOS LTDA</Referencia>
           <Latitude>-00.0000</Latitude>
           <Longitude>-00.0000</Longitude>
           <EstimativaInicio>2015-09-07T00:00:00</EstimativaInicio>
           <EstimativaFim>2015-09-07T10:06:00</EstimativaFim>
           <Peso>28.06</Peso>
           <Cubagem>0</Cubagem>
           <Valor>201.34</Valor>
           <Endereco>RUA, 000</Endereco>
           <Bairro>CENTRO</Bairro>
           <Cidade>CIDADE</Cidade>
       </Entrega>
   </Entregas>
</Viagem>

Esse XML acima deverá me retornar uma tabela com as seguintes colunas:

Identificador;
EstimativaInicio;
EstimativaFim;
IdCliente;
IdEmbarcador;
CNPJUnidade;
TemperaturaMinima;
TemperaturaMaxima;
Motorista;
Placa;
FoneMotorista;
Tipo;
Peso;
Valor;
Cubagem; e
ViagemPrioritaria.

As colunas da tag de Entregas deve ser ignorada pois não será utilizada neste primeiro momento.
Alguém sabe como fazer isto?
Comment: Qual a tecnologia do banco?
Comment: @CiganoMorrisonMendez Trabalho com SQL Server
Answer: Para fins de testes, coloque seu XML dentro de uma variável para testar. Repare que editei os namespaces pra funcionar:
declare @data xml = '<Viagem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <Identificador>111111</Identificador>
       <EstimativaInicio>2015-09-07T23:46:48</EstimativaInicio>
       <EstimativaFim>2015-09-07T23:46:48</EstimativaFim>
       <IdCliente>000</IdCliente>
       <IdEmbarcador>000</IdEmbarcador>
       <IdUnidade xsi:nil="true" />
       <CNPJUnidade>00000000/0000-00</CNPJUnidade>
       <IdCooperativa xsi:nil="true" />
       <IdTransportadora xsi:nil="true" />
       <TemperaturaMinima>0</TemperaturaMinima>
       <TemperaturaMaxima>0</TemperaturaMaxima>
       <Motorista>JOAO DA SILVA</Motorista>
       <Placa>ITO-7457</Placa>
       <FoneMotorista>0000000000</FoneMotorista>
       <Tipo>AAA</Tipo>
       <Peso>0</Peso>
       <Valor>0</Valor>
       <Cubagem>0</Cubagem>
       <ViagemPrioritaria>1</ViagemPrioritaria>
       <Entregas>
           <Entrega>
               <Sequencia>2</Sequencia>
               <Codigo>000000000/0000-00</Codigo>
               <Referencia>AA COMERCIAL DE ALIMENTOS LTDA</Referencia>
               <Latitude>-00.0000</Latitude>
               <Longitude>-00.0000</Longitude>
               <EstimativaInicio>2015-09-07T00:00:00</EstimativaInicio>
               <EstimativaFim>2015-09-07T10:06:00</EstimativaFim>
               <Peso>28.06</Peso>
               <Cubagem>0</Cubagem>
               <Valor>201.34</Valor>
               <Endereco>RUA, 000</Endereco>
               <Bairro>CENTRO</Bairro>
               <Cidade>CIDADE</Cidade>
           </Entrega>
       </Entregas>
    </Viagem>';

select @data.value('(/Viagem/Identificador/node())[1]', 'nvarchar(max)') as Identificador,
    @data.value('(/Viagem/EstimativaInicio/node())[1]', 'nvarchar(max)') as EstimativaInicio,
    @data.value('(/Viagem/EstimativaFim/node())[1]', 'nvarchar(max)') as EstimativaFim,
    @data.value('(/Viagem/IdCliente/node())[1]', 'nvarchar(max)') as IdCliente,
    @data.value('(/Viagem/IdEmbarcador/node())[1]', 'nvarchar(max)') as IdEmbarcador,
    @data.value('(/Viagem/CNPJUnidade/node())[1]', 'nvarchar(max)') as CNPJUnidade,
    @data.value('(/Viagem/TemperaturaMinima/node())[1]', 'nvarchar(max)') as TemperaturaMinima,
    @data.value('(/Viagem/TemperaturaMaxima/node())[1]', 'nvarchar(max)') as TemperaturaMaxima,
    @data.value('(/Viagem/Motorista/node())[1]', 'nvarchar(max)') as Motorista,
    @data.value('(/Viagem/Placa/node())[1]', 'nvarchar(max)') as Placa,
    @data.value('(/Viagem/FoneMotorista/node())[1]', 'nvarchar(max)') as FoneMotorista,
    @data.value('(/Viagem/Tipo/node())[1]', 'nvarchar(max)') as Tipo,
    @data.value('(/Viagem/Peso/node())[1]', 'nvarchar(max)') as Peso,
    @data.value('(/Viagem/Valor/node())[1]', 'nvarchar(max)') as Valor,
    @data.value('(/Viagem/Cubagem/node())[1]', 'nvarchar(max)') as Cubagem,
    @data.value('(/Viagem/ViagemPrioritaria/node())[1]', 'nvarchar(max)') as ViagemPrioritaria;

Comment: A execução do código que você postou retorna o seguinte erro:

"Msg 9459, Level 16, State 1, Line 3
XML parsing: line 1, character 106, undeclared prefix"
Comment: Editei a resposta.
Comment: Funcionou perfeitamente, obrigada!

XML para Colunas do Banco de Dados


Multiple regression analysis with spatial data as independent variable

Question: In my PhD thesis I am working on spatial modeling of different chemical parameters in groundwater, and for spatial modeling I am also using the multiple statistical approach.
I have a question about multiple regression analysis. (Or it is better to use polynomial regression?)
The equation for spatial regression modeling is: $Y = α +
β_1x_1 + β_2x_2 +.... + β_ix_i + ε$
For my dependent variable, I have concentrations of calcium in groundwater, which were measured from different sampling points in the entire research area. For the independent variable, I choose the spatial data that influence the distribution of calcium in groundwater. I have lithology, vegetation, slope, climatic conditions (temperature, precipitation), depth of soil, ...
The problem is that lithology and vegetation are categorical data (lithology = 3 categories from 1 to 3, where 1 means clastic rocks, 2= carbonate rocks and 3= metamorphic and igneous rocks; and vegetation = 4 categories (1= bare rocks, 2= agriculture land, 3= grassland, 4= forests); all others variables are numerical and continuous.
Do you have any idea how to solve the problem with categorical data in multiple regression analysis? Might it be better to use some other method?
Best regards and thank you very much for your help.
Comment: With spatial data it's usual to take into account, or at any rate check for, correlation between nearby locations that's not captured by the predictors. Plot a semi-variogram of the residuals from your fitted model.
Answer: It's a little unclear what your objectives are, so other methods might be preferable depending on those. Polynomial regression may suit continuous variables, but wouldn't make sense for categorical ones. You can add higher-order terms for the continuous variables alongside categorical predictors though.
Nominal predictors can be added to a multiple regression model using dummy codes. In your case, you could enter lithology as two dummy variables: using clastic rocks as the reference group (for example; not necessarily the one you want to choose), you could create one binary variable indicating whether a case involves carbonate rocks (1 if so, 0 if not), and another equivalent one for metamorphic/igneous rocks. The same process of dummy coding can work for any number of levels, and won't be too much harder to interpret for vegetation. Here's an example dataset:
$$\begin{array}{c|cccccc}\rm Case&\rm Carbonate&\rm Metamorphic/Igneous&\rm Farm&\rm Grass&\rm Forest&...\\\hline\small\rm Clastic\ bare&0&0&0&0&0&...\\\small\rm Carbonate\ bare&1&0&0&0&0&...\\\small\rm Igneous\ bare&0&1&0&0&0&...\\\small\rm Clastic\ farm&0&0&1&0&0&...\\\small\rm Carbonate\ farm&1&0&1&0&0&...\\\small\rm Igneous\ forest&0&1&0&0&1&...\\...&...&...&...&...&...&... \end{array}$$See how that works? (I can elaborate if not.) Just enter these binary predictors like any other. The corresponding $\beta$s represent the differences between given groups and the reference group.
E.g., $\beta_{\rm Carbonate}$ represents the difference between carbonate and clastic in the above example.
Comment: Nick, yes I can see how this works, you presented very clearly. I will do that. The objective of this research is a spatial distribution of calcium in groundwater based on statistical methods. That means that I have to "find the equation" or better algorithm which will present the best correlation between spatial indenpendent variables. Than I have to enter this equation in GIS and do moddeling. I only have some concerns about this method of regression, due to categorical data and than moddeling. So that is why I asked if there is any other method that would be better for moddeling calcium?
Answer: Lets be careful in defining the problem. You have asked for couple of things here. You are talking about linear or polynomial , you are taking about categorical variables.
I see that Response variable Y is a continuous variable. So we can use R function lm(). Linear Models. Now your modeling problem has multiple Predictor variables x1,x2,..,xN. So we can do "Multiple regression analysis".
In lay-man term  whether to use linear or polynomial equation ( quadratic or exp equation ) to fit your data really depends on the data self. In general polynomial equation tends to over-fit so be careful.
I see you are concerned about one more issue categorical variable. The good news is any categorical variable in R is represented as a factor. So you dont have to worry about it.
Now R code
fit1 = lm(Y ~ lithology + vegetation + X3 + X4, data = spatialdata)

This is your model. But you need to make sure you pass the multicollinearity test.


What do the terms "nearly-optimal rate", "near-minimax rate", "minimax optimal rate" and "minimax rate" mean in the context of posterior consistency?

Question: Definition: A sequence $\epsilon_n$ is a posterior contraction rate at the parameter $θ_0$ if $$\Pi_n(θ: d(θ, θ_0) ≥ M_n \epsilon_n| X^{(n)}) → 0$$ in $P^{(n)}_{θ_0}$-probability, for every $M_n → ∞$.
I am studying the subject of posterior consistency. While this subject seems straight forward there are few keywords used which I can't find any definition for. Most of these terms are used in the literature and published papers where the author assumes prior knowledge of this subject by the reader. From farther reading, it seems that these "rates" are related to the contraction rate and seem to originate from the Minimax theory/criterion however I still haven't found any definition for them or their relationship to the contraction rate $\epsilon_n$.
Could you please provide me with any helpful definition for these terms or direct me to a source where they are explained?
Some papers:
https://arxiv.org/pdf/1712.08964.pdf
https://arxiv.org/pdf/1811.06198.pdf
https://arxiv.org/pdf/0910.2042.pdf
Comment: @frank https://arxiv.org/pdf/1712.08964.pdf and https://arxiv.org/pdf/1811.06198.pdf and https://arxiv.org/pdf/0910.2042.pdf and several others..
Comment: There terms may be too advanced for this site... I hope you find what you looking for though.
Comment: @user3741635, I don't think so. These terms are widely used in the literature, Thank you anyway.
Comment: Could you give links to papers that use those terms?
Answer: Can't comment due to lack of rep, but think I may be able to add some useful input if you haven't figured it out already.
I believe what you are missing here is that the speed of convergence of the mass of the posterior on the true value is an important factor and that this is likely what is being referred to as the rate (it would be useful if you gave a reference to the literature you're talking about).
Showing that updates to the posterior are a contraction about the true value of the parameter demonstrates consistency.
Then placing bounds on that contraction rate (via minmax) will allow you to guarantee some rate of convergence on the true value.
So convergence and contraction are sort of related concepts here. The Terminology might be more usefully explained in texts on real analysis, dynamical systems, optimisation etc. than statistics.
Comment: But what is the difference between each of these rates listed in the title?
Comment: Someone has clearly found a theoretically optimal rate of convergence (which I don't fancy digging around for because it's probably incomprehensible to me anyway) and the authors have compared their bounds on the rate to this theoretical optimum and decided they're close: I dont think there's a hard definition of near-optimal in optimisation, but do have a look if you don't believe me! If you search for info in the context of posterior consistency I think you'll find nothing, because they're concepts in prerequisite other etc. as suggested in the answer (optimisation added to answer)
Comment: I don't think this answers my question.


Forcing IE to render output in table

Question: Can I make internet explorer render the page when in php i use
flush()

In a table, Internet explorer will wait for the rest of the
 before it renders the information. Firefox renders it straight away.
Edit:
I'm using a table to display live information about servers and services.
For example:
1st column is the server name.
2nd column is servers status, I get this by pinging the machine.
Is there a better way to display this information?
Comment: +1 Although I just think that's how IE works. Hence (one of) the reasons we don't use table for layouting anymore. (<-- among many others)
Comment: `flush()` just sends whatever output you have in the buffer out to the client browser. If the client web browser doesn't render it, the only thing you can do is change what you output to something that the client browser does render.
Comment: So basically what @yes123 said. If IE will refuse to render a partially-coded table, change the format to something other than a table.
Answer: Setting table-layout: fixed in your stylesheet will stop some browsers (probably including IE) waiting for the whole table before rendering it (of course it will also stop browsers re-rendering it based on content size).
Answer: No, simply calling flush() causes PHP to push its buffer to the web server, nothing more.  Even if IE has the data for the table, it won't render it ahead of time.
The only thing you could do would be to create a table with JavaScript and add to it, piece by piece.  Of course, this is ridiculous though, and you should never do it.  It will be incredibly slow.
There is nothing you can do about this behavior (short of Quentin's suggestion, which changes your layout), and certainly not server-side.
Answer: i suggest moving on to using a list instead of a table. this way, it's faster. mark-up is somewhat similar so you can't go wrong.

        server1
        OK

        server2
        NOT OK

Forcing IE to render output in table


Does Voronoi tessellation in 3D always produce convex polyhedrons?

Question: I'm more or less certain that the Voronoi tessellations (using Euclidean distance measure) produce convex polygons/polyhedrons. Is there a way to prove this mathematically? Or am I wrong? I am especially interested in 3D case. On a side note, can a convex polyhedron have a concave face?
Comment: If it has a concave face, then the 2 points which make the face not convex, will fail the definition of a convex polyhedron. Hence, no to side note.
Comment: @Calvin: As I understand the question, that's not true. 'Concave face' presumably means concave as a 2-dimensional polygon. So the line between your two points could be contained in the polyhedron. I think your conclusion is correct, but I don't think you have proved it.
Comment: @TonyK Yes you're right. It could have a protrusion. Like 3-D Pac-man with a wide beak.
Comment: Can we prove this please (convex polyhedrons have all convex faces)?
Answer: Assuming all your sites $P_k$ are points, the definition of the $k$th Voronoi cell
$$R_k = \{x \in X\,\, | \,\,d(x,P_k) \leq d(x, P_j)\,\, \text{for all}\,\, j\neq k\}$$
reduces to an intersection of half-spaces, because $d(x,P_k)\le d(x,P_j)$ if and only if $\langle x-P_k,P_j-P_k\rangle\le\frac12\lVert P_j-P_k\rVert^2$, that is, $x$ lies on the side closer to $P_k$ of the plane perpendicularly bisecting the line segment between $P_k$ and $P_j$. This makes it a convex polyhedron (assuming your definition of polyhedron includes unbounded sets).
Comment: Can we also prove this just from the definition of convexity, that is, if $d(x, P_k) \le d(x, P_j)$ and $d(y, P_k) \le d(y, P_j)$ for all $j \ne k$, then $d(\lambda x + (1 - \lambda) y, P_k) \le d(\lambda x + (1 - \lambda) y, P_j)$ for all $j \ne k$?


An estimator for the Exponential distribution with $\lambda\le 10$

Question: I'm trying to solve these two question below:

For the following experiments, define a statistical model and check
whether the parameter of interest is identified.
a. One observes $n$ i.i.d. Poisson random variables with unknown parameter $\lambda$.
b. One observes $n$ i.i.d. exponential random variables with parameter $\lambda$, which is unknown but a priori known to be no larger than
$10$.

I have the following questions:

What does he mean by "parameter of interest", an estimator with no bias or any estimator converging to the parameter is a valid one? in this case for any question asking an estimator of a parameter, that's enough to use WLLN and mapping theorem.

for the item a, using WLLN:

$$\bar X_n\xrightarrow{P}\lambda$$
and $\bar X_n$ is unbiased because $E[\bar X_n]=\frac{X_1+\ldots+X_n}{n}=\frac{n\lambda}{n}=\lambda$

The last part I found a little tricky.

Using the WLLN, mapping theorem and the fact $E[X_i]=1/\lambda$, I showed $$T_n=\frac{1}{\bar X_n}\xrightarrow{P}\lambda$$
But I'm having problems to find the bias of this estimator (I know this $E[\bar X_n]=\frac{1}{E[\bar X_n]}$is not always true by Jensen's inequality) and I don't know how to use the fact $\lambda\le 10$.
Answer: They simply ask you to define the Statistical Model for the two experiments.
The statisical model is definded through the following phases

Definition of the Base Model

Bernullian Sampling (with replacement)

1. Base Model
In your cases, the base model is the following:
$$\Big(X, p(x|\theta), \theta \in \Theta\Big)$$
2. Statistical Model
The given Sampling rule induces the following Stat Model
$$\Big(\mathcal{X}^{(n)}, \prod _{i=1}^{n}p(x_i|\theta), \theta \in \Theta\Big)$$
If the question is what you posted

For the following experiments, define a statistical model and check whether the parameter of interest is identified.

no calculations are needed
For the first experiment you have
$$\Big(\mathcal{X}^{(n)}, \frac{e^{-n\lambda}\lambda^{\Sigma_i X_i}}{\Pi_iX_i!}, \lambda>0 \Big)$$
Where
a. $\mathcal{X}^{(n)}$ is the set of all possible n-tuples where any element can takes the values $\{0,1,2,3,...\}$
b. The function $\frac{e^{-n\lambda}\lambda^{\Sigma_i X_i}}{\Pi_iX_i!}$, given the knowledge of $\lambda$, assigns the probability to any possible n-tuple.
c. $\lambda$ is the parameter of interest

Similar reasoning for the 2nd experiment


Dual-port server acting as router, but LAN can't see WAN

Question: Using Windows Server 2012 Essentials.
I've got two ethernet ports. One is connected to a router which is connected to the internet. This portion of the network is fine. The router runs DHCP on the 192.168.1.x subnet, and provides a Company1 WiFi for guests, which does not have access to servers etc.
The idea is to have a second LAN, through the Windows server. I'm trying to use the .16.x subnet for this, but machines on teh 16.x subnet can't see the internet.
Port 1 is set to get settings automatically from the router.
Port 2 is configured as so:
IP: 192.168.16.101
Subnet: 255.255.255.0
Gateway 192.168.1.101
DNS: 192.168.1.101
This connection shows as limited connectivity on the server.
Clients are set to use 192.168.1.101 as both gateway and DNS. The server provides DNS services and DHCP on the internal network interface. I suspect that either the DNS/Gateway settings on port 2 (Internal) are wrong, but I've tried everything I can think of.
Comment: Who or what is supposed to provide Internet access to machines in the 192.168.16.x subnet? If you didn't configure the router to and didn't configure the server to, then of course they won't have Internet access. (Think about it, what would Internet servers see as the source IP address of connections they make? How would reply packets from the Internet get back to machines on that network?) Some device has to NAT for them.
Comment: I've just discovered that, thanks. I figured server 2012 was intelligent enough to just route between the networks. I'm trying to use RRAS, but now I'm getting an issue whereby both my network interfaces are attached to the domain, so I can't set up remote access. Is it possible to configure NAT without this?
Comment: It is intelligent enough to just route between the networks. However, that won't give them Internet access.
Answer: Solved it, so I'll leave this here in case anyone else has the same issue.
I needed to add the RRAS module (Routing and Remote Access), then configure NAT to translate the internal network onto the external IP.
Comment: You should accept your answer so that the question doesn't keep popping up forever, looking for an answer.


How can I use jQuery 1.7 without having issues in the admin pages?

Question: Is anybody successfully running jQuery 1.7?
I'm using a jQuery component on my pages which requires jQuery 1.7 or later. This version causes some unwanted side effects in the admin UI, such as checked checkboxes that don't reveal additional controls when available, or field widget not being active.
I was wondering if there's a solution that could let me easily work with jQuery 1.7.
I saw this answer before asking. As far as I understand, there are 2 separate issues: updating src of the jQuery to 1.7.x, and updating the javascript used by admin. I tried to use the latest jquery_update development snapshot, and apply a patch, but it does not solve the above-mentioned problems with UI.
Comment: The policy pretty much dictates that upgrading Drupal versions shouldn't break anything that relies on jQuery, so the version stays consistent.
Comment: Technically this issue is a dupe of http://drupal.stackexchange.com/a/41394/809 Also I'm a bit bias but the other question has a better answer.
Answer: I would look at Clive's advice on doing it manually here:
How do I update jQuery to the latest version I can download?
and add some more intelligence into the script to not do it on admin pages, eg:
if (arg(0)=='admin') {
  return;
}

You would also have to do that on node/#/add and node/#/edit pages etc so as to not disrupt anything "core" there, or, if you want, dive into drupal core and bring everything else up to 1.7 as well.
Depending on what version of Drupal you are running, this might also work:
function YOURTHEME_preprocess_page(&$vars) {
  if (YOUR CONDITION HERE) {
    $scripts = drupal_add_js('PATH TO YOUR JQUERY FILE');
    unset($scripts['core']['PATH TO DRUPAL JQUERY FILE']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

where you could set "YOUR CONDITION HERE" to be whatever pages you want the new jquery on, eg, arg(0)!='admin' etc.
Comment: +1 A nice simple way to get a list of all admin pages that don't have 'admin' in the url is: `$pages = module_invoke_all('admin_paths');`
Comment: Keep in mind that ctools has had a history of breaking, too, with jquery updates.  You may need to adjust the patch to account for this.
Comment: @Clive, does this catch ctools AJAX URLs?  Like when you use a ctools widget on a "normal" page?
Comment: Thanks Jimajamma, I did not use your code, but your answer put me on the right track. I found a nice patch that adds UI to the jquery_update config screen, that allows you to use different versions of jQuery for admin. http://drupal.org/node/1524944. Working good so far.
Comment: Thanks for pointing this out. Do you have an idea what would be the best way to test against that?
Comment: @Artur, IIRC all of the ctools paths start with "ctools" or something similar.
Comment: @MPD I'm not sure to be honest, ctools doesn't seem to implement `hook_admin_paths()` so maybe not
Answer: jQuery Update now has the ability to enable different jQuery versions for the front-end and the back-end. Download the latest dev version and you're good to go: 1.5 in the backend, so it works with the Views UI, and 1.7 or 1.8 in the frontend, for extra jQuery goodness.


Running test with Nightwatch in Firefox fails to connect to Selenium server

Question: I'm trying to do an automated testing for a website using Nightwatch.js and I'm on macOS High Sierra.
So I started testing using the Selenium Standalone Server as said in the documentation.
The chrome testing works good and I have no problem with it. But I can't seem to make the Firefox testing work, I've been testing and searching online for a fix but I gave up because none of the solutions I found worked.
Here's is my nightwatch.json configuration file.
{
    "src_folders": [
        "test"
    ],
    "output_folder": "reports",
    "custom_commands_path": "",
    "custom_assertions_path": "",
    "page_objects_path": "",
    "globals_path": "",
    "selenium": {
        "start_process": true,
        "server_path": "./bin/selenium-server-standalone-3.13.0.jar",
        "log_path": "",
        "port": 4444,
        "cli_args": {
            "webdriver.chrome.driver": "./bin/chromedriver",
            "webdriver.gecko.driver": "./bin/geckodriver",
            "webdriver.firefox.profile": "nightwatch"
        }
    },
    "test_settings": {
        "default": {
            "launch_url": "https://www.google.com",
            "selenium_port": 4444,
            "selenium_host": "127.0.0.1",
            "default_path_prefix": "",
            "silent": true,
            "screenshots": {
                "enabled": false,
                "path": ""
            },
            "desiredCapabilities": {
                "browserName": "firefox",
                "javascriptEnabled": true,
                "acceptSslCerts": true,
                "marionette": true
            }
        },
        "chrome": {
            "desiredCapabilities": {
                "browserName": "chrome",
                "chromeOptions": {
                    "args": [
                        "--load-extension=/Users/jackch/Downloads/chrome, --url-base=/wd/hub"
                    ]
                }
            }
        }
    }
}

And then when I run nightwatch -e --verbose in the terminal, I get the same error Error retrieving a new session from the selenium server Connection refused! Is selenium server started?.
I tried many things:
1) I started geckodriver in a separate terminal on the default port 4444, and here are the logs from geckodriver:
2018-07-23 12:09:03.432 plugin-container[27769:6329668] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7903, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2018-07-23 12:09:03.559 plugin-container[27769:6329668] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7943, name = 'com.apple.coredrag'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2018-07-23 12:09:03.624 plugin-container[27770:6329696] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7b37, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2018-07-23 12:09:03.713 plugin-container[27770:6329696] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7bcf, name = 'com.apple.coredrag'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1532336943850   Marionette  INFO    Listening on port 52869
2018-07-23 12:09:04.333 plugin-container[27771:6329828] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7d07, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2018-07-23 12:09:04.413 plugin-container[27771:6329828] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7d83, name = 'com.apple.coredrag'

See /usr/include/servers/bootstrap_defs.h for the error codes.

2) Then I tried to change the port of geckodriver, because I thought they may intefere since both Selenium and gecko choose the 4444 port, but nothing changed.
3) I tried to launch the Selenium server alone and then linking it. Which mean that I set the "start_process" to false in the nightwatch.json. And I still didn't manage to make it work.
Here is the complete message after I run nightwatch -e --verbose:
    Starting selenium server... started - PID:  28112

[Test] Test Suite
=====================

Running:  Login
INFO Request: POST /session
 - data:  {"desiredCapabilities":{"browserName":"firefox","javascriptEnabled":true,"acceptSslCerts":true,"platform":"ANY","marionette":true,"name":"Test"}}
 - headers:  {"Content-Type":"application/json; charset=utf-8","Content-Length":145}
INFO Response 200 POST /session (1721ms) { value:
   { sessionId: '187e2af1-54a1-224a-9b8d-d4ff9f3913c7',
     capabilities:
      { acceptInsecureCerts: false,
        browserName: 'firefox',
        browserVersion: '61.0.1',
        'moz:accessibilityChecks': false,
        'moz:headless': false,
        'moz:processID': 28131,
        'moz:profile': '/var/folders/vw/j4dsztz17sj_vtk500lv09r00000gn/T/rust_mozprofile.GRCHbtKdy2zm',
        'moz:useNonSpecCompliantPointerOrigin': false,
        'moz:webdriverClick': true,
        pageLoadStrategy: 'normal',
        platformName: 'darwin',
        platformVersion: '17.7.0',
        rotatable: false,
        timeouts: { implicit: 0, pageLoad: 300000, script: 30000 } } } }

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?
{ value:
   { sessionId: '187e2af1-54a1-224a-9b8d-d4ff9f3913c7',
     capabilities:
      { acceptInsecureCerts: false,
        browserName: 'firefox',
        browserVersion: '61.0.1',
        'moz:accessibilityChecks': false,
        'moz:headless': false,
        'moz:processID': 28131,
        'moz:profile': '/var/folders/vw/j4dsztz17sj_vtk500lv09r00000gn/T/rust_mozprofile.GRCHbtKdy2zm',
        'moz:useNonSpecCompliantPointerOrigin': false,
        'moz:webdriverClick': true,
        pageLoadStrategy: 'normal',
        platformName: 'darwin',
        platformVersion: '17.7.0',
        rotatable: false,
        timeouts: [Object] } } }

Thank you for any help you can bring.
Answer: I run nightwatch on mac os high sierra on firefox, safari, chrome. And on window opera, IE.
My config:
module.exports = {
    "src_folders": ["tests"],
    "output_folder": "reports",
    // "live_output" : true,
    // "parallel_process_delay" : 1500,
    "custom_commands_path": "commands",
    "custom_assertions_path": "assertions",
    "page_objects_path": "",
    "globals_path": "",
    "selenium": {
        "start_process": true,
        "server_path": "./node_modules/nightwatch/lib/sel-serv.jar",
        "log_path": "selenium_logs",
        "port": 4444,
        "cli_args": {
            "webdriver.chrome.driver": "./node_modules/.bin/chromedriver",
            "webdriver.gecko.driver": "./node_modules/.bin/geckodriver",
            "webdriver.edge.driver": "./node_modules/.bin/edgedriver",
            "webdriver.ie.driver": "drivers/IEDriverServer.exe",
            "webdriver.opera.driver": "drivers/operadriver.exe",
            "webdriver.safari.driver": "/usr/bin/safaridriver"
        }
    },

    "test_settings": {
        "default": {
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "default_path_prefix": "/wd/hub",
            "silent": true,
            "screenshots": {
                "enabled": true,
                "on_failure": true,
                "on_error": true,
                "path": "tmp_screenshots"
            }
        },

        "firefox": {
            "desiredCapabilities": {
                "browserName": "firefox",
                "marionette": true,
                "acceptSslCerts": true,
                "javascriptEnabled": true
            },
            "globals": {
                "type": "firefox",
                "user": "me1",
                "pass": "test"
            }
        },

        "chrome": {
            "desiredCapabilities": {
                "browserName": "chrome",
                "chromeOptions": {
                    "args": [
                        "disable-web-security",
                        "use-fake-device-for-media-stream",
                        "use-fake-ui-for-media-stream"
                    ]
                },
                "acceptSslCerts": true,
                "javascriptEnabled": true
            },
            "globals": {
                "type": "chrome",
                "user": "me1",
                "pass": "test"
            }
        },

        "opera": {
            "desiredCapabilities": {
                "browserName": "opera",
                "operaOptions": {
                    "binary": "C://Program Files//Opera//53.0.2907.68//opera.exe"
                },
                "acceptSslCerts": true,
                "javascriptEnabled": true
            },
            "globals": {
                "type": "opera",
                "user": "me4",
                "pass": "test"
            }
        },

        "ie": {
            "desiredCapabilities": {
                "browserName": "internet explorer",
                "version": 11,
                "allowBlockedContent": true,
                "javascriptEnabled": true,
                "acceptSslCerts": true,
                "ignoreProtectedModeSettings": true
            },
            "globals": {
                "type": "ie",
                "user": "me3",
                "pass": "test"
            }
        },

        "safari": {
            "desiredCapabilities": {
                "browserName": "safari",
                "javascriptEnabled": true,
                "acceptSslCerts": true
            },
            "globals": {
                "type": "safari",
                "user": "me3",
                "pass": "test"
            }
        }
    },
    "test_workers": {
        "enabled": true,
        "workers": "auto"
    }
};

Comment: This solution fixed my problem, I don't know what fixed it but I changed some settings to match this one and it works now. Thank you


Evaluating a Gaussian integral

Question: Let $X_1,\ldots,X_n$ be a sequence of $n$ zero-mean independent and identically distributed Gaussian random variables, i.e. $X_i\sim N(0,\sigma^2)$ for all $i=1,\ldots,n$ and variance $\sigma^2>0$.  Therefore, the probability density of $X_i$ is $\phi(x_i;0,\sigma^2)=\frac{1}{\sqrt{2\pi}\sigma}e^{-x_i^2/2\sigma^2}$.  This is all elementary probability theory...
I am lost trying to evaluate the following expectation:
$$U(k)=\int_{-\infty}^\infty\cdots\int_{-\infty}^\infty\prod_{i=1}^n\phi(x_i;0,\sigma^2)\left(\sum_{i=1}^n x_i\right)^k\prod_{i=1}^{n}dx_i$$
There are $n$ integration operations and $k$ is a positive integer.
Now, $U(1)$ is obviously zero (since the mean of each $X_i$ is zero).
$U(2)=n\sigma^2$ since $X_i$'s are independent and each have zero mean, which means that the expectations of the cross terms are zero: for $i\neq j$, $E_{X_iX_j}[X_iX_j]=\int_{-\infty}^\infty\phi(x_i;0,\sigma^2)\phi(x_j;0,\sigma^2)x_ix_jdx_idx_j=0$.
$U(3)=0$ since each $X_i$ has mean and third moment zero.
I am confused when I get to $k=4$.  The sum term in the expectation now looks like:
$$\left(\sum_{i=1}^n x_i\right)^4=\sum_{i=1}^n x_i\sum_{j=1}^n x_j\sum_{a=1}^n x_a\sum_{b=1}^n x_b$$
Since the cross terms are zero, I can group the sums inside the expectation as follows:
$$U(4)=\int_{-\infty}^\infty\cdots\int_{-\infty}^\infty\prod_{i=1}^n\phi(x_i;0,\sigma^2)\left(\sum_{i=1}^n x_i^2\sum_{j=1,j\neq i}^n x_j^2+\sum_{i=1}^n x_i^4\right)\prod_{i=1}^{n}dx_i=n^2\sigma^4+2n\sigma^4$$
However, I have a feeling that the above is not correct and that $U(4)=3n\sigma^2$...  and that $U(k)=nE[X_i^k]$, but I am not sure how to get there...
Comment: $U(k)=\mathbb{E}[(\sum X_i)^k]$ and you know the moments of the distribution of $\sum X_i$
Comment: @StéphaneLaurent : Maybe you should make your comment into an answer.
Comment: The point is that the sum of independent normal random variables is normal.
Comment: Aha, now I see.  Thank you!
Answer: We have $U(k)=\int f(x_1, \ldots, x_n)\mathrm{d}\mu(x_1,\ldots, x_n)$ where $f(x_1, \ldots, x_n)={(\sum_{i=1}^nx_i)}^k$ and $\mu$ is the law of $(X_1,\ldots,X_n)$. In other words $U(k)=\mathbb{E}\left[{(\sum_{i=1}^nX_i)}^k\right]$. Now the point is that the random variable $\sum_{i=1}^nX_i$ has a Gaussian distribution whose law is easy to determine and the moments of a Gaussian distribution are well-known.

Evaluating a Gaussian integral


How would I play this note that has two G's next to each other

Question: How would I play the notes that are side by side in the same line?
Comment: Does this answer your question? [Why does this note have a stem pointing up and another pointing down?](https://music.stackexchange.com/questions/33948/why-does-this-note-have-a-stem-pointing-up-and-another-pointing-down)
Comment: Does this answer your question? [Two adjacent notes of same pitch seemingly occupying the same beat?](https://music.stackexchange.com/questions/61200/two-adjacent-notes-of-same-pitch-seemingly-occupying-the-same-beat)
Answer: You'd play the G and hold it for the bar. It's the same note played in two different voices. There have been many similar questions concerning this same issue.
Answer: As far as playing is concerned, play the notes once and hold it for the largest of the two time values given.
This kind of writing is done when the music is for more no. of voices than staves used. Within a staff, if there are two voices, first voice's note stem goes up and the other voice's goes down. When writing for two voices, time signature has to be satisfied for both voices seperately and independently.
Note that this kind of question has been asked several time is MusSE and make sure you do your research before asking a question. Duplicate questions get closed.

How would I play this note that has two G’s next to each other


disable osk (onscreen virtual keyboard) in windows 7 (or vista) OR customize osk layout

Question: I use windows 7 as host for touchscreen PC in public environment. I would like to prevent the OS being controled by a user.
With a physical keyboard, you would remove the control and alt keys. But with the built-in on-screen keyboard?
does anybody know how to customize or completely remove the on-screen keyboard (osk) that appears in windows 7 when you touch the left border of a touchscreen ?
I've been trying for hours, including one hour with the help from a MS support tech guy, and we found ... nothing!
Answer: You should be able to either set permissions on the osk.exe executable so the user is unable to run it or add a path rule to Software Restriction Policies forbidding the execution of osk.exe altogether.
Comment: Thank you very much syneticon-dj. I'll try this tomorrow. Can you just tell me how to "add a path rule to Software Restriction Policies" ? I've never done that. How do you start to do that ?


mysql : How to obtain the list of product id's with two different conditions?

Question: How to obtain the list of product id's which has size small and color green?
I have a table as
prodid | heading  |  description

20    |   color    |   green

20    |   size     |    s

21    |   size     |    s

22    |  size     |    s

My query:
select prodid from tablename
where heading in('color','size') and description in ('green','s');

but required output is "the list of prodid containing size small and green color".
prodid | heading  |  description

20    |   color   |  green

20    |   size    |   s

Can any one please help me to write a query to obtain the above output.
Answer: Because you need both color and size rows of the product to impose all the conditions, join the table to itself:
select t1.prodid
from mytable t1
join mytable t2 on t2.prodid = t1.prodid
where t1.heading = 'color' and t1.description = 'green'
and   t2.heading = 'size'  and t2.description = '5'

Answer: You can build the query using nested 'and' and 'or's:
select prodid from tablename where (heading = 'color' and description = 'green') or (heading = 'size' and description = 's');

Comment: That is not what he is asking... he wants **both** conditions to be satisfied on the same prodid ;)
Comment: Ahh, I see. But his sample output is not actually what he wants... the 'correct' answer will give one row per prodid.
Comment: Yes... his result set is not absolutely clear... I agree
Comment: basically  i am working on a filter. the table contains the different attributes such as color,size,brand under a heading column name and there respective description such as green,s,brandname etc for each product id. i want to obtain the list of product id which has colour = green and size = s. How this can be done?
Answer: select prodid from tablename
  where heading = 'color'
  and description = 'green'
  and prodid in (select prodid from tablename
         where heading = 'size'
         and description = 's');

Answer: I'd use this:
SELECT prodid
FROM mytable a
WHERE EXISTS (
  SELECT prodid
  FROM mytable b
  WHERE b.prodid=a.prodid AND b.heading='size' AND b.description='small'
) AND EXISTS (
  SELECT prodid
  FROM mytable c
  WHERE c.prodid=a.prodid AND c.heading='color' AND c.description='green'
)

Even though it uses the table 3 times, I find it more readable and extensible.
If performance is an issue, it can be done by using the table only twice, like Bohemian suggested. But first make sure you have an index on (prodid,heading,description).


Laravel Service Provider Class Not Found — Server Specific Issue

Question: I'm creating a custom package for Laravel 5, and have run into the problem where Laravel is having trouble finding the service provider for this, but only on a specific server. Locally, I'm running this under Vagrant using the Homestead box, and it's working fine. Using git to push it to a dreamhost VPS (Ubuntu), it's giving me the error that it can't the class Figoliquinn\Quickbooksconnect\QuickbooksconnectServiceProvider. It feels like a namespace issue to me because it's working differently on different environments, but I haven't been able to track down the cause.
The folder structure for the package is (from the laravel root):
<code>* packages
|--* figoliquinn
   |--* quickbooksconnect
   |--* src
      |--* QuickbooksconnectServiceProvider.php
</code>
QuickbooksconnectServiceProvider.php
<code>    <?php namespace Figoliquinn\Quickbooksconnect;

use Figoliquinn\Quickbooksconnect;

use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;

class QuickbooksconnectServiceprovider extends ServiceProvider {

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Get the views we'll need
        $this->loadViewsFrom(__DIR__ . '/views', 'quickbooksconnect');

        // Register our controller and routes
        $this->app->router->group(['namespace' => 'Figoliquinn\Quickbooksconnect\Controllers'],
        function(){
            require __DIR__.'/routes.php';
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

    }

}
</code>
Here's what my composer.json file looks like in the Laravel root:
<code>{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "illuminate/html": "~5.0",
        "guzzlehttp/guzzle": "~5.3|~6.0",
        "doctrine/dbal": "~2.3"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "Figoliquinn\\Quickbooksconnect\\": "packages/figoliquinn/quickbooksconnect/src/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ],
        "files": [
            "app/helpers.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}
</code>
And then when adding this in config/app.php, this looks like (abbreviated just to the providers section):
<code>'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Routing\ControllerServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,
        'Illuminate\Html\HtmlServiceProvider',
        'Figoliquinn\Quickbooksconnect\QuickbooksConnectServiceProvider',

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        'App\Providers\MacrosServiceProvider',
        'App\Providers\CurrentOrgServiceProvider',

    ],
</code>
Any suggestions on something I might have overlooked?
Comment: Have you dumped your autoloader?
Comment: Yep. The Figoliquinn namespace is also showing up within vendor/composer/autoload_psr4.php.
Comment: Hmm. Are you doing this on the production end as well? The autoloader is usually in the vendor folder which is automatically added to .gitignore
Comment: Yep, which is why it was feeling pretty strange. Ran composer dump-autoload within the root of the laravel directory multiple times.
Answer: Ended up being really stupid on my part. I'd included more or less an SDK I was try to integrate into a package, and that SDK had a .gitignore file that was causing some issues pushing stuff around. Removing that did the trick.


How to get Current position of a control on Win Form

Question: Am trying very hard but not find any method to get the location(x,y) of the control like picturebox on the form .. please help me ...
Answer: you can just use  picturebox1.Left as you X  and picturebox1.Top as your Y
or
you can  combine PointToScreen and PointToClient:
Point locationOnForm = control.FindForm().PointToClient(
    control.Parent.PointToScreen(picturebox1.Location));


Bootstrap 3 with fullscreen background slider always suddenly jumps to the top of the page on mobile devices

Question: my problem is that when I scroll down in an mobile browser where the menu bar vanishes (e.g. chrome) my background tries to adjust for the larger screen height.
When scrolling up again the menu bar of chrome appears again and reduces the screen height calling my background to shrink again and then suddenly jumps to the beginning of the page.
This looks like hickups and destroys the usability of the page.
the domain is www.kaufbar-muelheim.de
Any clues how to resolve this problem?
THX
Philipp
Answer: You can remove the div id="maximage", and do all the work on the body.
Just give the body the following css:
<code>body {
    background-size: auto 100%;
}
</code>
And cycle the background by changing the background-image on the body tag.
This will avoid all the calculations for the image size, and gives you the same result.
The problem, is that you would probably have to preload all the background images somehow. As the images are not in the DOM anymore.


Online store with support for store credit

Question: I am looking into online stores to use internally at a company. They would like to be able to add credit to a users account as part of an incentive program.
I have started looking at Online store software, but am not clear as to which support store credit, or if it is a function of the payment module (ie separate issue).
The credit shouldn't be in the form of actual money (so it shouldn't be like putting money on a users paypal account), but credit which can be redeemed in-store.
Comment: hopefully that makes the question clearer
Comment: honestly i have not seen any such functionality,but i believe you can do something like credit points which user can redeem at his/her own will
Comment: This is something that you'll need to write yourself. Something like Satchmo is only going to support actual currencies.
Comment: What about stores that support gift codes. Are there open source stores that support that?
Answer: You could implement this easily in Satchmo with the Giftcertificate-Module. You can assign a GiftCertificate an amount of money and the user owning this code can use it on checkout to pay. If the cart-amount is less, then the GC can be used afterwards with the rest-money on it. And if it isn't enough money on it, the user can pay the rest with any other payment method available.
Answer: Magento has this functionallity built into their commercial editions.


C++ Error in my own stack class

Question: This is a program with my Stack class:
<code>    #include <iostream>
    using namespace std;
    template <class T>
    struct Node{
        T element;
        Node<T> *prevElement;
    };

    template <class T>
    class Stack {
    private:
        unsigned int NumberOfElements;
        Node<T> *tempAdr;
        Node<T> *topElement;
    public:
        Stack(){
            topElement = new Node<T>;
            topElement->prevElement = nullptr;
            NumberOfElements = 0;
        }
        ~Stack(){
            delete topElement;
        }

        void push(T input_element){
            tempAdr = topElement->prevElement;
            topElement = new Node<T>;
            topElement->element = input_element;
            topElement->prevElement = tempAdr;
            NumberOfElements++;
        }

        void pop(){
            tempAdr = topElement->prevElement;
            delete topElement;
            topElement = tempAdr;
            NumberOfElements--;
        }

        T top(){
            return topElement->element;
        }

        unsigned int size(){
            return NumberOfElements;
        }

    };

    int main(){
        Stack<int> MyStack;
        MyStack.push(17);
        MyStack.push(18);
        MyStack.pop();
        cout << MyStack.top()<<" "<<MyStack.size();
        system("pause");
        return 0;
    }
</code>
Expected output is

17 1

But when I run the code, I'm getting the error message:

Unhandled exception at 0x00EE5FA9 in LB_4_RealStack.exe: 0xC0000005:
  Access violation reading location 0x00000000.

So, can you guys help me to find the error? I was looking through my code over and over again, but I didn't find the reason for the exception.
Comment: You didn't mention which line throws the exception.
Comment: @user2079303 `return topElement->element;` in my top() method
Comment: You should add that information to the question.
Comment: The error message clearly states that you are dereferencing a null pointer. Step through your code line by line, operation by operation, and determine where it diverges from the algorithm that you wrote out on paper before beginning.
Comment: Yeah, really. Thanks for attension
Answer: I think the error is in your push() method, the first instruction.
In fact what you obtain in the code is to add the element on top of the next element from the top (disregarding the current top), so if you rewrite the method as in:
<code>void push(T input_element){
    tempAdr = topElement;
    topElement = new Node<T>;
    topElement->element = input_element;
    topElement->prevElement = tempAdr;
    NumberOfElements++;
}
</code>
It should work.
Comment: You're right. I've changed my push() method with yours, and it worked fine. Thank's so much!

C++ Error in my own stack class


How to destroy/delete/unset a variable value in Ansible?

Question: Is there a way to destroy the variable in Ansible?
Actually, I have a {{version}} variable being used in my all roles for respective packages. When I run multiple roles, the version value of one role is passed to another - this is due to for some role I am not giving version value so that it can install the default version of that package available for respective m/c like ubuntu/redhat etc.
Here is my role template. The value of {{version}} from mysql is being passed to rabbitmq.
    roles:
- { role: mysql }
- { role: rabbitmq}

If I can destory/delete the value of version in every role, it should solve the problem, I believe.
Answer: As already pointed out it is not possible to unset a variable in Ansible.
Avoid this situation by adding a prefix to your variable names like rabbitmq_version and so on. IMHO this a best practice.
Beside avoiding the situation you ran into, this will add clarity to your host_vars and group_vars.
Answer: No, there is no way to unset a variable (top level) in Ansible.
The only thing you can do, is to create a dictionary and store the variable as a key in this dictionary. Clearing the "parent" dictionary will essentially make the dictionary.key is defined conditional expression work.
Answer: To unset a variable, try running a set_fact task setting the variable to null, like:
- name: Unset variables
  set_fact:
    version:
    other_var:

If you have a full dictionary that could just override the dict with null, like:
- name: Set dict
  set_fact:
    dict:
      rabbitmq_version: 1
      other_version: 2

- name: override dict to null
  set_fact:
    dict:

Something like other_var: just is "other_var": null in JSON. That is how you can unset variables in Ansible. Have a nice day.
Comment: I don't know what you mean by `null`, but your first example sets those facts to the empty string, not undefined (as I just discovered).
Comment: FWIW this approach combined with [omit filter](https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#making-variables-optional) could allow the null or empty string to be sensed to drop the version key. It would need to be done whereever the variable is used though, rather than where the variable is set.
Answer: you should use variable per role instead:
  roles:
    - role: mysql
      version: mysql_version
    - role: rabbitmq
      version: rabbitmq_version

or
  roles:
    - { role: mysql, version: mysql_version }
    - { role: rabbitmq, version: rabbitmq_version }

Answer: You can set it to nothing. I'm currently using it like that:
variable_name: ''

Comment: This makes the variable's value an empty string, but it does not unset the variable.