Is there a smallest possible sample size for MANOVA (post-hoc)

Question: I am testing two DV and two IV using a two-way MANOVA. I have four groups. I had used g*power to recommend a sample size, however I have not yet achieved this recommended sample size. Instead I have 11 samples from 11 random participants. I understand that this is not optimal because then I have uneven samples in groups (i.e. A=3, B=3, C=3, D=2) and DV's (DV1=6, DV2=5). However, that aside, my concern is whether there is a minimum sample size that is acceptable.
I have checked the significance of my results and found they are strongly significant. In RStudio the results are marked with three asterisk ***. Given that my alpha remains at 0.05 (in Gpower the graphs show that) I have no chance to make a Type I error. By the low power of my sample size I have a very large chance to make a Type II error (to accept the null hypothesis even though it is false). My results show a significant difference despite this low power. So in this case I won't make a Type II error, as I will reject the null hypothesis.
I was wondering if this is an acceptable statistical result (so that results would be considered for publication), or whether there is a minimum sample size that should be reached. I heard there is a rule 'you need to have more cases in each cell than you have DVs'. I have two DVs. Does that mean I have covered the minimum requirements? I don't have a textbook or journal article to cite this rule either. I would appreciate if someone can help me out here.
Thank you in advance!
Answer: I have found the following reference. I would prefer Journal or Textbook references.

"Assumption #4: You should have an adequate sample size. Although the larger your sample size, the better; for MANOVA, you need to have more cases in each group than the number of dependent variables you are analysing."

https://statistics.laerd.com/spss-tutorials/two-way-manova-using-spss-statistics.php
Your feedback is much appreciated!

"POWER AND SAMPLE SIZE:
As we have seen, the first test that's performed when we do a MANOVA is a test for homogeneity of the VCV matrices. For this test to run, we must have more subjects than variables in every cell (Tabachnick and Fidell, 1996)."

https://basicmedicalkey.com/multivariate-anova-manova/


Does the "number of unrollings" of an RNN always have to match the length of the input sequence?

Question: An RNN can be visualized in two ways: rolled and unrolled, as in the following picture

I have seen in a few implementations the "number of unrollings" as a parameter or variable of the system, which made me wonder if the number of "unrollings" (in the picture above it should be $3$) is or not dependent on the length of the input sequence.
In chapter 10.1 of the book Deep Learning
 (by Goodfellow et al.)  it is stated

What we call unfolding is the operation that maps a circuit, as in the left side of the figure, to a computational graph with repeated pieces, as in the right side. The unfolded graph now has a size that depends on the sequence length.

Is the number of times we unroll the recurrent connection always equal or not to the length of the input sequence?
I've just come across this post, where the author asks if there is any difference between unrolling one or multiple times an RNN. The answer to that question states that the "number of unrollings" is important only during training. This seems not to be consistent with the information from the book.
Answer: What the book mentions and what the author of the post meant are two different things.
As the book mentions, 'unfolding' is dependent on the length of the input sequence. To understand this, suppose you want to lay down the exact computations that are happening in an RNN, in that case, you have to 'unfold' your network and the size of your 'unfolded' graph would depend on the size of the input sequence. For more information refer to this page. It says that "By unrolling we simply mean that we write out the network for the complete sequence. For example, if the sequence we care about is a sentence of 5 words, the network would be unrolled into a 5-layer neural network, one layer for each word."
In case of the post, what the author meant is that during training you need 'unrolling' because you need to store the activations/ hidden states for backpropagation. During testing, you need not store the hidden states (as you don't need to do back-propagation), so no 'unrolling' is required.


Flip an image when a table cell is clicked, or the image itself is clicked

Question: I am trying to flip an arrow 180 degrees if a cell is clicked, or if the imaged itself is clicked.. Here's my code: Note: The image being flipped is the one in the first row with an ID of image1. I will be flipping all of the images once I get this first one working.

                Symbol
                Company
Name
                Buy
Date
                Buy
Price
                Closed
Price
                Closed
Date
                Total
Return

And the Javascript:
$(function(event){
    $("table .title a").tooltip({ bodyHandler: function(event) { return $($(this).attr("href")).html(); }, showURL: false, track: true, delay: 0 });
});

var value = 0
$("#image1").rotate({
   bind:
     {
        click: function(){
            value +=180;
            $(this).rotate({ animateTo:value})
        }
     }

});

I am using the jQuery Rotate plugin
Any recommendations?
Just to reaffirm: The image should do a 180 degree flip if the image is clicked, or if the CELL in which the image is located is CLICKED.
Comment: your code is working fine http://jsfiddle.net/9FMks/1/
Comment: you need to add $("#image1").rotate in th click [http://jsfiddle.net/9FMks/2/](http://jsfiddle.net/9FMks/2/)
Comment: No you see, I want the image to rotate when they click inside the table cell to. Just to reaffirm: The image should rotate when they click the image, and or if they click the cell in which the image is located. @Manish
Comment: It is rotating when you click on the image
Comment: When you click the image, OR the cell it is in @Manish
Comment: You are the man! Submit that as the answer and I'll except it @AbrahamUribe
Answer: you need to add the .rotate inside the "th" .click and preventPropagation on the image1 .click like this
var value = 0
$("th:first").click(function(){//you can add some class or id the first th or select only the first
    value +=180;
    $("#image1").rotate({ animateTo:value});//or $(this).find("img")
});
$("#image1").rotate({
   bind:
     {
        click: function(e){
            e.stopPropagation();//or the image will rotate 360
            value +=180;
            $(this).rotate({ animateTo:value})
        }
     }

});

http://jsfiddle.net/9FMks/2/
Comment: Thanks! Question though, I am trying to implement this to the other columns, but when I add it to the other columns (change the value, id selector for the rows) it doesn't work... Can you use this example and make it work on two columns so I can see how you do it? Thanks for the help @AbrahamUribe


How do I find the positions of my blobs using pydip?

Question: <code>import diplib as dip
from matplotlib import pyplot as plt
#reading video
vid = dip.ImageReadICS(r'C:\Users\mrtij\.spyder-py3\20211123_152822_capture.ics')
vid = vid[0:-1, 0:-1, 325:3149]
smvid = dip.Gauss(vid, [2,2,0])

for i in range(1000, 1001):
    img = smvid[0:-1, 0:-1, i]

    imgmask = dip.IsodataThreshold(img)
    imgmask = dip.Label(imgmask)

    measuremnt = dip.MeasurementTool.Measure(imgmask, img)
    print(measurment)
</code>
I am trying to find positions and sizes of blobs on a relatively low res video, the 20211123_152822_capture.ics file. First I add a smoothing filter and then two masking filters. The MeasurementTool.Measure function however, only returns sizes and not the positions of my blobs. I can't find how to fix this and thought maybe someone here could be of help.
Edit: I only view a single frame here, I plan on saving the coordinates of each blob on each frame, hence the for loop.
Comment: By the way: you are more likely to get an answer here if you use the right tags. Tags is what people filter questions on that they might be able to answer.
Answer: Figured it out, needed to use MeasurementTool.Measure(imgmask, img, ['Size', 'Gravity'])
Comment: "Size" gives you the size of the binary shape, "Mass" gives you the gray-scale "size", the integral over the Gaussian blob. Likewise, "Center" gives you the centroid of the binary shape, "Gravity" gives you the gray-scale centroid. The gray-scale measurements are typically more precise when measuring Gaussian blobs. You can even grow your labeled image a bit to improve precision ([GrowRegions](https://diplib.org/diplib-docs/regions.html#dip-GrowRegions-dip-Image-CL-dip-Image-CL-dip-Image-L-dip-sint--dip-uint-)).


There is no language option in drupal 7 site

Question: When I hit

Administration > Configuration > Regional and language

There is no language option in drupal 7 site. Could I need to install modules? Which modules can I install?
Comment: After enabled local module it's appear language option.
Answer: It is be because you've installed Drupal with English. You can make Drupal Multi-lingual after it is installed, using the quick steps provided on HowTo: Basic Internationalization setup.
You can also have a look at the Multilingual guide for detailed information.
Answer: You need to enable Locale(Drupal core) module. Get new option on configuration page for language(admin/config/regional/language).
Tutorial - Building a multi-language site
How to Build Multilingual Drupal Sites
Comment: Thanks for your reply. It's solved and your answer is right as like I done. Thanks


Smooth Integrable Functions with Integrable Derivatives

Question: Let $f: \mathbb{R}^n \rightarrow \mathbb{C}$ be a smooth function, that is $f \in C^{\infty}(\mathbb{R}^n)$, such that $f$ and all its derivatives belong to the Lebesgue space $L^p(\mathbb{R}^n)$, with $1 \leq p < \infty$. I am trying to prove that f must vanish at infinity, that is it satisfies
\begin{equation}
\lim_{|x| \rightarrow \infty} |f(x)| = 0.
\end{equation}
I could only prove the statement for $p=1$ (see the note below).
Any help is welcome. Thank you very much for your attention in advance.
NOTE (Motivation and Case p=1) First a matter of notation: if $\beta_i$ is a non-negative integer for $i=1,\dots,n$, we call $\beta=(\beta_1,\dots,\beta_n)$ a multi-index, we set $|\beta|=\beta_1+\dots+\beta_n$ as usual, and
\begin{equation}
D^{\beta}f = \frac{\partial^{|\beta|} f}{\partial x_{1}^{\beta_1} \dots \partial x_{n}^{\beta_n}}.
\end{equation}
We also denote by $D_i$ the partial derivative with respect to the i-th coordinate.
The relevance of the question comes from the fact that the space of functions
\begin{equation}
\mathcal{D}_{L^p} = \left \{ f \in C^{\infty}(\mathbb{R}^n) :  D^{\beta} f \in L^p(\mathbb{R}^n) \textrm{ for each multi-index $\beta$} \right \}
\end{equation}
is relevant in the theory of distributions. This vector space is topologised through the family of semi-norms
\begin{equation}
|| f ||_{p,N} = \max \left \{ || D^{\beta} f ||_p : |\beta| \leq N \right \} \quad \quad (N=0,1,2,\dots),
\end{equation}
where $|| . ||_p$ denotes the norm of the space $L^p(\mathbb{R}^n)$.
It was introduced by Schwartz in Théories des Distributions, Chapter VI, $\S{8}$, where I found the statement I am trying to prove, which is a crucial step in a remarkable embedding theorem. To state it, let us also introduce the space $\mathcal{B_0}$ (in the notation used by Schwartz this space is denoted with the symbol $\dot{\mathcal{B}}$) which is the vector space of all $f \in C^{\infty}(\mathbb{R}^n)$ such that $f$ and all its derivatives vanish at infinity. We topologise $\mathcal{B_0}$ thought the family of semi-norms:
\begin{equation}
|| f ||_{\infty,N} = \max \left \{ || D^{\beta} f ||_{\infty} : |\beta| \leq N \right \} \quad \quad (N=0,1,2,\dots),
\end{equation}
where $|| . ||_{\infty}$ denotes the norm of the space $L^{\infty}(\mathbb{R}^n)$.
Schwartz states that if $1 \leq p < \infty$ then each $f \in \mathcal{D}_{L^p}$ not only is bounded, but it also vanishes at infinity. This clearly implies that for $q \geq p$, we have $\mathcal{D}_{L^p} \subset \mathcal{D}_{L^q} \subset \mathcal{B_0}$. Moreover each inclusion is continuous.
Now let us come back to our question. The case $p=1$ can be proved as follows. Let $g \in C^{\infty}(\mathbb{R}^n)$ be a function with compact support such that $g=1$ on the unit ball with center $0$. Fix $r > 0$ and for any $x \in \mathbb{R}^n$ define $g_r(x)=g(x/r)$. Then set
$\phi_r=fg_r$. If $d > 0$ is such that $[-d,d]^n$ contains the support of $\phi_r$, then by repeated integration we get for any $x=(x_1,\dots,x_n)$:
\begin{equation}
\phi_r(x) = \int_{-d}^{x_1} \dots \int_{-d}^{x_n} (T\phi_r)(y) dy = \int_{-\infty}^{x_1} \dots \int_{-\infty}^{x_n} (T\phi_r)(y) dy,
\end{equation}
where $T=D_1...D_n$ (by the way, note that the last equality just says that $\phi_r$ is the convolution of $T\phi_r$ and Heaviside function $H$ on $\mathbb{R}^n$) . For any $R > 0$ define
\begin{equation}
Q(R)= \{ x=(x_1,\dots,x_n) \in \mathbb{R}^n : \min\{x_1,\dots,x_n\} \leq -R \}.
\end{equation}
We have that for any $x \in Q(R), z \in Q(R)$:
\begin{equation}
\left| \phi_r(x) - \phi_r(z) \right| \leq \int_{Q(R)} |(T\phi_r)(y)| dy.
\end{equation}
By using Leibniz formula we get that there exists $C> 0$ such that for any $r \geq 1$ we have
\begin{equation}
\int_{Q(R)} |(T\phi_r)(y)| dy \leq C M(R),
\end{equation}
where
\begin{equation}
M(R) = \max \left \{ \int_{Q(R)} \left| (D^{\beta}f)(x) \right| dx : |\beta| \leq n \right \}.
\end{equation}
By taking $R$ large enough, we get that for any $\epsilon > 0$, there exists $R > 0$ such that for any $x \in Q(R)$, $y \in Q(R)$, we have $|f(x) - f(y)| < \epsilon$. Since $f \in L^1(\mathbb{R}^n)$, we conclude that for any $\epsilon > 0$ there exists $r > 0$ such that $|f(x)| < \epsilon$ for any $x \in Q(r)$. By applying this result to $f(-x)$, we then get the desired conclusion.
A final note. Clearly, the fact that $f$ vanishes at infinity implies that $f$ is bounded. In the case $p=1$, this fact can be directly proved by using the representation above
\begin{equation}
\phi_r(x) = \int_{-\infty}^{x_1} \dots \int_{-\infty}^{x_n} (T\phi_r)(y) dy.
\end{equation}
Actually, from this representation and Leibniz formula we get
\begin{equation}
||f||_{\infty} \leq 2^{n} || g ||_{\infty,n} ||f||_{1,n},
\end{equation}
so that, if we set $A=2^{n} || g ||_{\infty,n}$, we conclude that
\begin{equation}
||f||_{\infty} \leq A ||f||_{1,n}.
\end{equation}
Clearly the same inequality applies to each derivative of f.
So we conclude that $\mathcal{D}_{L^1} \subset \mathcal{B_0}$ and that the inclusion $\mathcal{D}_{L^1} \hookrightarrow \mathcal{B_0}$ is continuous. Moreover, we also get that for $1 < q < \infty$ we have $\mathcal{D}_{L^1} \subset \mathcal{D}_{L^q}$ and that the inclusion $\mathcal{D}_{L^1} \hookrightarrow \mathcal{D}_{L^q}$ is continuous. We have so proved two particular cases of the general embedding theorem stated by Schwartz.
Comment: Dear Dirk, the claim is not mine. As I said, it is made by Laurent Schwartz in Théorie des Distributions, Hermann Paris, 1966, Chapter VI, $\S 8$, pp. 199 - 200. He claims that every $\phi \in \mathcal{D}_{L^p}$, with $1 \leq p < \infty$ is bounded, so that we also have $\phi \in  \mathcal{D}_{L^q}$ with $q \geq p$, and it vanishes at infinity.
Comment: Are you sure that the claim is true? Wouldn't a smooth function with unbounded support of finite measure give a counterexample?
Answer: It is not that difficult, I need the following proposition on a parametrix, somewhere mentioned in Schwartz book for the specific case of a fundamental solution of the iterated Laplace equation.
Proposition: Let $k\in\mathbb{N}, K\subset\mathbb{R}^n$ compact containing $0$ as an interior point. There exist $\varphi\in\mathcal{D}_K^k, m\in\mathbb{N}$, and $\xi\in\mathcal{D}_K$ such that $$ \delta=\Delta^m\varphi+\xi,$$
where $\Delta^m$ is the $m$-times iterated Laplace operator. [$\mathcal{D}_K^k$ denotes the space of $k$-times differentiable functions with support in $K$.]
Not let $K$ be such a compact set and $f\in\mathcal{D}_{L^p}$. Consider the convolution map $C_f\colon \mathcal{D}_K\to \mathcal{B}_0, C_f(\varphi)=f\ast\varphi$. Note that for $\varkappa\in\mathbb{N}^n$ we have (here $q$ is the conjugate exponent of $p$, $\lambda$ is the Lebesgue measure on $\mathbb{R}^n$ and $B_{K}(x) = \{ w \in \mathbb{R}^n: w = x - y, \text{ with } y \in K \} $):
$$
|\partial^\varkappa(f\ast\varphi)(x)| \leq [\lambda(K)]^{1/q} ||\varphi||_\infty\bigl{(}\int_{B_K(x)} |\partial^\varkappa(f)|^p\bigr{)}^{1/p} \longrightarrow 0 \text{ as } |x|\to\infty,
$$ and $$
||\partial^\varkappa(f\ast\varphi)||_\infty \leq [\lambda(K)]^{1/q}||\varphi||_\infty ||\partial^\varkappa f||_p,
$$
showing that $C_f$ is well-defined and continuous. Choose now for $k=0$ an $m$ and a $\varphi_0\in\mathcal{D}_K^0$ according to the proposition.
Now let $(\psi_i)_i$ be a sequence in $\mathcal{D}_K$ with $||\psi_i-\varphi_0||_\infty\to 0$, which is possible as $C_c^{\infty}$ is dense in $\mathcal{D}_K^0$. By the formula above, $(C_f(\psi_i))_i$ is a Cauchy sequence in $\mathcal{B}_0$, a Frechet space, so the limit $f\ast\varphi_0$ (considered in the space of distributions) is in fact an element of $\mathcal{B}_0$ too. So you conclude $$
f = f\ast\delta =f\ast (\Delta^m\varphi_0) + f\ast\xi = \Delta^m(f\ast\varphi_0)+f\ast\xi \in \Delta^m[\mathcal{B}_0] + \mathcal{B}_0 = \mathcal{B}_0.
$$
Comment: I just realize, that the argumentation via Cauchy sequences is not necessary. One may directly apply the estimates to see $f\ast\varphi_0\in\mathcal{B}_0$.
Comment: Dear Vobo, thank you very very much for your invaluable help: I could never solve the problem by myself! There is only a little correction to make in your formulas, I think: the constant $const_{K,f}$ actually does not depend on $f$. If we call it $C$, then we have $|| \partial^{\beta} f ||_{\infty} =  || (\partial^{\beta} \Delta^{m}f) \ast \phi_0 + (\partial^{\beta}f) \ast \xi ||_{\infty} \leq C || \phi_0 ||_{\infty} ||\partial^{\beta} \Delta^{m}f ||_{p} + C || \xi ||_{\infty} ||\partial^{\beta} f ||_{p}$, which proves that $\mathcal{D}_{L^p} \hookrightarrow \mathcal{B}_{0}$ is continuous.
Comment: I also found the proposition about the "parametrix" you stated: it is at p. 191 of Schwartz, Theories des distributions, Hermann Paris, 1966, just after Theorem XIX of Chapter VI.
Comment: A final comment: from the inequality I stated in my previous comment it immediately follows that also the inclusion $\mathcal{D}_{p} \hookrightarrow \mathcal{D}_{L^q}$, with $q \geq p$ is continuous, so completing the proof of the embedding theorem stated by Schwartz (see the note in my post).
Comment: I have replaced $const_{K,f}$ in Vobo's answer (which as I noted before does not depend actually on $f$ and which I called simply $C$ in my previous comment) by its exact value $[\lambda(K)]^{1/q}$.


Reverter um git reset hard

Question: Fiz umas coisas erradas ao fazer alguns teste e apaguei todo meus arquivos tanto no local quanto no github, como faço para reverter e não perder tudo?
os comando que utilizei e creio que foi o que bagunçou tudo foram:
git checkout --orphan gh-pages

git reset --hard

git commit --allow-empty -m "Initializing gh-pages branch"

git push origin gh-pages

git checkout master

Comment: Primeiramente recomendo **NÃO RODE O GC**, segundamente recomendo esperar uma resposta com bastante calma...
Comment: Eu usei isso para reverter um branch local que eu tinha apagado... estou pesquisando o como
Comment: Algo aqui ajuda? https://stackoverflow.com/q/3640764
Comment: @JeffersonQuesado ja tentei algumas coisas não deu certo, acho que perdi tudo mesmo =/
Answer: Arrumar esses dados começa com o git fsck. Esse comando verifica a base de dados do git, para saber se está tudo certo.

seu nome é derivado das ferramentas usadas para verificar a sanidade em sistemas de arquivos, File System Consistency checK

Temos várias opções para esse comando do git:

--unreachable para objetos não alcançáveis de maneira tradicional
--no-reflogs para ignorar o reflog
--full manda o git procurar em outros cantos além do padrão

O seguinte comando usa esses argumentos para procurar coisas não alcançáveis, ignorando o reflog e de tudo que é canto:
git fsck --unreachable --no-reflogs --full

Comment: Então uma dessas SHA era um commit ai dei o comando git cherry-pick "SHA"  e voltou os arquivos ...
Comment: Fico feliz com o resultado o/ Mais cuidado da próxima vez. Sempre que vejo algo desse tipo eu fico passando mal, é muito desespero
Comment: So achei um pouco confusa sua escrita na resposta, não sei se vc é Brasileiro talvez possa ser isso rs, mas sua dica foi o que me ajudou, obrigado.
Comment: Erick, só vi durante a escrita da minha resposta que você tinha tentado essas alternativas. Se não for útil, me avise que eu removo a resposta
Comment: Rodei esse comando e me retorou alguns SHA
Comment: O problema é que deletei a branch aonde eu tinha comitado tudo e dado push, tem algum jeito de recuperar essa branch?
Comment: Bem, talvez algum desses SHA1 seja o do commit do branch master original...
Comment: Opa aguenta ai que acho q consegui recuperar com sua dica, vou avaliar aqui
Comment: @Erick claro que sim, você pode pedir para o git listar o que ele sabe de cada SHA1 desses. Se for um commit, basta dar um `git checkout -b lucky-restore-jeff `, que então o branch `lucky-restore-jeff` apontará para esse commit
Comment: @Erick sou brasileiro e ainda escrevi informal demais. Perdão às gírias e expressões locais, vou tentar reformular em um outro momento para uma linguagem mais adequada

Reverter um git reset hard


Changing e-mail authentication-related DNS records

Question: Suppose that I have e-mail service on my domain, say example.com, with a Sender Policy Framework (SPF) Domain Name System (DNS) record ("TXT" type) for authenticating sending Mail Transfer Agents (MTAs).  Also, suppose that I have either DomainKeys or DomainKeys Identified Mail (DKIM) enabled with the corresponding TXT record in DNS.
What happens if, at some later time, the SPF record needs to change to indicate other IP addresses that are authorized to send mail?  Also, what happens if the DomainKeys or DKIM public key (certificate) needs to change?  Will the old e-mails prior to the change, that recipients already have, be invalidated (get flagged as spam or forgeries) after the changes are made?
Answer: Emails are checked when they're received.
A change to SPF/DKIM records will have no effect on already-processed emails.
Comment: Side note: this is the third hypothetical question you've asked in the last few days. Are you solving actual issues, or just randomly trying to poke holes in RFCs?
Comment: Can you provide more details? Are the results always stored in message headers, and Is there a guarantee that an e-mail client won't run or re-run these tests on messages at a later time -- including if you change e-mail clients or delete all local information about the messages?
Comment: @user553702 Results don't *have* to be stored at all (the RFC says `Received-SPF` is *recommended*). There's no guarantee a particular client didn't do something stupid, but the RFC [recommends against re-running tests](http://www.openspf.org/svn/project/specs/rfc4408.html#op-result) - "Performing the authorization after the SMTP transaction has finished may cause problems, such as the following: (1) It may be difficult to accurately extract the required information from potentially deceptive headers; (2) legitimate E-Mail may fail because the sender's policy may have since changed."


Array of samples from multivariate gaussian distribution Python

Question: I am trying to build in Python the scatter plot in part 2 of Elements of Statistical Learning. First it is said to generate

10 means mk
  from a bivariate Gaussian distribution N((1,0)T,I) and labeled this class
  BLUE. Similarly, 10 more were drawn from N((0,1)T,I) and labeled class
  ORANGE.

I draw one such mean from bivariate gaussian using
from numpy.random import multivariate_normal as mvnorm
cov = [[1, 0], [0, 1]]
mean_or = [1,0]
mean_bl = [0,1]
m_or = [0]*10
m_bl = [0]*10
for i in range(10):
    m_or[i] = list(mvnorm(mean_or,cov))
    m_bl[i] = list(mvnorm(mean_bl,cov))
Is there a more elegant way to generate a vector of 10 means in python, a one-liner replacing the for-loop here ?
Side question : what difference between drawing samples from $N((1,0)T,I)$ and $N((0,1)T,I)$ ?
Answer: As far as I can tell you are drawing samples from that distribution rather than estimates of the mean. I'm not sure if this is what you want to be doing. If you just want to draw samples a simple way would be
from scipy.stats import multivariate_normal
import numpy as np

n_samps_to_draw = 10

mvn(mean=[0,1],cov=np.eye(2)).rvs(n_samps_to_draw)

alternatively, you could just go
n_samps_to_draw = 10
m_or = np.random.multivariate_normal([0,1],np.eye(2),n_samps_to_draw)
m_bl = np.random.multivariate_normal([1,0],np.eye(2),n_samps_to_draw)

if you wanted to sample 10 measurements of the mean, you could just run
from scipy.stats import multivariate_normal
import numpy as np
n_samples_to_est_mean = 500
n_mean_ests = 10

[np.mean(mvn(mean=[0,1],cov=np.eye(2)).rvs(n_samples_to_est_mean),axis=0) for _ in range(n_mean_ests)]

or again with just numpy
import numpy as np
n_samples_to_est_mean = 500
n_mean_ests = 10
[np.mean(np.random.multivariate_normal([0,1],np.eye(2), n_samples_to_est_mean),axis=0) for _ in range(n_mean_ests)]

Comment: the books says drawing 10 means from the bivariate distribution, isn't it what I am doing ? ( drawing 10 points from bivariate distribution )
Comment: without having the book and knowing the context, I'm not sure. It could be that you are trying to estimate the mean 10 times or draw 10 samples. Code for both is above.
Comment: ((1,0),)  is a multivariate normal distribution where the mean of the first dimension is 1 and the mean of the second dimension is 0. ((0,1),)  is the other way around. mean of the first dimension is 0, mean of the second dimension is 1.


Resume AVPlayer stream playback last sample

Question: I am trying to use the native player (AVPlayer) to reproduce a live stream on iOS. However, I have trouble resuming the playback. When I stop the playback and resume it after few seconds, the playback starts from the moment I paused instead of reproducing the current (last) sample of the live stream.
Is there a way to get the last sample, o configure AVPlayer to reproduce from last sample when tapping on Play Button?
Comment: Does re-creating the `AVPlayerItem` from the URL achieve the desired behaviour?
Comment: Finally, the only solution I found is to request the live stream URL each time I need to resume the playback.
Comment: How do you do that?
Comment: Basically, stopping player (destroying the object) and create a new instance of AVPlayer to configure the ViewController. I can paste you code in case you need it.
Comment: you should add the code as an answer and accept it
Answer: My solution is based on denying user to keep the player paused. This is, destroying the player each time playback is resumed. And creating a new instance each time, playback is intended to be resumed.
According to Apple recommendation, the only solution to know if the AVPlayer was stopped is to add KVO. This is:
<code>- (void)setupPlayer {
    AVPlayer *player = [AVPlayer playerWithURL:streamURL];
    AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
    playerViewController.player = player;
    self.playerViewController = playerViewController;

    [self configureConstraintsForView:self.playerViewController.view]; //Add Player to View

    [self setupObservers];

    [player play];
}

- (void)setupObservers {
    [self.playerViewController.player addObserver:self
                                       forKeyPath:@"rate"
                                          options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                                          context:NULL];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
    if ([keyPath isEqualToString:@"rate"] && self.playerViewController.player.rate == CGPointZero.x) {
        [self.playerViewController.view removeFromSuperview];
        [self.playerViewController.player removeObserver:self forKeyPath:@"rate"];
        [self.playerViewController.player pause];
        self.playerViewController = nil;
    }
}
</code>
Then, when user wants to re-engage the player, just call <code>-(void)setupPlayer</code> which start the playback from the last live sample.


Graduate Commutative algebra book or lecture notes in German

Question: It may look strange but I am looking for a Graduate level book / lecture notes on Commutative algebra in German.
I wish the content to be as close as it is possible to Eisenbud's "Commutative Algebra with a view towards Algebraic Geometry".
Any suggestions are welcome.
Answer: Kunz's Einführung in die kommutative Algebra und algebraische Geometrie is fairly standard, and (as far as I can tell) corresponds quite neatly to the book by Eisenbud. If you're looking for something freely available online, I believe this Skript (lecture notes) is quite comprehensive.
Comment: Briliant! Thank you very much.
At first look I like the notes very much.
Comment: Since no other answers were posted I accept the existing one. Thank you a lot.
Comment: @EvgenyKuznetsov no problem :)


Equal Variables Not Returning as Equal

Question: Despite the two groups (userTry and username & passTry and pass) being equal, the code returns nothing occurring in the login function that handles the case when those two are equal. Instead of what should be an introduction to the user, the page returns nothing and I am curious as to why there is no indication of those two variables being equal
<!DOCTYPE html>

Create an Account:

<button onclick="create()">Sign Up</button>
<button onclick="login()">Login</button>
<button onclick="doc()">Make a Document</button>

Comment: Debug what's happening and it will make sense why. Your variable scopes are not what you are assuming they are.
Answer: In the scope of the login function the variables username and pass are not declared. This should give you a ReferenceError.
Answer: Since you've defined the variables username and pass in the function create(), their scope ends after the function ends. So to use them globally you need to declare them globally.
<!DOCTYPE html>

Create an Account:

<button onclick="create()">Sign Up</button>
<button onclick="login()">Login</button>
<button onclick="doc()">Make a Document</button>

Answer: Like others said, the variables are out of scope so you're probably getting an unseen JS error.  It's generally a good idea to use developer tool when messing with JS/Jquery.  Both Chrome and Firefox have Developer tools already built in:
If you're using Chrome:
Options > More Tools > Developer Tools
If you're using Firefox:
Options > Web Developer > Developer Toolbar
If you open those up and then go to your page, you should see the error in the console window.  Also, when making JS changes you may need to periodically delete your cache to get rid of the older JS version.

Equal Variables Not Returning as Equal


How to obtain information about downloads, total installation, and active installation from my published android applications programmatically?

Question: I have a few questions regarding android market(Google play). How can I list my published application by accessing from my google account? What I have done so far is using my application package name as a query string to search my application and display all information which I used android market api to do it. Is there another better way to display all my published or installed applications by accessing from my google accounts?
My second question is about detecting number of downloading and installations of my published application. I have found only google analytics so far(for free) which I need to embedded some codes to monitoring my application. Is it possible for me to access those information from android market publish page . I have found that publish page contains information that I need.
Edited: For second question, I would like to obtain statistical information without adding any new code to my application. Is it possible to provide only google account to grant the permission to get those information?
My application is published. If I am using google analytics to monitoring my application do I need to start my counting from zero?
Sorry for my English and my little knowledge about this.
Thanks in advance..
Edited: .. I have found an application, called "analytics" that is what exactly I want to do. But I still cannot figure it out how it works..
Comment: Sorry for unclear questions... For the first question, I have to list my application package before get the list of my application. Actually, from google account it already know what am I publishing right? So, I am thinking there might be another way to do this without knowing the package name. For second question, I wonder that can I obtain information like number of downloads and installs without embedded any code to my application (just only provide google account to grant the permission).
Comment: Ah ok, I don't know that one. I'll let someone else answer it.
Comment: Thanks for quick respond anyway.. :)
Answer: The only place you will find this kind of information is on your Developer page. That said, if I were wanting to do what you are, I would put up an app on App Engine that either parsed my Dev page on request, or on a schedule. I mention App Engine as personal preference here, you could obviously use anywhere you can host scripts on.
You can then do what you like with the data you have collected, and your app can request this from your site. Assuming you have no qualms with publicising these numbers, you wouldn't need to scare users by authenticating, and would just need a plain html request.
Edit:
In your language of choice, you would need to request your developer page (the one that lists apps and their install count) and would also need to authenticate as yourself to get it. It's for this reason I would use your own hosting if you can. I can't be more specific than this, as I don't know what language you're most likely to be using. It should be trivial to find out how to do an html request and step through the page in whatever language it is though. App Engine pages are written in Java or Python and deployed to the server, while other obvious options are PHP or Perl. On my own server I would most likely use Perl as it's ideal for ripping up html with regexps.
Comment: Can you explain me more about how to parsing my Developer page? Which app do I need to put on App Engine or just put a request script?
Comment: If you were doing it on request, you would just deploy an applet that grabs your page, rips it up, and then spits out the data the Android App is needing.
Comment: You mean grabs the https://market.android.com/publish/ page and split that information one by one? If that so it will take a lot of times and efforts then..  The information there is in flash graph. Is it possible to collect those data also?
Comment: I think you're moving onto a new question re. parsing HTML. Yes there would be lots to parse, but you write code to loop through that, so volume doesn't matter.


Trying to access Cups' web interface gives error 403

Question: I've installed cups and started the service.
Trying to access to the web interface at 192.168.x.x:631 I receive a 403 error.
Answer: I need to enable remote access with this command:
sudo cupsctl --remote-admin

and restart the service
service cups restart

Answer: On Ubuntu Srv 16.04
My /etc/cups/cupsd.conf
(make a copy before)
LogLevel warn
PageLogFormat
MaxLogSize 0
Port 631
Listen /var/run/cups/cups.sock
Browsing Off
BrowseLocalProtocols dnssd
DefaultAuthType Basic
WebInterface Yes
<Location />
  Order allow,deny
  Allow @LOCAL
</Location>
<Location /admin>
  Order allow,deny
  Allow @LOCAL
</Location>
<Location /admin/conf>
  AuthType Default
  Require user @SYSTEM
  Order allow,deny
  Allow @LOCAL
</Location>
<Location /admin/log>
  AuthType Default
  Require user @SYSTEM
  Order allow,deny
  Order allow,deny
  Allow @LOCAL
</Location>
<Policy default>
  JobPrivateAccess default
  JobPrivateValues default
  SubscriptionPrivateAccess default
  SubscriptionPrivateValues default
  <Limit Create-Job Print-Job Print-URI Validate-Job>
    Order deny,allow
  </Limit>
  <Limit Send-Document Send-URI Hold-Job Release-Job Restart-Job Purge-Jobs Set-Job-Attributes Create-Job-Subscription Renew-Subscription Cancel-Subscription Get-Notifications Reprocess-Job Cancel-Current-Job Suspend-Current-Job Resume-Job Cancel-My-Jobs Close-Job CUPS-Move-Job CUPS-Get-Document>
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit CUPS-Add-Modify-Printer CUPS-Delete-Printer CUPS-Add-Modify-Class CUPS-Delete-Class CUPS-Set-Default CUPS-Get-Devices>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Pause-Printer Resume-Printer Enable-Printer Disable-Printer Pause-Printer-After-Current-Job Hold-New-Jobs Release-Held-New-Jobs Deactivate-Printer Activate-Printer Restart-Printer Shutdown-Printer Startup-Printer Promote-Job Schedule-Job-After Cancel-Jobs CUPS-Accept-Jobs CUPS-Reject-Jobs>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Cancel-Job CUPS-Authenticate-Job>
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit All>
    Order deny,allow
  </Limit>
</Policy>
<Policy authenticated>
  JobPrivateAccess default
  JobPrivateValues default
  SubscriptionPrivateAccess default
  SubscriptionPrivateValues default
  <Limit Create-Job Print-Job Print-URI Validate-Job>
    AuthType Default
    Order deny,allow
  </Limit>
  <Limit Send-Document Send-URI Hold-Job Release-Job Restart-Job Purge-Jobs Set-Job-Attributes Create-Job-Subscription Renew-Subscription Cancel-Subscription Get-Notifications Reprocess-Job Cancel-Current-Job Suspend-Current-Job Resume-Job Cancel-My-Jobs Close-Job CUPS-Move-Job CUPS-Get-Document>
    AuthType Default
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit CUPS-Add-Modify-Printer CUPS-Delete-Printer CUPS-Add-Modify-Class CUPS-Delete-Class CUPS-Set-Default>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Pause-Printer Resume-Printer Enable-Printer Disable-Printer Pause-Printer-After-Current-Job Hold-New-Jobs Release-Held-New-Jobs Deactivate-Printer Activate-Printer Restart-Printer Shutdown-Printer Startup-Printer Promote-Job Schedule-Job-After Cancel-Jobs CUPS-Accept-Jobs CUPS-Reject-Jobs>
    AuthType Default
    Require user @SYSTEM
    Order deny,allow
  </Limit>
  <Limit Cancel-Job CUPS-Authenticate-Job>
    AuthType Default
    Require user @OWNER @SYSTEM
    Order deny,allow
  </Limit>
  <Limit All>
    Order deny,allow
  </Limit>
</Policy>

Don't forget open the firewall (if enable)
sudo ufw allow 631


Extension of Holder's Inequality

Question: I found the proof of Generalization of Hölder's inequality from Wikipedia
I get the other part, but I don't get why in case 1: we have the inequality
$\Vert f_1f_2\cdots f_n \Vert_r \leq \Vert f_1f_2 \cdots f_{n-1} \Vert_r \Vert f_n \Vert_\infty $
Could someone explain this?
Comment: You have copied the inequality incorrectly. The product on the right hand side should end with $f_{n-1}$.
Comment: oh yeah you're right :)
Answer: Take $f = f_1 f_2 \ldots f_{n-1}$ and $g = f_n$. Then, by Hölder's inequality we have
$$\|fg\|_r \leq \|f\|_r \|g\|_\infty,$$
i.e.
$$\|f_1 f_2 \ldots f_{n-1} f_n\|_r \leq \|f_1 f_2 \ldots f_{n-1}\|_r \|f_n\|.$$

Extension of Holder's Inequality


Preciso fazer uma consulta no banco de dados. mySQL

Question: Tenho o seguinte banco de dados.
CREATE TABLE IF NOT EXISTS futebol (
    id INT PRIMARY KEY AUTO_INCREMENT,
    nome  VARCHAR(30) NOT NULL,
    estado VARCHAR(2) NOT NULL,
    brasileirao INT NOT NULL,
    copadobrasil INT NOT NULL,
    estadual INT NOT NULL
);

INSERT INTO futebol
(nome, estado, brasileirao, copadobrasil, estadual)
VALUES
("Flamento", "RJ", 5, 3, 33),
("Palmeiras", "SP", 9, 3, 23),
("Santos", "SP", 8, 1, 21),
("Coríntias", "SP", 7, 3, 27),
("São Paulo", "SP", 6, 0, 21),
("Vasco", "RJ", 4, 1, 23),
("Cruzeiro", "MG", 4, 5, 37),
("Internacional", "RS", 3, 1, 44),
("Grêmio", "RS", 2, 5, 36),
("Águia de Marabá", "PA", 0, 0, 0),
("Águia de Marabá", "PA", 0, 0, 1);

E agora preciso fazer essa consulta:
O estado que possui o maior número de títulos no campeonato brasileirão.
Consegui fazer essa query abaixo, mas suponho que não esteja totalmente correta.
SELECT MAX(estado) AS Estado, MAX(CampeonatoBrasileiro) AS Títulos
FROM (SELECT estado, SUM(brasileirao) AS CampeonatoBrasileiro
FROM futebol GROUP BY estado) AS Brasileirão;

Poderiam me ajudar?
Answer: Primeiro determine a quantidade de títulos por estado e depois ordene e pegue o maior.
SELECT estado, SUM(brasileirao) AS CampeonatoBrasileiro FROM futebol GROUP BY estado
ORDER BY 2 DESC LIMIT 1;

Comment: Dessa forma ele está resultado em todos os estados. Preciso exibir apenas um resultado com o estado e número máximo de títulos.
Comment: Muito obrigado cara, funcionou.
Comment: Se a ajuda dele resolveu o seu problema, coloque como RESOLVIDO


Set up a cron job to run drush migrate command

Question: I have a custom module which migrates articles from a remote xml file. Because the RSS feed changes, I want my Drupal site to be in sync with the RSS feed. How do add e.g this command drush mim xml_content to my cron job, so it will update by each cron interval?
Or how do I add it to my custom module with hook_cron()?
Answer: While it's certainly possible programmatically invoke a Drush command in a custom hook handler (via drush_invoke_process()), you shouldn't do this.
Cron tasks are designed to handle periodic, smallish, update tasks on hourly, or sub-hourly, intervals. Migration jobs can get pretty I/O heavy so you shouldn't couple them on the same schedule as ongoing cron maintenance, lest you add potential instability based on some outside service/feed.
You should add a new cron job to your cron runner (e.g. crontab, Jenkins, etc.) that executes the drush mim xml_content on its own schedule. Depending on where your cron system is, the cron job will evoke drush mim xml_content or drush @host-alias mim xml_content (if your cron runner is outside the Drupal host machine).


Finding $\sum_{k=1}^{n-1} \frac{1}{1-e^{2i\pi k/n}}$

Question: We know that
$$\frac{z^n-1}{z-1}=(z-z_1)(z-z_2)(z-z_3).....(z-z_{n-1}), z_k=e^{2i\pi k/n}$$
We get the well known result
$$(1-z_1)(1-z_2)(1-z_3).....(1-z_{n-1})=\lim_{z \to 1} \frac{z^n-1}{z-1}=n.$$
Next, we have
$$\ln \left(\frac{z^n-1}{z-1}\right)=\ln(z-z_1)+\ln(z-z_2)+\ln(z-z_3)+...+\ln(z-z_{n-1})$$
D.w.r.t. $z$, we get
$$\frac{z-1}{z^n-1} \frac{(z-1)nz^{n-1}-(z^n-1)}{(z-1)^2}=\frac{1}{z-z_1}+\frac{1}{z-z_2}+\frac{1}{z-z_3}+....+\frac{1}{z-z_{n-1}}$$
$$\implies F= \frac{1}{1-z_1}+\frac{1}{1-z_2}+\frac{1}{z-z_3}+....+\frac{1}{1-z_{n-1}}=\lim_{z\to 1} \frac{nz^n-nz^{n-1}-z^n+1}{z^{n+1}-z-z^n+1} \to \frac{0}{0}.$$
By L'hospital, we get
$$F=\lim_{z\to 1}\frac{n^2z^{n-1} -n(n-1)z^{n-2}-nz^{n-1}}{(n+1)z^n-1-nz^{n-1}}\to \frac{0}{0}.$$
L'Hospital, once more gives
$$F=\lim_{z\to 1} \frac{n^2(n-1)z^{n-2}-n(n-1)(n-2)z^{n-3}-n(n-1)z^{n-2}}{n(n+1)z^{n-1}-n(n-1)z^{n-2}}\to \frac{n-1}{2}.$$
The question is how else we can get this result?
Comment: There are many elegant proofs here: https://math.stackexchange.com/questions/1222259/how-to-prove-that-sum-k-1n-1-frac11-e2-pi-i-k-n-fracn-12
Answer: Since this problem already received nice solutions in the past, consider the continuous case
$$I_n=\int_1^{n-1}\frac{dk}{1-e^{\frac{2 i \pi  k}{n}}}=\frac {n- 2}2$$


Is there a way to get time zone abbreviations in browser Javascript?

Question: I can get the tz name with Intl.DateTimeFormat().resolvedOptions().timeZone - e.g in my browser's case, America/Los_Angeles. Is there a way to instead get the abbreviation for the time zone (as of asking this question, PDT)?
Answer: Yes, you can format just the time zone name, in short form, and then pull it out of the formatted parts, like this:
Intl.DateTimeFormat('en', {timeZoneName: 'short'}).formatToParts().find(p => p.type === 'timeZoneName').value

Keep in mind a few things though:

The language matters.  'en' here is English.  You could pass undefined to use the end-user's language, but not all languages have time zone abbreviations defined.

The specific date and time matters.  The formatToParts accepts a Date object, but when left absent (or undefined) it uses the current date and time.

Not all time zone abbreviations are well defined.

Not all time zone abbreviations are used consistently.

Not all time zone abbreviations are unique.

Not all time zones have abbreviations.

Thus, I highly recommend avoiding time zone abbreviations if you can.


drupal_html_id() alternative for non-Ajax content?

Question: I am looking for a drupal_html_id() function alternative which returns incremented ID's of non-Ajax contents only.

Is this "ajax/non-ajax" distinction feasible in this context or any other way?
If yes, can anyone provide a solution or recommendation?
Comment: Not sure this makes a lot of sense...perhaps if you explained what problem you're trying solve that would help? Also could you confirm which version you want an answer for? The solution would probably be wildly different between 7 and 8 so you'll need to specify which one answerers should be focusing on. Many thanks
Comment: Actually, to answer the question exactly as it's posed: no, there's no way to do that (just look at the code for `drupal_html_id()` and you'll see why)
Comment: @Clive Thanks, a "no" is a totally adequate answer. To still answer your first question, I am primarily focusing on D8 here. I am setting unique ID's (ex. `#link-key-1--2`, `#link-key-1--3`, etc.) for a set of identical links. These links perform an Ajax request. `drupal_html_id()` then increments the ID in the Ajax response. This is what I want to prevent.
Comment: Ah, that old chestnut :) Usually people want to do this so they can target elements with specific JS and not rely totally on the AJAX API - is that what's happening here?
Comment: Exactly ;) Then, in the JS I will iterate over these elements and perform some actions..
Answer: Here's a simpler version I came up with by altering drupal_html_id() that doesn't pay attention to the $ajax_html_ids. Also note that it produces dashes instead of hyphens:
function foo_html_id($id) {
  $id = strtr(drupal_strtolower($id), array(' ' => '_', '_' => '_', '[' => '_', ']' => ''));
  $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  $id = preg_replace('/\-+/', '_', $id);

  $seen_ids = &drupal_static(__FUNCTION__);

  if (isset($seen_ids[$id])) {
    $id = $id . '_' . ++$seen_ids[$id];
  }
  else {
    $seen_ids[$id] = 1;
  }

  return $id;
}

Answer: You could manually prevent any handling of AJAX within drupal_html_id():
unset($_POST['ajax_html_ids']);
drupal_html_id($some_id);

Be careful with this, because any other AJAX-dependent forms rendered after your code will also be affected.


How to compare outcomes from single variable experiment?

Question: I've performed a study which yielded (?) the following results:
-                   no bike box      bike box     % change
correct procedure      173              55           -27%
incorrect procedure    68               50           69%

Since a result could only be one of the two - correct and incorrect procedure, do I need both quantities in my data, or should I just interpret one of them? If so, which one should I use, or does it depend what i'm trying to demonstrate?
Sorry for being so vague, but I hope this is enough to answer my question.
Answer: You can report percent correct along with sample size $n$, and reporting percent correct instead would be sufficient in most cases, even if you focus more on the percent incorrect in your interpretation.
Answer: If I understand correctly, your IV is "bike box" vs. "no bike box", and your DV is "correct" vs. "incorrrect". The resulting $2 \times 2$ classification table can be summarized with the Odds Ratio: "given the bike-box condition, what are the odds of getting a correct response?" compared to "given the no-bike-box condition, what are the odds of getting a correct response?" If the odds are identical, OR is 1. Yule's Q standardizes OR to the $[-1, 1]$ interval. In R:
> IV    <- factor(rep(c("no bbox", "bbox"), c(241, 105)))
> DVnbb <- rep(c("correct", "incorrect"),   c(173,  68))
> DVbb  <- rep(c("correct", "incorrect"),   c( 55,  50))
> DV    <- factor(c(DVnbb, DVbb))
> cTab  <- table(IV, DV)
> addmargins(cTab)
         DV
IV      correct incorrect Sum
bbox         55        50 105
no bbox     173        68 241
Sum         228       118 346

> library(vcd)                   # for oddsratio()
> (OR <- oddsratio(cTab, log=FALSE))
[1] 0.4323699

> (55/50) / (173/68)             # check: ratio of odds
[1] 0.4323699

> (Q <- (OR-1) / (OR+1))         # Yule's Q
[1] -0.3962873

A corresponding test for equal distributions of your DV within IV groups is Fisher's test.
> fisher.test(cTab)
Fisher's Exact Test for Count Data
data:  cTab
p-value = 0.0008111
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.2619504 0.7158848
sample estimates:
odds ratio
0.4334897

Note that fisher.test() does not report the empirical OR, but a maximum-likelihood estimation.
Edit: Reading your answer, another measure that might capture some relevant information is relative risk: its definition is very similar to OR but calculates the "risk" of getting a correct response given one of the two conditions (and not the odds), i.e., the conditional relative frequency of a correct response.
# risk of getting correct (1st column) response in the two conditions
# calculated as conditional frequency: (cell count) / (sum of row counts)
> (risk <- prop.table(cTab, margin=1))
              DV
IV        correct incorrect
bbox    0.5238095 0.4761905
no bbox 0.7178423 0.2821577

# compare risk in experimental condition to risk in control condition
> (relRisk <- risk[1, 1] / risk[2, 1])
0.7297

Answer: my brother posted the original data.
what is happening here is that i am observing two different conditions. the control is no bike box. this is the baseline. a normal intersection with bike lanes. the experimental condition is an intersection that has bike boxes added. i am attempting to interpret the correct/incorrect use as a function of this change in the environment.  basically, i want to know how best to report the data in a simple and understandable way.
the problem i find it that stuff gets messed up because boxes/no boxes are independent from the correct/incorrect behaviour. i think.
if you take this as percentages
           correct       incorrect

no box (control)   72%          28%
bbox (exp)         52%          48%
i basically want to have a descriptive value so i can explain how the bike boxes effect the outcome of correct or incorrect behaviour at a specific intersection.
the two intersections have different sample sizes which complicate things from my basic psych stats text and knowledge. what i am also thinking is that i need to use the no box data as my baseline in which to compare the experimental condition? that makes sense, no?
what i was thinking is that i could report a decrease of 20% correct behaviour and an increase of 20% for incorrect responses.  so does that mean there is a total difference of 40%? or should i just focus on the 20% and report for one variable, correct or incorrect as to which i see as more important for the report. but to me this data seems incomplete. it doesnt really tell the whole story.
i also thought about doing a percent change ie (new val/old val)-1. but again, i used the percentages of the total per outcome (correct incorrect) as reported above. so i then got those values:
-27% change for correct behaviour due to addition of bike boxes
+69% change for incorrect behaviour due to addition of bike boxes
does that make any sense to what i am trying to show??
i am basically confused as to what makes the best sense to report in this case given the comparison i am making and what is the most accurate data that describes these changes.
thank you all.


continuity of a function series

Question: I need help finding for which $x$ the function:
$$\sum_{n=1}^{\infty}\frac{x+n(-1)^n}{x^2+n^2}$$
is continuous.
I first need to show that the series converges uniformly, the thing is I don't know how to deal with the $(-1)^n$. I tried comparing to the series $\sum_{n=1}^{\infty}\frac{x+n}{x^2+n^2}$ but I think I hit a dead end there.
any suggestions?
Answer: $f(x) = \sum_{n=1}^{\infty}\frac{x+n(-1)^n}{x^2+n^2}$
We need to show that for any $\epsilon$ there exists a $\delta$ such that for all $x,y$ in the domain, when $|x-y|< \delta,$ then $|f(x) - f(y)| < \epsilon$.
The first thing we are going to need is some upper bound on $f(x)-f(y)$
$f(x) -f(y) =$$ \sum_{n=1}^{\infty}\frac{x+n(-1)^n}{x^2+n^2}-\frac{y+n(-1)^n}{y^2+n^2}\\
\sum_{n=1}^{\infty}\frac{x^2y - y^2x+n(-1)^n(y^2-x^2)}{x^2y^2+(x^2+y^2)n^2 + n^4}\\
(y-x)\sum_{n=1}^{\infty}\frac{xy+n(-1)^n(x+y)}{x^2y^2+(x^2+y^2)n^2 + n^4}$
Now we need to show that $\sum_{n=1}^{\infty}\frac{xy+n(-1)^n(x+y)}{x^2y^2+(x^2+y^2)n^2 + n^4}$ converges.
The denominator grow at the order of $n^4$ and numerator grow with the order of $n$, so the series converges.
What we really want to be able to say is that:
There exists an $M$ such that $\sum_{n=1}^{\infty}\frac{xy+n(-1)^n(x+y)}{x^2y^2+(x^2+y^2)n^2 + n^4} < M$
If $x,y$ are big the denominator grows more quickly than the numerator, and if $x,y$ are near $0,$ the numerator collapses to $0,$ while the denominator does not.
It seems obvious, but I suggest you tighten that up.  Anyway, once that has been established you will be able to say.
$|f(x)-f(y)|< M|y-x|$
$\delta = \frac \epsilon M$
Update
You are looking for something along these lines?
let $\{f\}$ be sequence of functions such that
$f_k(x) = \sum_{n=1}^{k}\frac{x+n(-1)^n}{x^2+n^2}$
We want to show that this sequence converges uniformly to $f(x)$
for any $\epsilon>0$ there exists a $K>0$ such that $k,m>K \implies \sup|f_k(x) - f_m(x)|<\epsilon$
$f_k(x) - f_m(x) = \sum_{n=k}^{m}\frac{x+n(-1)^n}{x^2+n^2}$
Unfortunately, I have to run... and can't figure out the last bit.
Comment: thank you for answering. I wish to show the answer by using that if $f_n(x)$ are continuous and the series converges uniformly than it is continuous. the book I study with don't use epsilon-lambda language.
Comment: Are you trying to prove uniform continuity, or uniform convergence?  How will you be defining $f_n$?
Comment: if you mean $f_n(x)$ than it's the all the functions you get when you input different x's. In this case they are all continuous.
Comment: I wish to prove continuity through uniform convergence
Comment: I have put in an update, is this more along the lines you were considering?
Comment: I tried that way but also hit a dead end(altough by looking by "eye" it is smaller than epsilon).
Answer: as I mentioned in Doug answer, if we will prove the series coverges uniformly we can easily show it's contionous.
when $n\rightarrow \infty$ than the series acts as $\sum_{n=1}^{\infty}(-1)^n\frac{n}{x^2+n^2}$. using Leibniz test we know the series converges so from that we conclude that for all x's the series is continuous.

continuity of a function series


android studio , auto refresh data json url every 60 second

Question: am new in android studio and I am trying to make my simple app get JSON data from URL using Volley , everything good but i want to do auto refresh data json .am try to do but not working .
my code if any one can help my
package imo.meteoiraq;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.Timestamp;

public class MainActivity extends AppCompatActivity {
RequestQueue rq;
TextView timeDesc,tempDesc,windspeedDesc,windguestDesc,humdityDesc;
    int ages;
    int temp;
    int windspeed;
    int windguest;
    int humdity;
    long timeupdate;

    String url="/stationlookup?station=I1410&units=metric&v=2.0&format=json";
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rq= Volley.newRequestQueue(this);

        timeDesc= (TextView) findViewById(R.id.timeupdateDesc);
        tempDesc= (TextView) findViewById(R.id.tempid);
        windspeedDesc= (TextView) findViewById(R.id.windid);
        windguestDesc= (TextView) findViewById(R.id.windgustid);
        humdityDesc= (TextView) findViewById(R.id.humdid);

        sendjsonrequest();
    }
public void  sendjsonrequest(){
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {

                JSONObject stationsJO = response.getJSONObject("stations");
                JSONObject I1410JO = stationsJO.getJSONObject("I1410");
                 temp = I1410JO.getInt("temperature");
                 windspeed = I1410JO.getInt("wind_speed");
                 windguest = I1410JO.getInt("wind_gust_speed");
                 humdity = I1410JO.getInt("humidity");
                timeupdate = I1410JO.getLong("updated")* 1000L;

                 tempDesc.setText(Integer.toString(temp));
                 windspeedDesc.setText(Integer.toString(windspeed));
                 windguestDesc.setText(Integer.toString(windguest));
                 humdityDesc.setText(Integer.toString(humdity));
                 timeDesc.setText(getDate(timeupdate));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}

    private String getDate(long  timeStamp){
        try{
            DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
            Date netDate = (new Date(timeStamp));
            return sdf.format(netDate);
        }
        catch(Exception ex){
            return "xx";
        }
    }
}

Comment: you want to hit volley request every 60 secs??
Comment: yes i mean auto update, without from app and back agin
Comment: what do you mean by without from app and back again?? Can you explain clearly
Comment: @sumit , i mean when i enter to app i want see auto update data every 60 sec .
Answer: You can use Handler to do that. For e.g
`
Handler handler = new Handler();
    Runnable runnable = new Runnable() {
         @Override
         public void run() {
             // polling code
             handler.postDelayed(this, SIXTY_SECONDS);
         }
    };Handler.postDelayed(runnable, DELAY_TIME) ;`

Comment: cannot resolve symbol 'handler'
Comment: Edited, you need to create an instance of Handler
Comment: unknown ' class ' runnable
Comment: handler.postDelayed(runnable, DELAY_TIME); with small letter, otherwise it will consider it as static class
Answer: Use this:
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                sendjsonrequest();
                handler.postDelayed(this,6000);//60 second delay
            }
        };handler.postDelayed(runnable,Initial_Delay_time);

Hope this helps!!!
Comment: thank you , cannot resolve symbol 'postDelayed'
Comment: make sure you're importing import android.os.Handler; android os handler
Comment: the code working fine but there no update !! ?
Comment: so check whether you're getting some new data on the server or not??
Comment: yes there update every 60 sec , when i change value sec i see some delay to show data
Comment: can we use postAtTime ?
Comment: I didn't get your point is the update coming or not??
Comment: no, the data its same in app but in server is different data
Comment: share your php code??
Comment: data json not php
Comment: you must have something on server side which sends you response when you hit the url??
Comment: am get information form my weather station via data json my station updata every 60 sec , when i enter to app i see new data but when i keep in side app over 60 sec there no auto update .
Comment: can we make pull up for refresh ?
Comment: yes you can also do that
Comment: any idea for code :) ?
Comment: wait i'll share the code for that but I am trying to figure out why you're not getting update second time when you hit the request
Comment: i dont know , if i put handler.postDelayed(runnable,1000); there delay to show data if i make him 6000 the data show immediately
Comment: wait i see some thing
Comment: can you share the updated code how have you used the handler??
Comment: he just update too times then stop update , do you thing about asynctask ?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149074/discussion-between-sumit-and-aligassan).


Cannot use CreateObject from VB scripts on Windows 7 x64

Question: When I try to create a COM object in VB script on a Windows 7 (64 bit) machine, I always get the following error:
"ActiveX component can't create object 'xxx.xxx'.  Code: 800A01AD
I have applications that use the COM object without any problem.  I have tried running the command line in admin mode, no difference.
Is there any way to enable this?
Answer: The VBScript interpreter (cscript.exe/wscript.exe) comes in two flavors on a 64-bit version of Windows: a 32-bit version and a 64-bit version.
The 32-bit version can create and use 32-bit COM components only, and the 64-bit version can create and use only 64-bit COM components.
By default, .vbs files are associated with the 64-bit version. You COM component is most likely a 32-bit one, hence the error.
You can find the 32-bit version in the <code>%windir%\SysWOW64</code> folder. Launching this version should give you access to all 32-bit COM components:
<code>%windir%\SysWOW64\wscript.exe myScript.vbs
</code>
or
<code>%windir%\SysWOW64\cscript.exe myScript.vbs
</code>
Comment: After banging my head for a couple of hours, you saved the day!
Comment: Do you know how to make this work for HTA applications, I'm seeing code like this:  and making it like this obviously fails: ****
Comment: @JeremyThompson: You need to start the correct version of `mshta.exe`, i.e. the 32-bit version: `c:\Windows\SysWOW64\mshta.exe c:\page.hta`. If you want to enable starting the .hta by double-clicking in Explorer you probably could have your .hta restart with the correct version of mshta.exe.
Comment: Thanks Dirk, I tried `SysWOW64\mshta.exe` initially and it didn't force the VBS files to run under 32 bit that's why I was trying to do it in the HTA file. I'll report back when I get this working.
Comment: %windir%\SysWoW64\wscript.exe in Browse I used the file path in add arguments and I set the program start in path but I could not able to get that done.The task seems to be successfully completed but there is no output as expected


Html is not parsing while parsing a template to send email

Question: I am working on a SAAS based project for which I need to send emails to different clients on different events.
I am using email templates which use tokens (in format {{.TOKENNAME}}) that are made dynamic while sending emails. Now these token are parsed by using "html/template" package.
following is the custom function that I have made to parse these tokens into email body.
    type EmailTemplate struct{
    BookingDetails              string
}

type EmailRequest struct{
    EmailTo      string
    EmailBody    string
}

// get saved html with tokens from database
notificationTemplate, errVal := merchantDb.GetNotificationTemplate()
request := EmailRequest{
    "firstname.lastname@example.com",
    notificationTemplate.Content,
}
templateData.BookingDetails += "
Industry"+industry.IndustryName+"
"

request.EmailSend(templateData)

func (request *EmailRequest) EmailSend(notificationTemplateData interface{}) (bool, error) {
    body, errParse := ParseTemplate(request.EmailBody, notificationTemplateData)
    //email sending code here
}

func ParseTemplate(templateHtml string, data interface{}) (string, error) {
    var body string
    t, err := template.New("my_template").Parse(templateHtml)
    if err != nil {
        return body, err
    }
    buf := new(bytes.Buffer)

    if err = t.Execute(buf, data); err != nil {
        return body, err
    }
    body = buf.String()
    return body, nil
}

Where templateHtml is the email body with tokens and data is the interface holding dynamic values for these tokens. When I use ParseTemplate function to parse tokens as string values then it works fine. But if I have to parse html in one of my tokens then it parses html as string and in email displays html as string.
Can anybody tell me what should I do to parse html in ParseTemplate function?
Comment: Please explain what you mean by "it parses html as string".  Show examples of your input and output, and what output you expected instead.
Comment: @Flimzy, here is my input: "bookingDetails += "Industry"+industry.IndustryName+""" and output is: "IndustryHome Cleaning"
Comment: That should be in your question.
Comment: Okay. But did you get any solution for it ??
Answer: You can convert your strings containing html to the type template.HTML:
str := "
" // gets converted and renders as "<br>"
strSafe := template.HTML(str) // renders as "
"

This marks your string as safe. When you do that, be sure that the containing html is safe, especially when it comes from a third party.
Comment: when I am casting it as template.HTML it is giving me this error: cannot convert data (type interface {}) to type "html/template".HTML: need type assertion. I have taken my html fragment as type interface in function
Comment: Please show us your code where you assemble the `data`.
Comment: You could call `body, errParse := ParseTemplate(request.EmailBody, template.HTML(notificationTemplateData))`. In this case you have to be absolutely certain that there is no malicious code in the body. At least that should compile.
Comment: Still getting the same error by using above statement: cannot convert notificationTemplateData (type interface {}) to type "html/template".HTML: need type assertion
Comment: I see. You could change the signature of EmailSend to `EmailSend(notificationTemplateData string)`. But this is getting a bit hacky. You can pass structs as data to the Execute func and render the fields with pipelines. But that would be quite another matter.
Comment: Sorry I did not get what you wrote
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170371/discussion-between-amandeep-kaur-and-mbuechmann).
Answer: You just need to define type EmailTemplate struct as
type EmailTemplate struct{
    BookingDetails template.HTML
}

Comment: What kind of value will be assigned to BookingDetails ??


Melhores práticas para montar a condição do IF

Question: Faz um tempo que eu tenho a seguinte dúvida: teria alguma diferença de desempenho entre declarar um IF dessas duas maneiras?
Ou mesmo que não tenha diferença na questão de desempenho, alguma dessas formas é mais correta do que a outra?
Forma 1
if(date('N', strtotime($data)) == 3)

Forma 2
$d = date('N', strtotime($data));

if($d == 3)

Comment: Se vc for precisar do valor em `$d` posteriormente, a segunda forma é melhor; se não, a primeira seria melhor.
Comment: Em relação a desempenho tem diferença, a segunda forma tem uma variável a mais, ou seja, um espaço a mais na memória sendo alocado.
Agora qual forma é mais a bonita, isso varia de pessoa pra pessoa. Eu prefiro a primeira
Comment: Bem colocado pelo @RobertodeCampos. Eu, particularmente, sempre prezo pelo desempenho.
Comment: @AndreiCoelho então eu recomendo rever alguns conceitos. PHP não foi feito para ter desempenho, então essas diferenças, tal como perguntada, são irrelevantes para a aplicação, fazendo com que a legibilidade e semântica devem ser sempre prioridade. Se tal diferença de desempenho é relevante para aplicação, PHP não é a linguagem mais indicada.
Comment: Além que o recurso utilizado em ambos os códigos são os mesmos, visto que o PHP precisa armazenar o retorno da função em memória para utilizar na validação da expressão. A diferença é que com a variável ele valor fica acessível pelo desenvolvedor.
Answer: Como já foi dito nos comentários a segunda forma é menos performática  (a diferença, nesse caso, é irrelevante) por ter uma variável sendo criada antes, exemplificando...
No primeiro a função é executada, é feito um gasto X de recursos (memória, processamento...), depois é feita uma verificação, mais um gasto Y.
Na segunda é criada uma variável, gasto Z, e atribuída a ela a execução da função, gasto X, e depois é feita a comparação, gasto Y.
Porém se vai ser feitas muitas verificações com o mesmo valor que vem de uma função é melhor guardar o resultado em uma variável do que executar a mesma função diversas vezes, a não ser claro que em cada verificação mude o valor ao fazer a execução
Answer: Assim como discutido na pergunta Concatenação ou sequenciação de dados: qual tem melhor desempenho?, esse tipo de preocupação com desempenho em relação à linguagem não faz muito sentido. É sabido que o PHP não foi criado para ser uma linguagem performática, então micro-otimizações no código não irão alterar o resultado e devem ser evitados quando ao fazê-las a legibilidade e semântica são prejudicadas. Prefira sempre o código que é mais fácil de ler do que aquele que é supostamente mais rápido.
Você pergunta se há diferença de desempenho entre os dois códigos, não há, exceto se você executá-lo milhares de vezes para então começar a ver alguma diferença. O consumo de recursos das duas soluções é o mesmo. Mesmo que na segunda existe uma variável e na primeira não, o PHP irá precisar armazenar o retorno da função na memória de qualquer forma, a diferença é que com a variável o valor ficará acessível ao desenvolvedor (de maneira direta).
Mesmo que não haja diferença de desempenho, você pergunta qual é o melhor. Na minha opinião, nenhuma das duas formas, pois ambas são difíceis de ler e não são claras quanto ao objetivo. Lendo a documentação, é possível perceber que o parâmetro N de date irá retornar um número referente ao dia da semana de uma determinada data: 1 para segunda-feira, 7 para domingo. Se está verificando se é igual a 3, precisa saber se determinada data é uma quarta-feira. Nenhuma das formas deixa isso claro.
A forma que eu faria é:
$isWednesday = (date('N', strtotime($data)) === "3");

if ($isWednesday) {
    ...
}

Desta forma, eu não preciso recorrer à documentação da função date para saber o que o código está fazendo, pois o nome da variável me diz que estou verificando se é quarta-feira.
Comment: Entendi o que você quis dizer no comentário. Realmente, não faz muita diferença no php, pois geralmente ele é lido uma vez apenas, não faz sentido você prezar pela performance e deixar de lado a semântica.
Answer: Eu faria da primeira forma.
Se usasse um nome de variável que service como documentação do que é aquilo aí eu poderia fazer da segunda forma, mesmo que ficasse um pouco mais lento (talvez nem fique). Mas só faria isto em algo que realmente não fosse óbvio. Seria algo como nosso amigo Anderson fez, mas ali acho desnecessário, mas é só o meu gosto, pode ser bom para programadores iniciantes lerem o código e entender o que está fazendo ali.
Ou eu faria uma função com a condição que retornasse true ou false e chamaria a função no if.
Tudo isso é só uma forma de demonstrar melhor o que você está fazendo. Um comentário pode ser mais eficiente em casos assim.


Efficient way to count unique elements in array in numpy/scipy in Python

Question: I have a scipy array, e.g.
a = array([[0, 0, 1], [1, 1, 1], [1, 1, 1], [1, 0, 1]])

I want to count the number of occurrences of each unique element in the array. For example, for the above array a, I want to get out that there is 1 occurrence of [0, 0, 1], 2 occurrences of [1, 1, 1] and 1 occurrence of [1, 0, 1].
One way I thought of doing it is:
from collections import defaultdict
d = defaultdict(int)

for elt in a:
  d[elt] += 1

is there a better/more efficient way?
thanks.
Comment: Where is the usage of Numpy / Scipy in your example code? Or is this only supposed to get the idea across, wanting to have a Numpy / Scipy function to solve this?
Answer: If sticking with Python 2.7 (or 3.1) is not an issue and any of these two Python versions is available to you, perhaps the new collections.Counter might be something for you if you stick to hashable elements like tuples:
>>> from collections import Counter
>>> c = Counter([(0,0,1), (1,1,1), (1,1,1), (1,0,1)])
>>> c
Counter({(1, 1, 1): 2, (0, 0, 1): 1, (1, 0, 1): 1})
I haven't done any performance testing on these two approaches, though.
Comment: defaultdict will be faster.  John Machin showed this with timings in an answer earlier today (http://stackoverflow.com/questions/4036474/add-new-keys-to-a-dictionary-while-incrementing-existing-values).
Comment: Doesn't use Numpy / Scipy though, as requested by the title of the OP. Also advocates usage of outdated versions of Python. Not sure this is a good answer.
Answer: You can sort the array lexicographically by rows and the look for points where the rows change:
In [1]: a = array([[0, 0, 1], [1, 1, 1], [1, 1, 1], [1, 0, 1]])

In [2]: b = a[lexsort(a.T)]

In [3]: b
Out[3]:
array([[0, 0, 1],
       [1, 0, 1],
       [1, 1, 1],
       [1, 1, 1]])

...

In [5]: (b[1:] - b[:-1]).any(-1)
Out[5]: array([ True,  True, False], dtype=bool)

The last array says that the first three rows differ and the third row is repeated twice.
For arrays of ones and zeros you can encode the values:
In [6]: bincount(dot(a, array([4,2,1])))
Out[6]: array([0, 1, 0, 0, 0, 1, 0, 2])

Dictionaries can also be used. Which of the various methods will be fastest will depend on the sort of arrays you are actually working with.
Answer: for python 2.6 <
import itertools

data_array = [[0, 0, 1], [1, 1, 1], [1, 1, 1], [1, 0, 1]]

dict_ = {}

for list_, count in itertools.groupby(data_array):
    dict_.update({tuple(list_), len(list(count))})

Answer: The numpy_indexed package (disclaimer: I am its author) provides a solution similar to the one posted by chuck; which is a nicely vectorized one. But with tests, a nice interface, and many more related useful functions:
import numpy_indexed as npi
npi.count(a)


MLE of Cauchy distribution in R

Question: I am trying to compute the following "approximate Maximum Likelihood Estimate" in R. I am a little lost as to how to do this though:

any hints would be appreciated.
Comment: This looks more like a statistics/math question than programming. I'm voting to migrate this to CV.
Comment: @RomanLuštrik its purely about how to implement this in R, why is that a statistics question
Comment: Use numeric optimization on the function.
Comment: Then I think you should show us what you've tried and where you get stuck. See `?optim`.
Answer: You want to use the function nlm() to calculate the argmax, which requires a function to be optimized as the first argument and the an initial guess at the parameters as the second argument, like so:
# define g(x;gamma)
g  <-  function(x,gamma) {
    (1/pi) * ( gamma / (x^2 + gamma^2) )
}

# define y here so it can be used inside fun() via lexical scoping
y <- blah blah blah

# the function to be optimized is optimized over the first argument.
fun  <- function(x){
    # separate the first argument into the variables needed
    # for opimization
    phi = x[1:2]
    psi = x[3:4]
    gamma = x[5]

    # PERFORM THE BIG SUM
    out  <-  0
    for(t in seq(r + 1,T-s)){
        # calculate A
        A  <-  (y[t]   * (psi[1]*phi[1] + 1)
                + (psi[1]*phi[2] + phi[1]) * y[t-1]
                - phi[2]* y[t-2]
                - psi[1] * y[t+1]
                )
        # increment the sum
        out  <-  out + log(g(A,gamma))
    }
    #nlm performs the argmin, so we'll return -out
    -out
}

# do the optimization
out  <-  nlm(fun,
        # initial guess at the parameters,
             c(0,0,# phi
               0,0,# psi
               0))# gamma

phi_hat   <- out$estimate[1:2]
 psi_hat   <- out$estimate[3:4]
gamma_hat <- out$estimate[5]

Note that nlm() does not make restrictions on the arguments so, for
example, if you need the arguments to be positive, you need to make a
transformation like this:
phi = exp(x[1:2])

in fun()  and also here:
phi_hat   <- exp(out$estimate[1:2])

MLE of Cauchy distribution in R


When the destroy() has been declared?

Question: import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException,
            InterruptedException {
        System.out.println("Creating Process");

        Process process = Runtime.getRuntime().exec("notepad.exe");

        System.out.println("Waiting for 3 Sec");

        Thread.sleep(3000);

        process.destroy();

        System.out.println("process Destroyed");
    }
}

As far as I know Process Class is an abstract class and it has this method for destroy()
abstract void destroy();
But as you can see when I invoke the destroy method for the process Object it knows exactly what to do!
When this method has been declared ?
Answer: Process is an abstract class, but what you get from Runtime.getRuntime().exec("notepad.exe") is an instance of a concrete subclass of Process. In this concrete subclass, there is an implementation for the abstract destroy() method.
You don't need to know which concrete subclass is returned. What matters is that it's a Process. Chances are that the concrete subclass used on Windows is different than the one used on MacOS or Linux. But they all are subclasses of Process. That's what polymorphism is.
Comment: You are too quick for me :/
Comment: Thanks sir .. I almost got what you are telling me .. Any way .. can we put our hand on the implementation for the destroy() method itself?  the one that running for windows .. ?
Comment: @WaseemSwaileh: why do you want that?
Answer: From java.lang.Process:
"The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it."
It is the job of the subclass to define destroy().
And from ProcessImpl.java we have:
/* This class is for the exclusive use of ProcessBuilder.start() to
 * create new processes.

...

public void destroy() { terminateProcess(handle); }

When the destroy() has been declared?


Can a player accidentally tap a penalty having elected to kick for goal?

Question: Lets' say that team A are playing team B,
Team A get a penalty inside team B's half. Team B withdraw 10 metres; team A tell the ref they want to kick for goal and the ref does their fancy-pointing-arms thing.
So far, so good.
Often in this situation you'll see a player from team A unconsciously do something while they're waiting for the tee that otherwise could be interpreted as tapping the penalty. Things like dropping the ball and kicking it from foot to foot, a small (say 1/2 metre) kick along the ground, kicking the ball to themselves etc. All within range of the mark for taking a tap penalty and all technically tapping the penalty, but clearly with no intent to do so.
Here's the question:
If this occurs, can the penalty be deemed to have been taken and are team B thus entitled to come forward and pick up the ball/tackle the player in possession?
Comment: The "fancy-pointing-arms thing" is actually an instruction to the touch judges (assistant referees) to go behind the posts to verify the kick.
Answer: In rugby union, No. Law 21.5(b) is the relevant one here.

21 Penalty and Free Kicks

21.5 Scoring a Goal from a Penalty Kick

21.5(b)

If the kicker indicates to the referee the intention to kick at goal, the kicker must kick at goal. Once the kicker has made the intention clear, there can be no change of the intention. The referee may enquire of the kicker as to the intention.

The only circumstances in which a kick at goal then might not actually occur are -

if the kicker doesn't take the kick within 1 minute of indicating their intention. (law 21.4(c) - scrum to the non-kicking team.)
if the kicker doesn't take the kick correctly (law 21.5 - scrum to the non-kicking team)
if the kicker's team commit foul play before the kick is taken (law 10.4(n) - penalty to the non-kicking team)
Comment: Nice answer. The one last little question I would ask about it is if knocking the ball about could be interpreted as taking the kick incorrectly, assuming it's at the mark, is a kick and it moves a visible distance, but not at the goal. Obviously a ref wouldn't bother, but if the opponents captain pointed it out, would the ref be obliged to act?
Comment: No he wouldn't be obliged to act.   "6.A.4(a) The referee is the sole judge of fact and of Law during a match."  See [here](http://therugbyref.blogspot.co.uk/2011/01/urban-myth-no-3-im-captain-i-have-right.html) for comments on a captain's right to talk to a referee.


`Score.skipTypesetting` and multi-measure rests

Question: I want to produce a version of a score where a few bars are snipped off, using Score.skipTypesetting as in the following example:
cuts = {
  s1
  \set Score.skipTypesetting = ##t
  s1*2
  \set Score.skipTypesetting = ##f
}
clarinet = \relative {
  c'1 cis d dis e
}
trombone = \relative {
  R1*5
}

\score { \new StaffGroup <<
  \new Staff << \cuts \clarinet >>
  \new Staff << \cuts \trombone >>
>> }

However, this produces an incorrect multi-measure rest in the part which has rests
(a 3-bar rest under the 1-bar c', followed by two correct 1-bar rests). I understand that the multi-measure rest is typeset before Lilypond stops typesetting the staff; however, I could not find how to prevent this (I tried e.g. using \Score.skipBars = ##t or slightly displacing the skipTypesetting commands).
Is there a way to "cleanly" remove those measures?

The intended use case is that of a full orchestra score (e.g. full opera-size), where it will not be possible in practice to insert the skipTypesetting properties in each individual part; moreover there will be several such cuts. Also, I need to keep the source for these measures, since this is for a separate, abridged version of the piece. (Besides, removing those individual measures from the source would also be infeasible in practice at this scale).
Answer: You could try to add a skipped grace to allow for typesetting of the bar and to suspend counting of time (to not count skipped measures):
cuts = {
  \omit Score.StaffEllipsis
  s1
  \grace { s1024 }
  \set Score.skipTypesetting = ##t
  \cadenzaOn
  s1*2
  \cadenzaOff
  \set Score.skipTypesetting = ##f
  \grace {}
}
clarinet = \relative {
  c'1 cis d dis e
}
trombone = \relative {
  R1*5
}

\score { \new StaffGroup <<
  \new Devnull \cuts
  \new Staff \clarinet
  \new Staff \trombone
>> }


Checking Date part only, of a DateTime field

Question: I have a query like :
SELECT ..
        FROM ...
        WHERE ...
        AND ISNULL(ICA.actual_appearance_date, ICA.scheduled_appearance_date)
            BETWEEN LO.order_start_date
                AND ISNULL(LO.actual_expiry_date, LO.expected_expiry_date)

Is there a neat way to only check that the actual_appearance_date is between the start and end date, but not include time?
So:
Appearance Date is 03/Oct/2011 @ 14h00... and the dates we're check are 03/Oct/2011 @ 15h00 and and 07/Oct/2011 @ 10h00.
At the moment, that would not yield a result because of the time factors. I need to do a between on the date part only... So, between 03/Oct/2011 @ 0h00 and really 08/Oct/2011 @ 0:00.
Is there a neat way to do this?
Edit:
We're developing for a 2008 machine, but we're developing ON 2005 machines. Long story, but I can't use the nice and neat DATE fix.
I am trying the DATEADD method, but am finding an issue.
This is not returning the result I expect:
DECLARE  @Table TABLE
(
    StartDate DATETIME,
    EndDate DATETIME
)

INSERT INTO @Table VALUES ('02-Jan-2011 13:00:00', '07-Jan-2011 15:30:00')

SELECT * FROM @Table
DECLARE @Date DATETIME
SET @Date = '07-Jan-2011 16:00:00'

SELECT
    CASE WHEN
        @Date BETWEEN DATEADD(dd,DATEDIFF(dd,0,StartDate),0) AND DATEADD(dd, DATEDIFF(dd,0,EndDate),0)-- must cover the appearance date or still open
    THEN 1
    ELSE 0
    END AS Result
FROM @Table

Must I add +1 to the BETWEEN dates to include the last date? 'BETWEEN' doesn't seem to be inclusive of the last date..
Answer: You have SQL Server 2008 so just cast to date
SELECT ..
FROM ...
WHERE ... AND
     CAST(ISNULL(ICA.actual_appearance_date, ICA.scheduled_appearance_date) AS date)
        BETWEEN
           CAST(LO.order_start_date AS date)
        AND
           CAST(ISNULL(LO.actual_expiry_date, LO.expected_expiry_date) AS date)

For SQL Server 2005 and earlier, use the DATEDIFF/DATEADD trick: Best approach to remove time part of datetime in SQL Server
Do not use varchar or float conversions
Edit:, for SQL Server 2005
You need to apply the DATEADD/DATEDIFF to all values
...
SELECT
    CASE WHEN
         DATEADD(dd,DATEDIFF(dd,0,@Date),0)
              BETWEEN DATEADD(dd,DATEDIFF(dd,0,StartDate),0)
              AND DATEADD(dd, DATEDIFF(dd,0,EndDate),0)
    THEN 1
    ELSE 0
    END AS Result
FROM @Table

Or
WHERE ... AND
     DATEADD(dd,DATEDIFF(dd,0,ISNULL(ICA.actual_appearance_date, ICA.scheduled_appearance_date),0)
        BETWEEN
           DATEADD(dd,DATEDIFF(dd,0,LO.order_start_date),0)
        AND
           DATEADD(dd,DATEDIFF(dd,0,ISNULL(LO.actual_expiry_date, LO.expected_expiry_date),0)

Comment: This looks a lot safer than the VARCHAR fix. And because we're using inbuilt data types - SQL won't care if it's DMY or MDY, right?
Comment: Also, am I right in saying that because we're using BETWEEN, the 2nd date should have 1 day added to it? So, the "AND
           CAST(ISNULL(LO.actual_expiry_date, LO.expected_expiry_date) AS date)" should have 1 day added, or else it won't include that day?
Comment: @cdotlister: correct, we stcik with native date?time formats so language etc is irrelevant. You don't need to add a day because BETWEEN is inclusive (`>=` and `<=`). So "07 Oct 2011 14:00" will match to "07 Oct 2011 11:00" because both change to "07 Oct 2011". Even though a straight comparison *with* time will be false
Comment: I have had to modify my initial post, due to a problem with regards 2008/2005. Basically, we have a crazy situation where we're coding for a 2008 server in production and UAT - but all our dev servers are ... 2005! I know - upgrade them! But this is government, and things go slow... so I can't use DATE. Hope you can assist.
Comment: @cdotlister: You need to run the dateadd/datediff on all values. My orginal answer has CAST on all values but your update didn't.
Answer: You can use the convert process then compare:
Convert(Datetime,Convert(Varchar,OrderDate,106),110)


Sum of all combination in SQL Server without repeating same values

Question: This link does provide a close solution:
Sql Query : Sum , all the possible combination of rows in a table
The logic here is
n! / k!(n-k)!     where k = 1 to n

But I want the values which are not repeating
Example: TEMPTABLE
+----+-------+
| ID | Value |
+----+-------+
| 1  | 5000  |
| 2  | 5000  |
| 3  | 5000  |
| 4  | 5000  |
+----+-------+

For this table K should be 1 because only one way you can arrange the set
So the combination will be
5000
5000 + 5000 = 10000

5000 + 5000 + 5000 = 15000

5000 + 5000 + 5000 + 5000 = 20000

Total of 4 combinations
4! / 1!(4-1)! = 4

For the answer above the combination will be
= 4 + 6 + 4 + 1 = 15

11 of those will be same results
Problem will be if more number of entries are there the execution time will be more, so I want to remove those repeating totals while calculating the total.
Can anyone please help.
Answer: Just add a distinct or a group by depending what do you need
--To get the values
;With selfrec as (
  Select t.Value, t.ID, 0 as Level From #TempTable t
       UNION ALL
  Select t2.Value + t1.Value as Value, t1.ID, Level + 1 From #TempTable t1
  Inner Join selfrec t2 on t1.ID < t2.ID
  Where Level < 4 -- limit the number of recursions
)
Select Value
From selfrec
Group by value

-- To get the number of combinations
;With selfrec as (
  Select t.Value, t.ID, 0 as Level From #TempTable t
       UNION ALL
  Select t2.Value + t1.Value as Value, t1.ID, Level + 1 From #TempTable t1
  Inner Join selfrec t2 on t1.ID < t2.ID
  Where Level < 4 -- limit the number of recursions
)
Select COUNT(DISTINCT Value)
From selfrec

Comment: Problem will be if more number of entries are there the execution time will be more, so I want to remove those repeating totals while calculating the total.
Comment: Is a recursive function, you'll need to calculate each combination anyway, adding that validation to the CTE would have more impact in the performance than this, also, in a recursive CTE is not possible to use the recursive expression more than once (ex, to add an EXISTS condition)
Comment: Ok, but can we do this without **Recursive CTE** than?
Comment: The other way is using temp tables and loops, but anyway they need to iterate for all combinations and check if the value already exists, the cost will be the same. I think that this is the best option


Error While Creating Azure SQL Server Failover Group

Question: I am trying to implement a failover group in Azure for my SQL servers but I am getting this error while doing so.
Further, I have question too. I got to know that Secondary Server should not be in the same region, but I am anxious to know whether it should be in same Resource Group? I dont know whether the error relates to it.
Appreciate if anybody could help and clarify my question.
Answer: Few things required for sql managed instance HA in azure :

Vnet peering between both regions
NSG rules allowing traffic
Both MI instance in same resource group


Modelstate validation always return false using a dropdownlist

Question: NOTE: Code updated to take into account the comments and answer made below.
In my MVC app I need sometimes to make references to other objects (like a many-to-many relationship, or one-to-many relationship).
So I have this model:
public class ObjInfo
    {
        [Required(ErrorMessage = "Obj ID is required.")]
        [Display(Name = "ObjID")]
        public int m_Id { get; set; }

        [Required(ErrorMessage = "Obj Name is required.")]
        [Display(Name = "Obj Name")]
        public string m_Name { get; set; }

        [Display(Name = "Obj Number")]
        public int m_Number { get; set; }

        (...)

        [Required(ErrorMessage = "Other Obj is required.")]
        [Display(Name = "OtherObj")]
        public int m_OtherObjID { get; set; }

        public OtherObjInfo m_OtherObj { get; set; }

        (...)
    }

I have default and parameters constructors as well and can show them as needed, though I am not sure if they are at fault. Anyway.
In my controller, I have the two create methods following MVC methods:
        //
        // GET: /Obj/Create

        public ActionResult Create()
        {
            ViewBag.List = new SelectList(PopulateDDLs(), "OtherObj", "Other obj ID");
            return View();
        }

        //
        // POST: /Obj/Create

        [HttpPost]
        public ActionResult Create(Objinfo obj)
        {
            if (ModelState.IsValid)
            {
                m_ObjManager.CreateObj(obj);
                return RedirectToAction("SearchIndex");
            }

            ViewBag.List = new SelectList(PopulateDDLs(), "OtherObj", "Other obj ID");
            return View(obj);
        }

And, finally, here's how my "Create" view is coded:
@model MyApp.Models.ObjInfo

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>OBJ</legend>

            @Html.LabelFor(model => model.m_Id)

            @Html.EditorFor(model => model.m_Id)
            @Html.ValidationMessageFor(model => model.m_Id)

            @Html.LabelFor(model => model.m_Name)

            @Html.EditorFor(model => model.m_Name)
            @Html.ValidationMessageFor(model => model.m_Name)

            @Html.LabelFor(model => model.m_Number)

            @Html.EditorFor(model => model.m_Number)
            @Html.ValidationMessageFor(model => model.m_Number)

        (...)

            @Html.LabelFor(model => model.m_OtherObj , "Other Obj")

            @Html.DropDownList(model => model.m_OtherObjID, ViewBag.List as SelectList, "--- Select Other Obj ---", new {@class = "OtherObjInfo "})
            @Html.ValidationMessageFor(model => model.m_OtherObj)

            <input type="submit" value="Create" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Basically, the problem is that each time I click on the "create" button, the ModelState validation is always false for the OtherObj even if something is selected in the dropdownlist. Every other values are correct except this one.
I don't understand why and I would greatly appreciate your help on this one, thank you for your help!
 After code edited **
Now I get a crash as I enter the "Create" view:
DataBinding: 'System.String' does not contain a property with the name 'OtherObj'.

Exactly on the line where my dropdownlistfor is located.
The datavalueField and dataTextField are supposed to refer to what exactly?
Comment: what is the difference between your dropdown helper and other helpers?
Comment: Oh, ok! I'm using DropDownList, and not DropDownListFor. I saw them, but I have yet to figure out how they work. I must be honest on that.
Comment: Err, none, currently it displays the name of the OtherObj (if I understood your question well)
Comment: it didn't occur to you that every other helper has a **For** in it is a difference?
Comment: tightly bound relationships are "tighter"
Comment: Thats just the cosmetic hint. No lambda, and no tight association.
Answer: add otherObjectId to your model
public class ObjInfo
{
    public int m_Id { get; set; }

    ...

    [Required(ErrorMessage = "Other Obj is required.")]
    [Display(Name = "OtherObj")]
    public int otherObjectId { get; set; }

    public OtherObjInfo m_OtherObj { get; set; }

    ...

}

controller
public ActionResult Create()
{
    ViewBag.List = new SelectList(PopulateDDLs(), "Id", "Name");
    return View();
}

[HttpPost]
public ActionResult Create(Objinfo obj)
{
    if (ModelState.IsValid)
    {
        m_ObjManager.CreateObj(obj);
        return RedirectToAction("SearchIndex");
    }

    ViewBag.List = new SelectList(PopulateDDLs(), "Id", "Name");
    return View(obj);
}

view

    @Html.LabelFor(model => model.m_OtherObj , "Other Obj")

    @Html.DropDownListFor(model => model.otherObjectId, ViewBag.List as SelectList, "--- Select Category ---", new { @class = "some_class" })
    @Html.ValidationMessageFor(model => model.m_OtherObj)

better way is using strongly typed helpers. All your helpers are strongly-typed (editorfor, textboxfor, dropdownlistfor,...) except dropdownlist.
if you want to bind DDL value to your model, You should use dropdownlistfor instead of dropdownlist.
your model state is not valid, because you dont bind required value as DDL to model.
Comment: I'll try this, I will get you back on the results.
Comment: Haha, thanks for the word, Dave ;) I do understand your point, though. You are right, as is @AliRiza. :)
Comment: Ok, I re-written everything, but I get a crash when the create view is done: "DataBinding: 'System.String' does not contain a property with the name 'Id'."
Comment: You should write otherObject Text and Id. I mean Name is text and Id is value.
Comment: `new SelectList(PopulateDDLs(), "otherObjectPrimaryKey", "otherObjectNameOrText");`
Comment: Ok, I don't get it. The first parameters is the dataValueField, and the second is the dataTextField, but they are referring to what exactly? What sould I write there?
Comment: What properties are there in you OtherObjInfo ?
Comment: [Key]
        [Display(Name = "Other Obj Id")]
        public int m_Id { get; set; }

        [Display(Name = "Other Obj Name")]
        public string m_Name { get; set; }

        [Display(Name = "Other Obj Symbol")]
        public string m_SymbolText { get; set; }
Comment: `new SelectList(PopulateDDLs(), "m_Id", "m_Name");`
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24845/discussion-between-herve-simard-and-aliriza-adiyahsi)
Comment: Thanks to both of you, I'm nearly done with this. But I still have a question.
I want to know why now my ModelState.IsValid comes true, but the m_OtherObjInfo is null?
Comment: there is required field in your model and you pass it with null value, Now you select it from a dll and not null, so you get true