Where does GEE formula come from?

Question: I am trying to understand where GEE formula comes from.
Here is the formula:
$$Q(\beta) = \sum_{i}^{n} { \frac{d\mu}{d\beta}\boldsymbol{\Sigma}^{-1}(y_i - \mu)}$$
I am just wondering how they came up with this formula. In this formula, I see $\frac{y_i-\mu}{\boldsymbol{\Sigma}}$... this reminds me of a $Z$ Score.
I also know that GEE is based on quasi-likelihood (QL). QL is where you modify the likelihood to add extra terms to the probability distribution function (e.g, Poisson over-dispersion). When modified, the QL is no longer based on a real probability distribution (e.g., the modified probability distribution integral won't be 1).
But I can't understand how they come up with the GEE formula. This looks like a bunch of terms pasted together (e.g., why derivative of $\mu$ here)... where does this formula come from?
Answer: No one single person came up with the GEE formulation, but if we had to pick the most well known reference, it would be Liang Zeger (1986). They penned the most widely used terminology and notation for these models.
You're on the right track to connect the GEE to the quasilikelihood. So Wedderburn 1974 deserves some credit. About the same time, several highly generalized theories were being codified. McCullogh and Nelder (1983) released the first edition of Generalized Linear Models which, in part, emphasized the GLM as an abstract, method of moments type estimator which was derived using a link function and a variance function and, like quasi-likelihood, may not correspond to a proper set of likelihood equations, but has well defined limiting behaviors for inference and estimation.
There were several completely unrelated efforts to derive robust variance estimation which was unified under Liang, Zeger's GEE framework. Eicker (1963, 1967), Huber (1967), and White (1980) explored the "Heteroscedasiticity-consistent" variance estimator (HC). As pointed out by Boos and Stefanski (2013), Freedman (2006), and others, sandwich variance estimation very closely resembles model-based inference when assumptions are met. This is because in GLMs as it is for GEE, the maximum likelihood technique requires a very specific relationship between the link and the variance for exponential families.
As a motivating example, consider modeling a binomial response with logistic regression. The logistic link function is: $ g(x) = \log x / (1-x)$ and its inverse is the sigmoid which expresses the probability of response as a function of the linear predictor. $g^{-1}(x) = \exp(x) / (1-\exp(x)) = \mu$. Taking the derivative of the inverse link with respect to $x$ gives $\frac{\partial}{\partial x} g^{-1}(x) = g^{-1}(x)(1-g^{-1}(x)) = \mu(1-\mu)$ which is readily recognized as the mean-variance relationship in a binomial random variable. For this reason, the general GEE framework applied to this logistic regression scenario:
$$ \mathcal{U}(\beta) = D^TV^{-1}(y - g^{-1}(X^T\beta))$$
would yield the usual likelihood equations for a logistic regression.

References
Eicker, F. (1963), Asymptotic normality and consistency of the least squares estimator for families of linear regressions. Annals of Mathematical Statistics, 34(2), 447–456.
Eicker, F. (1967), Limit theorems for regressions with unequal and dependent errors. Pp. 59–82 in Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability. Berkeley: University of California Press.
Huber, P.J. (1967), The behavior of maximum likelihood estimates under non-standard conditions. Pp. 221–233 in Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability. Berkeley: University of California Press.
Liang, K.-L., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22.
Wedderburn, R. W. M. (1974). Quasi-Likelihood Functions, Generalized Linear Models, and the Gauss-Newton Method. Biometrika, 61(3), 439–447.
White, H. (1980), A heteroskedastic-consistent covariance matrix estimator and a direct test of heteroskedasticity. Econometrica, 48(4), 817–838.
Comment: thx! can u pls help us understand why GEE is only suitable for averaged population/marginal effects .... and not for individual level effects?
Comment: is GEE related to moment estimation?

Where does GEE formula come from?


Linear Algebra of Symmetric Sums

Question: I believe the following is true, but I do not know how to prove it.
Given two sets of distinct non-zero complex numbers $z_1, \dots , z_n$ and $w_1, \dots , w_n$, if
$$ \begin{bmatrix}
  z_{1}  & \cdots & z_{n} \\
  z_{1}^{2} & \cdots & z_{n}^{2} \\
  \vdots  & \ddots & \vdots  \\
  z_{1}^n  & \cdots & z_{n}^n
 \end{bmatrix}
\begin{bmatrix}
  1 \\
  1 \\
  \vdots  \\
  1
 \end{bmatrix}
=
\begin{bmatrix}
  w_{1}  & \cdots & w_{n} \\
  w_{1}^{2} & \cdots & w_{n}^{2} \\
  \vdots  & \ddots & \vdots  \\
  w_{1}^n  & \cdots & w_{n}^n
 \end{bmatrix}
\begin{bmatrix}
  1 \\
  1 \\
  \vdots  \\
  1
 \end{bmatrix}
$$
then $w_1, \dots , w_n$ is a permutation of $z_1, \dots , z_n$.
Any ideas?

Background
Again given distinct non-zero complex numbers $z_1, \dots , z_n$, consider the matrix equation:
$$ \begin{bmatrix}
  1  & z_{1}  & z_{1}^2 & \cdots & z_{1}^{n-1} \\
  1  & z_{2}  & z_{2}^2 & \cdots & z_{2}^{n-1} \\
  \vdots  & \vdots &  \vdots & \ddots  & \vdots  \\
  1  & z_{n}  & z_{n}^2 & \cdots & z_{n}^{n-1}
 \end{bmatrix}
\begin{bmatrix}
  a_0 \\
  a_1 \\
  \vdots  \\
  a_{n-1}
 \end{bmatrix}
=
\begin{bmatrix}
  0 \\
  0 \\
  \vdots  \\
  0
 \end{bmatrix}
$$
By the fundamental theorem of algebra, this equation can only be satisfied when the $a_1, \dots , a_n$'s are all zero, and so the matrix is non-singular. Since the complex numbers $z_1, \dots , z_n$ are non-zero, the matrix
$$
 \begin{bmatrix}
  z_{1}  & z_{1}^2 & \cdots & z_{1}^{n} \\
  z_{2}  & z_{2}^2 & \cdots & z_{2}^{n} \\
  \vdots &  \vdots & \ddots  & \vdots  \\
  z_{n}  & z_{n}^2 & \cdots & z_{n}^{n}
 \end{bmatrix}
$$
is also non-singular, and so its columns form a linearly independent basis for $\mathbb{C}^n$. Considered in this light, the claim above compares two bases formed in this way and says, in effect, if the dot-products of each member of the bases with $[ 1,1, \dots ,1]$ are the same, then the two bases are the same.
Comment: I played around with induction and got stumped by the inductive step. With the insight provided by the answers below, I now see where the inductive step was headed.
Answer: Yes, this is true. It follows from Newton's identities, which show that the first $n$ symmetric sums of $n$ numbers determine the coefficients of a polynomial with those numbers as its roots (in characteristic $0$).
A non-recursive formula follows from the exponential formula in combinatorics, which shows that the identity
$$\prod_{i=1}^n (1 + tz_i) = \exp \left( p_1 - \frac{p_2 t^2}{2} + \frac{p_3 t^3}{3} \mp ... \right)$$
is equivalent to the identity
$$e_k = \frac{1}{k!} \sum_{\pi \in S_k} \text{sgn}(\pi) p_{\pi}$$
where

$p_k = \sum_{i=1}^n z_i^k$,
$e_k$ is the $k^{th}$ coefficient of $\prod (1 + tz_i)$,
$\text{sgn}(\pi)$ is the sign of the permutation $\pi$, and
$p_{\pi} = p_{\lambda_1} ... p_{\lambda_m}$ where the permutation $\pi$ has cycle type $(\lambda_1, ... \lambda_n)$.

A short proof of the first identity is as follows: let $M$ be a matrix whose eigenvalues are $z_1, ... z_n$. Then the LHS is $\det (I + tM)$ and the RHS is $\exp \text{tr } \log (1 + tM)$. But the identity $\det \exp N = \exp \text{tr } N$ where $N$ is a matrix is straightforward to prove (e.g. by proving it for $N$ diagonalizable and extending by continuity).
Answer: The result is true. Look at http://en.wikipedia.org/wiki/Symmetric_polynomial and http://en.wikipedia.org/wiki/Newton%27s_identities
A symmetric polynomial in $n$ variables $p(x_1,\dots,x_n)$ is one that does not change under any permutation of the variables.
As explained in the first Wikipedia page linked to above, any symmetric polynomial in $x_1,\dots, x_n$ can be expressed as a polynomial expression with rational coefficients in the power sum symmetric polynomials $p_i(x_1, \dots, x_n)$ for $i=1,\dots,n$, where $$p_i(x_1,\dots,x_n)=x_1^i+x_2^i+\dots+x_n^i. $$
The point is then that the coefficients of $$q(x)=(x-z_1)(x-z_2)\dots(x-z_n)$$ are symmetric polynomials of $z_1,\dots,z_n$ and therefore expressible in terms of the $p_i(z_1,\dots,z_n)$. Since these coefficients completely determine $q(x)$, we have the result you are after.

Linear Algebra of Symmetric Sums


Why does the DFT only require N coefficients/exponentials for a signal of length N?

Question: I have been learning about the DFT:
$$ X(k) = \sum\limits^{N-1}_{n=1} x(n) e^{-i(2\pi/N)nk}$$
$$ x(n) = \frac{1}{N}\sum\limits^{N-1}_{k=0} X(k) e^{i(2\pi/N)nk} $$
Which allows for a discrete Signal of length N to be expressed as the sum of N complex sinousoids of frequency 0,1,..,N-1
It makes intuative sense that much fewer sinousoids should be required as the signal is not continous, and therefor does not have to deal with issues due to continuity in any order and only has to be equal to the function at discrete points.
I however saw no justification of why exactly N sinousoids are required.
Why does a N length DFT only require N sinousoids?
Answer: One of the reasons this makes sense is because the DFT is a linear map that is (or should be!) invertible,
the map has to be a linear operator $A:\mathbb C^N\to\mathbb C^M$ where $N=M$.
The dimension $N$ of the first vector spaces is given by the number of sample points,
the dimension $M$ of the second vector space is given by the number of basis function, ie. sinuoids.
With the argument above, they have to be equal.


Is Mathway wrong about the domain of $\sqrt{x-13}\sqrt{x-13}$?

Question: Say $f(x) = \sqrt{x-13}$. You're trying to find the domain of $(ff)(x)$ where $$(ff)(x) = \sqrt{x-13}\sqrt{x-13}.$$
However, $\sqrt{x-13}\sqrt{x-13} = x-13 $, right?
The domain of $x-13$ in interval notation: $ (-\infty, +\infty) $
The domain of $\sqrt{x-13}$ in interval notation: $[13, +\infty) $
The domain of $\sqrt{x-13}\sqrt{x-13}$ in interval notation:

The expression should first simplify to $x-13 $,  and we already found
  out that   "the domain of $x-13$ in interval notation: $(-\infty,+\infty)$"

So, then, why does Mathway say that the domain of $\sqrt{x-13}\sqrt{x-13}$ is $[13, +\infty)$?
Comment: Use LaTeX, please.
Comment: Well, it explains quite clearly what's going on. First, $\sqrt{x-13} \sqrt{x-13}$ is simplified to $x-13$, for which the domain clearly is all real numbers. (Note that this simplification is only possible if $x \geq 13$.) But this is different from the domain of $\sqrt{x-13}$.
Comment: Thank you Matti, I made those observations as well. Thank you Michael, I love parentheses.
Comment: Also to clarify, I am mostly just making the observation that sqrt(x-13)*sqrt(x-13) does have a different domain than sqrt(x-13) because sqrt(x-13)*sqrt(x-13) = x - 13 which has a domain of all real numbers. Mathway informed me that the domain of sqrt(x-13)*sqrt(x-13) is [13,+∞) (in interval notation). I'm curious whether Mathway is incorrect or if I am overlooking something.
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: My guess is that the function $\sqrt{x}:\mathbb{R}_+\to\mathbb{R}$ is defined only for $x\geq 0$. Thus, $x<13$,  the function $\sqrt{x-13}$  is undefined. Therefore, $\sqrt{x-13}\sqrt{x-13}$ is undefined. Hence, $\sqrt{x-13}\sqrt{x-13}=x-13$ only if $x\geq 13$.
It is just a matter of definition. In general, $\sqrt{\cdot}:\mathbb{R}_+\to\mathbb{R}_+$ and $(\cdot)^{1/2}:\mathbb{C}\to\mathbb{C}$. So,$ (x−13)^{1/2}(x−13)^{1/2}=x−13$ always.
Comment: i appreciate the feedback! isn't sqrt(x-13)*sqrt(x-13) = x - 13 always? yes, the function sqrt(x-13) is undefined when x < 13, as the square root of a negative number is not real. but sqrt(x-13)*sqrt(x-13) is the same as saying ((sqrt(x-13))^2 right? which is just x -13? and "the domain of x-13 in interval notation: (-infinity, +infinity)" right?
Comment: It is just a matter of definition. In general, $\sqrt{x}:\mathbb{R}_+\to\mathbb{R}_+$ and $(x)^{1/2}:\mathbb{C}\to\mathbb{C}$. So, $(x-13)^{1/2}(x-13)^{1/2}=x-13$ always.
Comment: that makes sense, so then shouldn't ((−13)^(1/2))*((−13)^(1/2) = −13  always have a domain of all real numbers?
Comment: I would say, yes!
Answer: I know nothing about Mathway but I don't think that it is necessary.  It is being a little pedantic but that is necessary in maths.  If you are not careful in this way then you can "prove" all sorts of nonsense such as $1 = 0$.  Incorrect handling of square roots is common in fake proofs.
I am assuming that you are dealing with the real numbers $\mathbb{R}$.  The complex numbers $\mathbb{C}$ add different complications.  Square roots need careful handling there as well.
$$\sqrt{x - 13}\sqrt{x - 13} = x - 13$$
This is true whenever the left hand side is defined so when $x \ge 13$.  It is not true when $x < 13$ as the left hand side is not defined.
When expressions like this arise in real problems, you need to note these assumptions because they might not be apparent in the final result.  You need to treat these cases separately.  Maybe the final result is true for them as well but it requires a different proof.  Maybe it isn't even though the final result does not appear to have the restriction.
Answer: If I understand the problem correctly, $(ff)(x)$ means $f(x)\cdot f(x)$ in which case I think Mathway is correct. In effect you are multiplying the 'output' of a function by the 'output' of another function. You are not multiplying two expressions to make a third expression.So, if one of the two functions has an undefined output for a given value of $x$, then the result of the multiplication must be undefined. Obviously in this case, both will have the same output for whatever value of $x$, and that will only be a defined output for $x\ge 13$.


How to make correlation coefficient account for linear transformation?

Question: The Pearson correlation coefficient is scale-invariant.  Therefore the correlation $cor(x,y)$ remains the same if $x$ or $y$ is linearly transformed (i.e., $x - 1$ or $2x$).
I am interested in a correlation coefficient that is sensitive to linear transformation.  If $cor(x,y) = 1.00$, I want $cor(x-1, y) < 1$.  In other words, I want a strict correlation coefficient that requires $x = y$ in order for $r = 1.00$.
One idea I had was to modify the covariance term $\Sigma (x - \bar x)(y - \bar y)$ to shrink when the means of $x$ and $y$ diverge, but I am uneasy about creating a monster statistic with intractable properties.  In principle, I am looking for something like $\Sigma (x - \bar x)(y - \bar y) - (|\bar x - \bar y |)$.
Is there an existing method to achieve this type of "strict" correlation coefficient?
Comment: How about a distance measure?
Comment: See identity coefficient and similarity ratio mentioned in https://stats.stackexchange.com/a/22520/3277. There are other alternatives to r as well.
Comment: https://en.wikipedia.org/wiki/Distance_correlation
Answer: There are (at least) two correlation-type measures that measure the absolute agreement between two measurements (i.e., they will only be equal to 1 when $x = y$). The first is the intraclass correlation coefficient and the other is the concordance correlation coefficient. They often give very similar results. For example:
<code>x <- c(2,4,3,6,8)
y <- 1 + x
n <- length(x)

s2x <- sum((x - mean(x))^2) / n
s2y <- sum((x - mean(x))^2) / n
sxy <- sum((x - mean(x)) * (y - mean(y))) / n

cor(c(x,y),c(y,x)) # ICC
[1] 0.8977505

2*sxy / (s2x + s2y + (mean(x) - mean(y))^2) # concordance correlation
[1] 0.9027237
</code>
Comment: The one that is estimated by `cor(c(x,y),c(y,x))` is the ICC(1,1). This estimator goes back to Fisher. You can also use the ANOVA approach to estimate it. The two approaches often give very similar estimates. If you want to estimate the ICC(2,1), then use the ANOVA approach.
Comment: You may have access to https://www.sciencedirect.com/science/article/pii/S0169555X05003740 which surveyed not just concordance correlation but the general problem of assessing agreement.
Comment: @Wolfgang Thank you for your helpful answer.  ICC fits the bill.  I like your clever implementation using cor().  Where can I read more about this implementation?  It is slightly different from other implementations of ICC.
Comment: @NickCox Thanks.  I found this article to be the most helpful: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4913118/
Comment: @Wolfgang If I may add a follow-up question: What type of ICC does your answer implement?  Based on the readings I am looking for ICC with two-way random effects, absolute agreement, and single rater, aka ICC(2,1).
Comment: @Wolfgang Thanks.  This is very helpful. All the best.


how to make navigation with 3-axis accelerometer and 3-axis gyroscope and gps

Question: as the title stated, I want to make Dead Reckoning with accelerometer and gyroscope. The accelerometer could apply with linear accleration and then used to get velocity by one time integration or get runing distance in the gap of sample time by twice integration. and also I could get changed angle by integration of gyroscope output value. so on the condition of initial position, I can get new postion by DR with distance and angle.
thought is perfect but fact is not so simple. acceleromter and gyroscope is unstable and always affected by temperature or unaligned axis direction. I have know there is one popular method called kalman filter to combined this sensors with gps to protect navigation from noise of output, but I think it's out of my comptent by now.
firstly, I want to know how to remove gravity force which is mixed with real accelerometer ouput?
sencond, how to correct gyroscope error?
the last, how to realize kalman filter with accelerometer, gyroscope and gps?
any suggestion is good to me, if you can give some code that's best of all!
thank you
[edit @2013/12/12]:
I have given up using accelemeter for calculating velocity and distance due to it's big drift. And also the error can become more and more under the influence of double integration. But there is a lucky thing that this work for a car in tis case. so I prefer to select receiving velocity from CAN, it was proven to be more exactly than accelerometer. By now a solution about velocity has been resolved, but the other question is still not sure in my opinion. expect more nice answer.
Answer: look here https://stackoverflow.com/a/19764828/2521214
And read the whole thing !!!

including the comments
and view also this http://www.youtube.com/watch?v=C7JQ7Rpwn2k ...
video link is from AlexWien answer in the same thread


How much of a discrepency is tolerable if Sample Ratio Mismatch is detected?

Question: We have analyzed several past online A/B tests and revealed that some of them have SRM at a statistically significant level (p<0.001).
Example: we had 50%/50% traffic allocation between control and test variations.
However, we ended up with the number of users below:
Control: 130631
Test: 133192

Some of the past tests had a discrepancy of 2% in the number of users between control and variation. Some had 5% or 10%.
Is there a percentage of discrepancy that can tolerate if a Sample Ratio Mismatch is detected?
Like less than 2% is tolerable, and we can still trust the results of our A/B tests. If more than 2% we can't do that.
Answer: The percentage of discrepancy doesn't tell you much on its own. For example:

prop.test(c(25, 20), c(50, 50)) has a 10 percentage-point discrepancy (50% vs 40%) but the p-value is clearly non-significant ($p=0.42$)
prop.test(c(2500, 2400), c(5000, 5000)) has a 2 percentage-point discrepancy (50% vs 48%) but the p-value is significant at the 5% level ($p=0.048$).

Therefore, what matters is the combination of the discrepancy and the sample size.
If the p-value of a SRM test is very small (e.g. $p<0.001$), that tells you that it would be extremely unlikely to get a discrepancy like the one you got (or larger) if your experimentation system was working properly. I would certainly be worried with such a small p-value.
On another note, if you are running many SRM tests on past A/B tests, you probably want to adjust for multiple comparisons. Otherwise, even if all your tests were correctly set up, you would still expect to get a $p<0.05$ approximately 5% of the time (false positive).


How do I make an package of an standalone app in VS.NET?

Question: So here is the situation.  I want to bundle Google Chrome Portable by itself.  The only modification I would make is to change the default homepage, and add a shortcut link to the desktop.  I also can't use the included Google Chrome installer because I would need to change the default homepage.
What should I use to make a simple installer that just unzip the Google Chrome folder into programs and create the shortcut on desktop?  I don't need anything fancy like program registration or anything like that, in fact, most of my clients probably will not have installation rights on there computer.
Now my project is in Visual Studio 2008, but I am willing to use any other type of packager.
Answer: You can also try the free version of Advanced Installer, i.e. by creating a "Simple" project. There is also a five-minutes tutorial on how to create the package
Answer: I went with the WinRar SFX Archive File, with auto-run after it finishes.


How does wordpress permalink system works?

Question: Wordpress uses this code in .htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

First question, what does the line of code below mean:
RewriteRule ^index\.php$ - [L]

Next thing is I don't know how index.php handles this. So all URLs are redirected to index.php...
If I type this URL:
website.pl/One-two-Five

.htaccess will redirect me to index.php:
webiste.pl/index.php

But there is no information, I mean QUERY_STRING or something. It's not something like:
website.pl/index.php?data=One-two-Five

but instead it is just:
website.pl/index.php

And this is just index.php... So how is index.php making this possible? How does WordPress handle this? I can't find any answers. What are the mechanics of WordPress for this?
Answer: Good question, and one I discussed recently in another question.
As you say, everything (that doesn't exist as a file or directory) is rewritten to index.php by:
RewriteRule . /index.php [L]

Regarding the line of code:
RewriteRule ^index\.php$ - [L]

That just prevents any more processing if the URL is already index.php. The - just says don't change anything and the [L] says stop processing this iteration. This is because .htaccess rewrite rules will restart processing until there is no change to the URL (so what it does is prevent a file system check on the second run through).
What happens after that is that WordPress examines the $_SERVER['REQUEST_URI'] variable to see what page was originally requested, and acts on that. That is why it does not need to pass anything through to index.php directly in the .htaccess file, since the originally requested URL is already available in the $_SERVER['REQUEST_URI'] variable.
One other point is that these are not redirects, they are rewrites. A redirect is external, going back to the browser. A rewrite is internal only, and does not change the URL for the browser.


Smallest positive integer that is divisble by 2, 3 and 5 and that is also a perfect square and perfect cube

Question: My son is having this problem:

Smallest positive integer that is divisible by $2$, $3$ and $5$, and that is also a perfect square and perfect cube.

He was busy using Excel, but I thought: Isn't there a faster way?
Comment: $$(2\cdot3\cdot5)^{6m}$$
Comment: @labbhattacharjee:  Since he said "smallest", my answer would be $(2\cdot 3\cdot 5)^6$,
Answer: Since number has to be divisible by $2,3,5$ therefore it should be divisible by $30$.
Since you want a perfect square and a perfect cube therefore your number should be of the form $30^{6t}$ . Where t is the integral number satisfying all such conditions.
In your case $t=1$ , therefore answer is $30^6$.
Comment: It took me a long time to edit , I could have posted it before lab bhattacharjee.
Comment: Thanks for upvote , next time I will try my best not to delay.
Answer: If $n$ is an integer, then

$n^2$ is a perfect square
$n^3$ is a perfect cube

An integer that has both these properties is $n^{2\cdot 3}=n^{6}$, since $$n^{6}=\underset{\color{red}{\text{square}}}{\underbrace{(n^{3})^\color{red}{2}}}=\underset{\color{green}{\text{cube}}}{\underbrace{(n^{2})^\color{green}{3}}}$$ You also want this to be divisible by $2,3,5$, these are prime numbers so the smallest non-zero such number is $$(2\cdot 3\cdot 5)^6=30^6=729 000 000$$


Chrome, css filter blur and scale at children and overflow hidden on parent results glowing edges

Question: Parent div has overflow:hidden, and the child element is scaled and blured on :hover, with transition. While animated you can see glowing edges ( I use transform:scale() strictly to avoid this, but it gets worse). I am using Chrome 39.0.2171.99 m.
JSFiddle

        Hover

.overflow{
    width: 200px;
    height: 200px;
    overflow: hidden;

}
.inner{
    width: 100%;
    height: 100%;
    background: green;
    transform: scale(1);
    filter: blur(0px);
    transition: all 0.5s ease-in-out;
}
.overflow:hover .inner{
    transform: scale(1.1);
    filter: blur(10px);
    -webkit-filter: blur(10px);
}

Comment: I don't have a solution, but we should rather find a way to force the WHOLE .inner element to be blurred.

Right now it seems like the browser only blurs the visible part of the element, i.e. after it was clipped by the parent.

The flickering seems to be the transition between the animating frames using a fast interpolation and the last frame using a better rendering.

http://jsfiddle.net/5wz9w8o0/
Comment: You only encounter this kind of bug once a year!
Answer: it chrome BUG with scale and overflow .
for the container that have the ( overflow:hidden )
add
position:relative;
z-index:1;

Comment: Can you refer/link to the chrome bug that you're mentioning that is actually related directly to this?
Answer: The glowing edges is due to the green background being blurred -- creates a sort of faded edge effect. you can solve this by moving your background: green style to the .overflow DIV. Also the scale transforms seem unnecessary now.
JSFIDDLE
.overflow{
    width: 200px;
    height: 200px;
    overflow: hidden;
    background: green;
}
.inner{
    width: 100%;
    height: 100%;
    transition: all 0.5s ease-in-out;
}
.inner:hover{
    filter: blur(10px);
    -webkit-filter: blur(10px);
}

EDIT:
If your content is HTML (not solid color background) that adds a bit of complexity. I kept running into an issue where the blur was applied to the visible area during the transition then the blur applied to the whole image once the transition ended... strange behavior but as far as I can tell unavoidable. I was able to achieve the desired effect by stacking two objects and using background images setting up two objects with the .back object already having the blur effect applied. Any text or other elements can be placed directly within the .front DIV but full size images need to be applied using CSS background-image: url() and must be 20 pixels larger than the container to account of the faded 10px blur effect on the edges. Hope this helps you out.
New JSFiddle example using image

Hover

.overflow {
    width: 200px;
    height: 200px;
    overflow: hidden;
    position: relative;
}
.front,
.back {
    box-sizing: border-box;
    position: absolute;
    top: -10px;
    left: -10px;
    width: 220px;
    height: 220px;
    padding: 10px;
    background-image: url(http://cache.graphicslib.viator.com/graphicslib/2982/SITours/tampa-bay-downtown-and-manatee-river-helicopter-tour-in-tampa-109952.jpg);
    background-size: 220px 220px;
    background-position: center center;
}
.front {
    z-index: 100;
    transition: all 0.5s ease-in-out;
}
.back {
    z-index: 50;
    filter: blur(10px);
    -webkit-filter: blur(10px);
}
.front:hover {
    filter: blur(10px);
    -webkit-filter: blur(10px);
}

Alternate New JSfiddle example using HTML elements
Comment: But this isn't a solution if the .inner div is html content or image, wich is in my case. This is just simplified version of the issue. Works fine on Firefox.
Comment: @MilosR - I addressed your issue and appear to have found a solution... take a look at the edited answer above.
Comment: That's the problem, as far as i know only in Chrome, when transition ends it look's like it recreate blur effect, but only if parent has overflow:hidden, thanks for this solution, i will try this.
Comment: appending rules transform: translateZ(0); or -webkit-backface-visibility: hidden;  to .inner fixes the problem while transition acts, but glowing edge now remains at the enf of transition... Looks [this](https://code.google.com/p/chromium/issues/detail?id=343568) issue is connected to our problem.


Redirect user to login page when they have to access to a view?

Question: I have a view which is only accessible to authenticated users. However, there are links to it on the site. Can I make it so that an unauthenticated user gets redirected to the login page, instead of the 403 they're seeing now?
Answer: The Redirect 403 to User Login module should do what you need.
Answer: I would use Rules, it is very configurable and should allow you to do what you require.
Answer: With LoginToboggan, the login form can be added to Access Denied (403) pages. No redirects needed.


Let $A=(-1,0),B=(1,0), C$ be points in $\mathbb{R}^2.$ What is the locus of points $\{s\in\mathbb{R}^2:C$ lies on the angle bisector of $AsB$}?

Question: Let $A=(-1,0),\ B=(1,0),\ C$ be points in $\mathbb{R}^2.$ What (shape(s)) is the locus of points $L(C)=\{s\in\mathbb{R}^2:C$ lies on the angle bisector of $AsB$ } ?
Obviously the set $L$ depends on where $C$ is, which is why I've written $L$ as a function of $C.$
If $C$ is the midpoint of $AB$, or on the perpendicular bisector of $AB$, it is not clear to me that $L= \{$ the perpendicular bisector of $AB\},$ because maybe $L$ contains more points. [Edit: Karan Elangovan has answered this part of the question.]
Comment: If $C$ lies on the line $AB$, say at $(c,0)$, then the locus is the circle on diameter $CC'$, where $C'=(1/c,0)$. This is an instance of the Apollonius circles.
Comment: If you want someone to get the full bounty, you should award it, or accept an answer. If you do nothing, only half will go to brainjam's answer.
Comment: Thanks for reminding me- I was planning on awarding it this morning, but got side-tracked.
Comment: I just didn't want half of the bounty to go to waste. Thanks!
Answer: The locus you are asking about is a subset of a cubic curve called an Apollonian strophoid (or strophoid of Apollonius).
The curve is the set of points $S$ for which either the internal or bisector of the angle $\angle ASB$ passes through $C$.  (The external bisector is the line through $S$ perpendicular to the internal bisector.)  As the strophoid $\Sigma$ comes in from infinity, $C$ is on the internal bisector but, as $\Sigma$ goes past $A$, $C$ is on the external bisector until $\Sigma$ passes $B$ after which $C$ is back on the internal bisector all the way to infinity.  So your locus is actually the strophoid minus the section between $A$ and $B$.
A GeoGebra applet that demonstrates the strophoid can be found here.  The strophoid is blue, the external bisector is green. You can move $S$ and $C$.  (Unfortunately the $S$ will jump around if you modify any of the points.  This is annoying but harmless.)  The strophoid is built using mathlove's equation.

There are two special cases where the cubic degenerates to a line $\ell$ and a circle $c$.   Both have been touched upon in other answers and comments for this question.

when $C$ is on the perpendicular bisector of $A$ and $B$, line $\ell$ is the perpendicular bisector and $c$ is the circumcircle of $A,B,C$.  For points $S$ on $c$ it is the external bisector that goes through $C$.  (Because, if $M$ is the midpoint of $A,B$ then the triangle $\triangle ECS$ is a right angle.

when $C$ is on the line $AB$, line $\ell$ is the line $AB$ and $c$ is an Apollonian circle of the segment $AB$.

For more about strophoids see the following references.
Gibert, Apollonian strophoids (part of a large catalog of so-called Triangle cubics)
mathcurve.com (Strophoid page)
Stachel, Strophoids, A Family Of Cubic Curves With Remarkable Properties (see Theorem 4).
Answer: Let $C(a,b),s(x,y)$ where $y\not=0$.
Also, let $U(u,0)$ be the intersection point of the angle bisector with $x$-axis.
Then, we have
$$\begin{align}&sA:sB=AU:BU
\\\\&\iff (1-u)\sqrt{(x+1)^2+y^2}=(1+u)\sqrt{(x-1)^2+y^2}
\\\\&\iff u=\frac{\sqrt{(x+1)^2+y^2}-\sqrt{(x-1)^2+y^2}}{\sqrt{(x+1)^2+y^2}+\sqrt{(x-1)^2+y^2}}\end{align}$$
So, $C$ is on the angle bisector ($sU$) if and only if
$$\begin{align}&b(x-u)=y(a-u)
\\\\&\iff (y-b)u=ay-bx
\\\\&\iff (y-b)\frac{\sqrt{(x+1)^2+y^2}-\sqrt{(x-1)^2+y^2}}{\sqrt{(x+1)^2+y^2}+\sqrt{(x-1)^2+y^2}}=ay-bx
\\\\&\iff (y-b)\bigg(\sqrt{(x+1)^2+y^2}-\sqrt{(x-1)^2+y^2}\bigg)
\\&\qquad\qquad=(ay-bx)\bigg(\sqrt{(x+1)^2+y^2}+\sqrt{(x-1)^2+y^2}\bigg)
\\\\&\iff (y-b-ay+bx)\sqrt{(x+1)^2+y^2}=(y-b+ay-bx)\sqrt{(x-1)^2+y^2}\end{align}$$
So, we have to have
$$(y-b-ay+bx)(y-b+ay-bx)\ge 0$$
under which we have
$$(y-b-ay+bx)^2\bigg((x+1)^2+y^2\bigg)=(y-b+ay-bx)^2\bigg((x-1)^2+y^2\bigg)$$
i.e.
$$\color{red}{bx^3-  a b x^2-  b x+(a^2 -b^2 +  1) x y -  a x^2 y +  b x y^2  -  a y^3+  a b y^2   -  a y     +  a b =0}$$

Examples :

If $a=b=0$, then we get a line $x=0$.

If $b=0$ with $a\not=0$, then we get a circle$$  \bigg(x-\frac{a^2+1}{2a}\bigg)^2 +  y^2   =\bigg(\frac{1-a^2}{2a}\bigg)^2$$under the condition that $-1\lt a\lt 1$ as jlammy commented.

If $a=0$ with $b\not=0$, then we get a line $x=0$ or a circle $$x^2  +\bigg(y-\frac{b^2-1}{2b}\bigg)^2  =\bigg(\frac{b^2+1}{2b}\bigg)^2$$under the condition that $(y+bx-b)(y-bx-b)\ge 0$.
Answer: Geometric Construction for $\boldsymbol{C}$ off the Axes
Here is a geometric construction for the points of the locus.
We are given the points $A=(-1,0)$, $B=(1,0)$, and $C$. For any $\lambda\in\mathbb{R}$, define
$$
\begin{align}
P&=\frac{A+C}2+\lambda\rho(C-A)\tag{1a}\\
Q&=\frac{B+C}2+\lambda\rho(B-C)\tag{1b}
\end{align}
$$
where $\rho(v)=v\begin{bmatrix}0&1\\-1&0\end{bmatrix}$ is $v$ rotated by $\frac\pi2$ counter-clockwise.
Then define two circles: one centered at $P$ passing through $A$ and $C$, and another centered at $Q$ passing through $B$ and $C$. Note that we are simply constructing two similar isosceles triangles: $\triangle APC$ and $\triangle BQC$.
By construction, both circles pass through $C$. Let the other point of  intersection of these circles be $D$.

By construction, $\angle APC=2\tan^{-1}\left(\frac1{2\lambda}\right)=\angle BQC$. Thus, by the Inscribed Angle Theorem,
$$
\angle ADC=\tan^{-1}\left(\frac1{2\lambda}\right)=\angle BDC\tag2
$$
The construction above works because $A$ is outside the circle containing $B$ and $B$ is outside the circle containing $A$. This construction also works when $A$ is inside the circle containing $B$ and $B$ is inside the circle containing $A$

Again, $\angle APC=2\tan^{-1}\left(\frac1{2\lambda}\right)=\angle BQC$. Thus, by the Inscribed Angle Theorem,
$$
\angle ADC=\tan^{-1}\left(\frac1{2\lambda}\right)=\angle BDC\tag3
$$
However, when only one of $A$ or $B$ is inside the circle containing the other, we have the following situation

Note that by the Inscribed Angle Theorem, $\angle BDC=\frac12\angle BQC$; however, $\angle ADC=\pi-\frac12\angle APC$.
$\angle ADC$ becomes supplementary to half its associated central angle, $\angle APC$, when $D$ passes through $A$; that is when $A$ changes whether it is inside or outside of the circle containing $B$. This happens when
$$
\lambda=\lambda_A\equiv\frac{(A-C)\cdot(B-A)}{2\rho(A-C)\cdot(B-C)}\tag4
$$
$\angle BDC$ becomes supplementary to half its associated central angle, $\angle BQC$, when $D$ passes through $B$; that is when $B$ changes whether it is inside or outside of the circle containing $A$. This happens when
$$
\lambda=\lambda_B\equiv\frac{(C-B)\cdot(B-A)}{2\rho(A-C)\cdot(B-C)}\tag5
$$
Which angle, $\angle ADC$ or $\angle BDC$, is supplementary to half its associated central angle switches when $D$ passes through $C$; that is, when the circles are internally tangent. This does not happen when the circles are externally tangent since then neither $A$ nor $B$ is inside the circle containing the other.
If we set
$$
\begin{align}
\mu&=\frac{(A-C)\cdot(B-C)}{\rho(A-C)\cdot(B-C)}\tag{6a}\\[3pt]
\sigma&=\operatorname{sign}(\rho(A-C)\cdot(B-C))\tag{6b}
\end{align}
$$
then the circles are internally tangent when
$$
\lambda=\frac{\mu-\sigma\sqrt{\mu^2+1}}2\tag7
$$
and externally tangent when
$$
\lambda=\frac{\mu+\sigma\sqrt{\mu^2+1}}2\tag8
$$
Here is an animation of $D$ (red point) traversing the locus of points (blue curve) where $C$ lies on the bisector of $\angle ADC$. The red curve is where one or the other inscribed angles is supplementary to half of its associated central angle.

Locus for $\boldsymbol{C}$ on the Axes
If $C$ is on the $y$-axis, then the locus is all of the $y$-axis except $C$.
If $C$ is on the $x$-axis, then the locus is all of the $x$-axis with the segment from $(-1,0)$ to $(1,0)$ and $C$ removed.
If $C=(0,0)$ then the locus is the union of the $x$-axis and $y$-axis with the segment of the $x$-axis from $(-1,0)$ to $(1,0)$ removed.
Comment: Amazing diagrams and animation.
Comment: @robjohn Which application has been used for drawing and animation?
Comment: I used Mathematica 11.3 for all of the drawings and animation in this answer.
Answer: Let $M$ be the midpoint of $AB$.
$C$ lies on the perpendicular bisector of $AB$, hence $AC = BC$
$\angle AsC = \angle BsC$
$sC$ is common.
Hence either the angles $\angle sCA$ and $\angle sCB$ are equal or supplementary. If they're supplementary, then $ACB$ is a straight line, meaning $C$ is the midpoint of $AB$. We will consider this case at the end. Otherwise though, we have $\angle ACs = \angle BCs$, and so $\triangle ACs \equiv \triangle BCs$, so $As = Bs$, so $s$ must lie on the perpendicular bisector of $AB$, so $L$ = the perpendicular bisector of $AB$, as required.
Finally consider the case that $C$ is the midpoint of $BC$, and the angles are supplementary.
$$ \frac{\sin\angle sBC}{sC} = \frac{\sin\angle BsC}{BC} \text{(Sine law)}$$
$$ = \frac{\sin\angle AsC}{AC} \text{(AC = BC})$$
$$ = \frac{\sin\angle sAC}{sC} \text{(Sine Law)}$$
So we have $\sin\angle sBC = \sin\angle sAC$, so the two angles are either equal or supplementary. Since they are angles of a triangle, they cannot be supplementary, so they are equal, so $\triangle sAB$ is isoceles with base $AB$, so $As = sB$, so again we have that $s$ lies on the perpendicular bisector, as required.
So yes, the only points in $L$ are those on the perpendicular bisector of $AB$.
Comment: Am I correct in thinking that this covers only the cases where $C$ lies on the perpendicular bisector of $AB$?
Comment: Yes, this only covers that case. Though isn't your question only about that case?
Comment: Nowhere in my question do I restrict $C$ to be on the perpendicular bisector of $AB.$ $C$ Could be anywhere in $\mathbb{R}^2.$
Comment: Sorry, I thought you were only thinking about perpendicular bisector since in the last paragraph you said it wasn't clear to you why L would be the perpendicular bisector in that case.
Comment: Like I say, you've answered *that part* of the question. But the main question is the title.


How can I reference an enum of another class in ObjectDataProvider?

Question: I want to bind an enum to the ComboBox.
Here is the class BarcodeModel.cs which contains the enum:

And here is the enum in the class:
public enum BarcodeType
        { AZTEC, CODABAR, CODE128, CODE93, CODE39, DATA_MATRIX, EAN13, EAN8, ITF, MAXICODE, PDF417, QRCODE, RSS14, RSSEXPANDED, UPCA, UPCE, UPC_EAN_EXTENSION }

Well, in another directory of the same project I use an ObjectDataProvider to bind it:
<Page x:Class="KongGamLung.ToolProperty.BarCodeProperty"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:KongGamLung.ToolProperty"
      xmlns:System="clr-namespace:System;assembly=mscorlib"
      xmlns:Model="clr-namespace:KongGamLung.Models"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="800"
      Title="BarCodeProperty">
    <Page.Resources>
        <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="Model:BarcodeModel.BarcodeType"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Page.Resources>
<ComboBox x:Name="BarcodeTypeCB" ItemsSource="{Binding Source={StaticResource dataFromEnum}}"></ComboBox>
</Page>

After it ran, Visual Studio threw a XamlParseException error which can not find "{clr-namespace:KongGamLung.Models;assembly=KongGamLung, Version=126.96.36.199, Culture=neutral, PublicKeyToken=null}BarcodeModel.BarcodeType"
How can I reference the enum correctly? Would you please help me? Thank you.
Answer: If you want to reference a nested type in xaml, instead of '.', use '+'.
<x:Type TypeName="Model:BarcodeModel+BarcodeType"/>

Comment: Thank you. It works! Whereas, I feel strange c# use + but not . in this place. Aha.
Comment: @102425074 Actually, the offical type name of a nested type is using '+'. You can check `Type.FullName` of a nested type.


Dividing Two Random Variables

Question: I am having trouble with a problem that I am working on for a course.  I am not looking for an answer to the question (I have the answer), but I am rather looking for understanding of the concept.  Let me pose the question.  The parts I have questions about I will mark to the right with a bold Q and a number, i.e. Q1, Q2, etc.
"The random variables $X$ and $Y$ are independent and uniform on the interval $(0,a)$.  Find the p.d.f. of $\frac{X}{Y}$"
Worked solution for this problem looks like so:
$Z=\frac{X}{Y}$
$F_Z(z)=P\left \{ \frac{X}{Y} \leq z \right \}$
$F_Z(z)=P\left \{ X \leq zY \right \}$ Q1
Case 1: $z < 1$ Q2
$F_Z(z)=\int_{0}^{a}\int_{0}^{zy}f_x(x)f_y(y)dxdy$ Q3 Q4
$F_Z(z)=\int_{0}^{a}\int_{0}^{zy}(\frac{1}{a})(\frac{1}{a})dxdy$
$F_Z(z)=\frac{z}{2}$ for all $z\leq1$ Q5
Case 2: $z \geq 1$
$F_Z(z)=P\left \{ X \leq zY \right \}$
$F_Z(z)=1-\int_{0}^{a}\int_{0}^{x/z}f_x(x)f_y(y)dxdy$ Q6 Q7
$F_Z(z)=1-\int_{0}^{a}\int_{0}^{x/z}(\frac{1}{a})(\frac{1}{a})dxdy$
$F_Z(z)=1-\int_{0}^{a}(\frac{x}{z})dx$
$F_Z(z)=1-\frac{1}{2z}$ for all $z>1$ Q8
From there, I understand differentiate to find the p.d.f. of each case, which makes sense.
I understand that the p.d.f. of a uniform distribution is $\frac{1}{b-a}$ for the interval $(a,b)$, which in this case makes the p.d.f. for both $X$ and $Y$ equal to $\frac{1}{a}$.
Here are my numerous questions about this process:
Q1 - Why is moving the random variable $Y$ to the $z$ side of the inequality necessary?
Q2 - How are the cases selected?
Q3 - Where do these limits of integration come from?
Q4 - Why are the two functions $f_x(x)$ and $f_y(y)$ now multiplied, when they were divided in the initial question?
Q5 - Why does the case selected show $z<1$ but the final CDF solved for gives $z \leq 1$?
Q6 - Where do these limits of integration come from?  Why are they so different from Case 1?
Q7 - Why is this equations now $1-\int$ whereas Case 1 was just the $\int$
Q8 - Much like Q5 how did these inequalities change?
I know this is quite a bit, but I am very lost on this concept.  I seem to be lacking an overall understanding of random variables that is causing a significant amount of confusion in a problem like this.
Thank you for any help you can provide with this!
If this is a bit much, please let me know how I can best post these kinds of questions in the future.
Comment: Likely many users will vote to close this as consisting of two many questions.  It's possible, though, to provide a single answer to them all: **draw a picture.**  A good diagram of the square $[0,a]\times [0,a]$ and the event $X/Y\lt z$ will immediately suggest answers to all your questions.
Comment: @pflykyle Follow whuber's instructions literally. **Draw** the picture _on a piece of paper_ instead of just envisioning it in your mind.
Comment: Whuber, thank you for your suggestion and feedback.  I can envision the square, but not the event.  Could you expand on that a bit for me?
Comment: The event is depicted by the set of points $(x,y)$ for which $x/y\lt z.$ Its boundary must consist of portions of the boundary of the square $[0,a]\times[0,a]$ and possibly part of the curve $x/y=z,$ which is more simply expressed by the equation $x=yz.$ You should recognize that as the equation of a line through the origin. Thus this event will be represented by an empty set, a line segment, a triangle, a trapezoid, or the entire square (minus $(0,0)$). Its probability will equal the area of that point set, suggesting you should use elementary geometric formulas instead of integrals.
Answer: A picture of an event usually helps in finding its probability.

Each panel graphs the relation $x/y \le z$ for typical values of the number $z \gt 0.$ (When $z\lt 0,$ no points in the unit square satisfy this inequality, so the relation is empty.)  I have chosen units of measurement in which the constant $a$ is one unit.  This does not affect the ratio $X/Y,$ so we needn't adjust $z$ at all.
Before we proceed, notice that since $X$ and $Y$ are uniform and independent, the probability of any event is just its area relative to that of the entire square.  Thus, elementary Euclidean geometry affords immediate answers which we may use to check the integrations:

The probability of the left event is the area of the triangle.  This triangle has height $1$ and base $z,$ whence its area is $(z)(1)/2 = z/2.$

The probability of the right event is the area of the trapezoid.  It has bases $1$ and $1-1/z$ and height (looking sideways) of $1,$ whence its area is $(1\,+\,1-1/z)(1)/2 = 1-1/(2z).$

Here is how the picture immediately answers all your questions:

It isn't necessary to re-express the event $X/Y \le z$ as $X \le zY,$ but doing so makes it clear that this event is bounded by the line $x = zy$ (shown by the dotted lines in the figure).  It passes through the origin with slope $1/z.$

At the left where $z\lt 1$ the event is a triangle whereas at the right where $z \ge 1$ it is a trapezoid.  Their probabilities are calculated slightly differently.

The limits of integration describe the triangle in the left panel.

The functions $f_x$ and $f_y$ are probability density functions.  They multiply because you assume the random variables $X$ and $Y$ are independent.  The density of $X/Y$ is not usually given by $f_x/f_y.$  (Indeed, the ratio of densities is unitless whereas a density must have units of probability per (unit $x$ times unit $y$).)

The given solution is sloppy about inequalities, but it doesn't matter because the case $z=1$ is illustrated by either panel.

The limits of integration describe the (gray) triangle in the right panel that is complementary to the trapezoid.

One could integrate directly over the trapezoid at the right, but it is simpler to integrate over its complement because that's equivalent to the computation already performed for the triangle at the left.

There is no evident change in any of the inequalities.
Comment: Whuber, this is a great answer.  Thank you very much.  I had tried to actually draw the square as Dilip suggested, but then I ended up just staring at a square.  I really did not want to ask for more clarification, but you provided it anyway.  Thank you so much for taking the time to really draw it out.  It is truly appreciated.

Dividing Two Random Variables


How do I set up a reverse proxy on the same physical server as a hosted website using apache?

Question: How can I use one server to do the following two tasks:

Serve a website hosted at http://foo.bar.com
Direct all traffic intended for http://loremipsum.bar.com to "http ://www. acme.com:87 60/Application" using a reverse proxy.

The website is already present and configured properly, I just need to add the functionality of #2. How can I do this on the same physical server? I imagine the answer is to use Virtualhosts, but I don't know how to do both on one physical box.
Answer: You just need to create a new VirutalHost section for loremipsum.bar.com.
It would look something like:
<VirtualHost *:80>
  ProxyPass / http://www.acme.com:8760/Application
  ProxyPassReverse / http://www.acme.com:8760/Application
  ServerName loremipsum.bar.com
 </VirtualHost>


Apollo React GraphQL VariableTypeMismatch error

Question: I've got a mutation that looks like this:
mutation ADD_CATEGORY($id: ID!, $category: ID!) {
  addCategory(id: $id, category: $category)
}

It is passed into my React component as addCategory.
My handleSave function looks like this:
    handleSave = () => {
      const { id, category } = this.state;
      addCategory({ variables: { id, category: category.id } });
    }

id and category.id are a string property on this.state object.
I get the following error:

[GraphQL error]: Message: Validation error of type
  VariableTypeMismatch: Variable type doesn't match, Location: [object
  Object], Path: null

Looking at the API from GraphiQL I see that the updateCategory mutation has the following arguments:
id: ID!
category: [ID!]!

What am I missing here?
Answer: Please make sure addCategory schema accepting String type for id & category.  From your API output looks like category is Array type.


python - how to not change an instantiation's attribute

Question: I have a pretty basic problem I guess, but I just can't get to the solution. My Code:
class Matrix:

    def __init__(self,data):
        self.data = data

    def __str__(self):
        display = []
        for row in self.data:
            display.append(str(row))
        return '\n'.join(display)

a = Matrix([[1, 2], [3, 4]])

print(a.data)

a.data = [[0,0],[0,0]]

print(a.data)

my first print works as intended: [[1,2],[3,4]]
but my second: [[0,0],[0,0]]
How can I stop my attribute value being changed by a.data = [[0,0],[0,0]]?
So that my second print also yields: [[1,2],[3,4]]?
I was looking for a solution pretty long, sorry if the question is already asked, I wasn't able to find any solution.
Comment: Why do you do `a.data = whatever` if you don't want to change the value of `a.data`?
Comment: Google for  `python __setattr__`
Comment: Possible duplicate of [How to make an immutable object in Python?](https://stackoverflow.com/questions/4828080/how-to-make-an-immutable-object-in-python)
Comment: Do you want people not to be able to change it? You could set it as "protected".
Answer: You need data to be a property:
class Matrix:
  def __init__(self,data):
    self._data = data
  def __str__(self):
    display = []
    for row in self._data:
        display.append(str(row))
    return '\n'.join(display)
  @property
  def data(self):
      return self._data

Unless you add a @setter the property will be read-only. So then this will happen if you try to assign a new value to data:
>>> a=Matrix([[1,2],[3,4]])
>>> print(a.data)
[[1, 2], [3, 4]]
>>> a.data = [[0,0],[0,0]]
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    a.data = [[0,0],[0,0]]
AttributeError: can't set attribute


What is the maximum number of cliques you can add to a graph by adding a vertex?

Question: Let $k$ be a positive integer and let $G=(V,E)$ be a graph with at least $k$ vertices.

What is the maximum number of cliques attainable by adding a vertex
$v$ to $G$ with $\deg(v)=k$?

My best guess is $2^k$, using the following example:
Let $G$ be the complete graph on $n$ vertices and let $k=n-1$. Then adding a vertex to $G$ with degree $k$ adds $2^k$ cliques. (I just did this by drawing examples for small $n$).
Is this correct?
Answer: That's right. Only as $k$ it is necessary to take $n$, that is, $k=n$.
If we add a vertex $v$ and connect it with all vertices of graph $G$, we obtain a complete graph with $n+1$ vertices.
Now each subset of vertices of graph $G$ together with vertex $v$ forms a new complete graph. Since there are exactly $2^n=2^k$ subsets in the set of $n$ elements, we obtain that the number of additional complete subgraphs is $2^k$.
Can there be more? The answer is 'no'. I think it is almost obvious. But if you doubt it, I'll give you this simple reasoning.


Prove that $f$ is differentiable

Question: One exercise from a list. I have no idea how to finish it.

Let $I=[c,d]\subset \mathbb{R}$.
Let $f:I\to \mathbb{R}$ be continuous at $a\in (c,d)$.
Suppose that there exists $L\in \mathbb{R}$ such that $$\lim \frac{f(y_n)-f(x_n)}{y_n-x_n}=L$$ for every pair of sequences $(x_n),(y_n)$ in $I$, with $x_n<a<y_n$ and $\lim x_n=\lim y_n=a$.
Prove that $f'(a)$ exists and it is equal to $L$.

Any help? Thanks in advance.
Comment: "I have no idea how to finish it." So I guess you started somewhere? What's your idea?
Comment: I tried to consider $z_n=y_n-x_n$ which converge to zero.
Comment: I think they require $x_n < a$
Comment: I have no idea what *I tried to consider $z_n=y_n−x_n$* could mean. You might want to explain.
Comment: Can you just do $\forall n\in\mathbb{N}, x_n=a$?
Comment: Could you first prove that $(f(y_m)-f(x_n))/(y_m-x_n)\to L$ as both $m,n\to\infty$, for any such pair of sequences $(x_n),(y_n)$?
Comment: @SeanEberhard, this is the hypothesis.
Comment: @Sigur Not quite. It's very slightly but very usefully different, since you could then let $x_n\to a$ first (using continuity of $f$).
Comment: @SeanEberhard, your suggestion is to consider sequences with different indexes, but still with the inequality?
Comment: @Sigur Yes. That's what I would try.
Answer: This proof uses the idea I indicated in my comment, even though it may not look like it.
I claim that
$$\frac{f(y_n) - f(a)}{y_n-a} \to L$$
for every sequence $(y_n)$ satisfying $y_n>a$ and $y_n\to a$. Indeed, given $y_n>a$ choose $x_n<a$ so that $|x_n-a|<1/n$ and
$$\left|\frac{f(y_n)-f(x_n)}{y_n-x_n} - \frac{f(y_n)-f(a)}{y_n-a}\right|<\frac{1}{n}.$$
(This uses the assumed continuity of $f$.) Now let $n\to\infty$ in this inequality.
Similarly we can prove that
$$\frac{f(a) - f(x_n)}{a-x_n} \to L$$
for every sequence $(x_n)$ such that $x_n<a$ and $x_n\to a$.
Comment: +1. Same idea as my own but much more compact. Well done.
Comment: Guys, I'd printed and I'll read carefully. Thanks for a while.
Comment: @EuYu I don't understand how continuity give that inequality...
Answer: Maybe this is one of these rare cases when reasoning by contradiction helps. Thus, assume without loss of generality that $L=0$ (otherwise, replace $f$ by $x\mapsto f(x)-Lx$) and that the conclusion is false.  Thus, either $f'(a)$ does not exist or $f'(a)\ne 0$, in any case, there exists a sequence $(z_n)_n$ and some $\varepsilon\gt0$ such that $z_n\ne a$, $z_n\to a$, and $|f(z_n)-f(a)|\geqslant2\varepsilon|z_n-a|$ for every $n$.
Assume without loss of generality that $z_n\lt a$ infinitely often and define $(x_n)_n$ as the subsequence of $(z_n)_n$ made of the terms $\lt a$ hence $x_n\lt a$, $x_n\to a$, and $|f(x_n)-f(a)|\geqslant2\varepsilon(a-x_n)$.
Now, $f(x)\to f(a)$ when $x\to a$, $x\gt a$, hence, for each $n$, one can choose $y_n\gt a$ such that $|f(y_n)-f(a)|\leqslant\varepsilon(a-x_n)$ and $y_n-a\leqslant\varepsilon(a-x_n)$. In particular, $(1+\varepsilon)(a-x_n)\geqslant y_n-x_n$. One gets
$$
|f(y_n)-f(x_n)|\geqslant|f(x_n)-f(a)|-|f(y_n)-f(a)|\geqslant\varepsilon(a-x_n)\geqslant(\varepsilon/(1+\varepsilon))(y_n-x_n),
$$
for every $n$, and, in particular,
$$
\frac{f(x_n)-f(y_n)}{y_n-x_n}\not\to0.
$$
Comment: This one was really helpful. Thanks!
Answer: The idea is that since the symmetric limit converges for every pair of sequences, we pick two sequences which show left and right convergence. If we define one sequence to be much closer to $a$ than the other, it becomes almost equivalent to approaching through the latter.
The below is more of a sketch than a proof.
Since $f$ is continuous, for each $n\in\mathbb{N}$ there exists $\delta_{n} > 0$ such that $$\vert x - a \vert < \delta_n \implies \vert f(x) - f(a) \vert < \frac{1}{n^2}$$
Let $a - \min\left(\delta_n,\frac{1}{n^2}\right)$ define $x_n$ and let $y_n = a + \frac{1}{n}$
$$L=\lim_{n\rightarrow\infty}\frac{f(y_n) - f(x_n)}{y_n - x_n}$$
$$=\lim_{n\rightarrow\infty}\frac{f(a + \frac{1}{n}) - f(a)}{\frac{1}{n} + \mathcal{O}\left(\frac{1}{n^2}\right)} + \frac{f(a) - f(x_n)}{\frac{1}{n} + \mathcal{O}\left(\frac{1}{n^2}\right)}$$
$$=\lim_{n\rightarrow\infty}\frac{f(a + \frac{1}{n}) - f(a)}{\frac{1}{n} + \mathcal{O}\left(\frac{1}{n^2}\right)} + \frac{\mathcal{O}\left(\frac{1}{n^2}\right)}{\frac{1}{n} + \mathcal{O}\left(\frac{1}{n^2}\right)}$$
$$=\lim_{n\rightarrow\infty}\frac{f(a + \frac{1}{n}) - f(a)}{\frac{1}{n} + \mathcal{O}\left(\frac{1}{n^2}\right)} = f'(a)$$
The argument should probably be made a bit more rigorous and general, in particular you must show that this convergence holds for every $y_n$ which will involve changing the delta argument a little bit (still requiring $x_n - a \ll y_n - a$ for whatever $y_n$ you should choose). But the overall idea should hold.

Prove that $f$ is differentiable


SQL Server Failover and Licensing

Question:
Possible Duplicate:
Can you help me with my software licensing question?

How many servers can I install SQL Server 2008 R2 Standard Edition on? I'd like to set up a backup server in case my main one dies. I'm not too familiar with what SQL Server Failover actually does. I'd prefer that if the main server dies I'd like to restore the database onto the backup server manually from a backup and switch over to the backup server. Is that possible with the Standard Edition or would I actually have to buy two Standard Editions?
Maybe this is what really Failover is, but I'm not too clear on what it actually does. I've done some reading on it, but I'm still confused.
Answer: SQL Server Failover Clustering refers to a configuration where you install identical instances of Microsoft SQL Server on 2 or more nodes in a Windows Failover Cluster, place your database and log files on a clustered disk and register the SQL Server Service in the same Application Group as a clustered network name and IP address. When one physical server (cluster node) fails, or gets rebooted, the SQL Server instance is brought online on one of the other nodes and you can quickly reconnect to your database.
A configuration like this ensures high-availability, but has nothing to do with manually restoring the databases in case of a failure
If you only use one SQL Instance at any one time (a so-called Active/Passive failover cluster configuration), you only need one license.
Read more on SQL Server Failover Clustering here: http://msdn.microsoft.com/en-us/library/ms189134.aspx
Comment: Do you know if Microsoft actually lets you install the same license key on two different servers? Or do I actually have deactivate the key on one server and activate it on the other when the server crashes?
Comment: 1 SQL Server Standard Edition license can be used (only) twice in one cluster configuration. If you need more than 2 nodes in an SQL Server Failover Cluster, you'll need the Enterprise version of SQL Server There's not much point to installing an automatic high-availability feature if you need to reconfigure the setup manually each time you need it.

SQL Server Failover and Licensing


Url Rewrite not working correctly

Question: I want to change this  url from :
 Site.com/Controller/myController.php?action=myAction&var1=y&var2=z

to :
 Site.com/myAction/var1/y/var2/z/..../varn/valn

Variables can be present or not.
No redirection
I tried many solutions but what i have done is just replacing Controller/myController.php with items:
RewriteEngine on
RewriteRule ^items/(.*)$ Controllers/myController.php$1

thank u
Answer: You can use this rule in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /

# recursion to replace /action/n1/v1/n2/v2 to QUERY_STRING
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\w+)(/.*)?$ Controllers/myController.php$2?action=$1 [L,QSA]

RewriteRule ^(Controllers/myController\.php)/([^/]+)/([^/]+)(/.*)?$ $1$4?$2=$3 [L,NC,QSA]

Comment: Not working , i added the Controller folder , but still not working
Comment: `RewriteEngine on
RewriteRule ^(\w+)/(\w+)/(\w+)/(\w+)/(\w+)/?$ Controllers/ebooksController.php?action=$1&$2=$3&$4=$5 [L,QSA,NC]`

my htaccess is empty , i added this  rule with and without Controllers folder , and then tried to access this page  :

     site.com/home

it should show the content of :

     site.com/Controllers/myController.php?action=home
Comment: Sorry , but this works only for fixed number of parameters (0 and 4 here)  , i need a dynamic one , depending of the number of get variables , sometimes , no one , sometimes 2 ,3 ....
Comment: Wow you totally changed the nature of the question in your last edit :)
Comment: sorry , it's my fault , i haven't put all details in the post , i will test this and tell you
Comment: thank uu , it works as expected , if you have time   , please do some comments
Comment: RewriteCond %REQUEST_FILENAME ! -d
RewriteCond %REQUEST_FILENAME ! -f
Comment: Sorry didn't what you mean by your last comment. I will add explanation in answer after work hours today.
Comment: Your htaccess made a problem , files ( css , imgs , js ) not work anymore , i added condition to exclude them from rewriting

Url Rewrite not working correctly


How to supply a text file with newlines as input to git push options

Question: I'm trying to set a GitLab merge request from the command line, using the -o merge_request.description="my merge request" option.
However, I wish to supply an entire Markdown file, and if I do this the command complains that newlines are not allowed. I have also tried using sed to replace all newlines with '\n', but these are then taken literally and my merge request is one line containing lots of '\n's.
Is there a way around this?
Comment: Then I'm afraid there is no way.
Comment: Does `-o merge_request.description="$(cat pr.md)"` help? (Requires Bash or git-bash)
Comment: Tried this thanks, I get `fatal: push options must not have new line characters`
Answer: Although git push options don't allow for newlines, you can replace newlines with
 to get a similar effect.
# ref: https://stackoverflow.com/a/1252191/5747944
description="$(sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/
/g' description.md)"
git push -o merge_request.description="$description"

Comment: Gotcha, yeah. That won't work with this solution, either. Tables, etc, also won't work if using usual markup. I don't think there's any solution for that given push options don't allow newlines.
Comment: This is potentially a solution if we change our MR templates to HTML but doesn't solve the issue for using markdown which is the preference
Comment: @tsvallender this does work for markdown. HTML markup like `` is allowed to be mixed in with markdown. Though, you will find when editing the description, the `` will be present instead of newlines, which may not be ideal for you. Unfortunately, that's simply a limitation of git push options.
Comment: Yes the tags are allowed within the markdown, but as markdown relies on certain characters - such as # - starting a line, these don't work as they are no longer on a new line.


Call a c# function from JavaScript in asp.net

Question: i have one function, which is named as callData() inside the c#. Now i want to call this function from JavaScript. I don't need any operations on JavaScript. Just i want to call that function. In this problem i don't need any other options.. Just i want to know how to call c# methods from JavaScript.
JavaScript

Html code

 <asp:Button ID="hbtn" runat="server" OnClientClick="Javascript:call();"/>

C# code
public static void callData()
{
 //some operations
}

Comment: Show your work and tell us what have you tried so far.. Give people more informations..
Comment: Dupicate: http://stackoverflow.com/questions/3994150/can-you-call-c-sharp-function-from-javascript
many many question like this before!
Comment: @AnhTú http://stackoverflow.com/questions/3994150/can-you-call-c-sharp-function-from-javascript this url just contains idea.. i need specific coding..
Answer: You can do this by making that C# function a web method with in a web service. Once you do that, you can make use of jQuery and call that function. To my knowledge you cannot just call a C# method within javascript.
Answer: You will need to decorate your C# server-side method with the WebMethod attribute and make it static to expose it as a callable AJAX member:
[WebMethod]
public static void callData() {
  //some operations
}

Then use the ajax method, something like so, in your JavaScript method:
$.ajax({
  type: "POST",
  url: "path/to/page/callData",
  contentType: "application/json; charset=utf-8",
  data: {},
  dataType: "json",
  success: function (data) { },
  error: function (xhr, status, error) { }
});

Where successFn, and errorFn are functions to handle successful or failing outcomes respectively, such as.


Deleting entry only if there is no more reference to other table

Question: i have three tables :
Parent:
Table A:
id tab_b tab_c
1  b1    c1
2  b1    c2

two child tables:
Table b:
id name
b1 ABC
FOREIN KEY (id) REFERENCES table A (tab_b) ON DELETTE CASCADE

Table c:
id name
c1 DEF
c2 GHI
FOREIN KEY (id) REFERENCES table A (tab_c) ON DELETTE CASCADE

if i want to delete c2 in Table c, only the entry c2 in Table C and the entry 2 in Table A should be deleted. b1 should only be deleted if there are no more entries with reference to it. Actually the entry in Table b will be deleted too. (i tried it with RESTRICT too, but there are nothing will be deleted). Is there a possibility to do it with ON DELETE/ ON UPDATE  and CASCADE / RESTRICT?
or have i to this proggrammicly in php?
i hope it´s clear what i want.
thanks in advance
Comment: `ON DELETE CASCADE` is designed to work going from parent to children, not the other way around.  So if you delete a record in A then it will also remove all children records.  Maybe you have a design problem.
Comment: I think you have mixed up your relations. Tables b and c look like the parent table, and table a looks like the child table because the id fields in tables b and c are part of the relationship. Therefore the fks should point from table a to tables b and c.
Answer: When using FKs, you can define "ON DELETE" with "CASCADE", "RESTRICT" or "SET NULL". When deleting an entry, which is a FK in other entries, "CASCADE" will delete them, "SET NULL" will set the FK to "NULL" and "RESTRICT" will stop the entire process.
What you want is the opposite as far as I understand. If you have three tables "A", "B" and "C" where "A" contains "n-n" references, you have to be tricky. Something like:
DELETE IGNORE  B, C
FROM    B
INNER JOIN  A
    ON      A.tab_b = B.id
INNER JOIN  C
    ON      A.tab_c = C.id
WHERE       c.id = ?;

If this doesn't work, set "ON DELETE CASCADE" in "A", delete the items in "C" manually and use an "AFTER DELETE TRIGGER" to take care of "B".


Hive multiple count (with and without DISTINCT) generate bad output

Question: I tried this Hive query
Select id,count(distinct CASE WHEN unix_timestamp(m_date) BETWEEN unix_timestamp(cast(date_sub(cast('2017-02-01' as date),60) as date)) AND unix_timestamp(cast('2017-02-01' as date)) THEN m_date ELSE 0 END)
         ,count(CASE WHEN unix_timestamp(m_date) BETWEEN unix_timestamp(cast(date_sub(cast('2017-02-01' as date),60) as date)) AND unix_timestamp(cast('2017-02-01' as date)) THEN m_date ELSE 0 END)
From DB.TABLE2 GROUP BY id limit 10;

And it gives me smthg like:
111007001007633 1       1
111007001029793 1       1
111007001000521 1       11
111007001000794 1       1
111007001000273 3       13
111007001001032 1       1
111007001025874 1       4
111007001001792 1       7
111007001029181 1       1
111007001000141 16      96

But when I add other count:
 Select id,count(distinct CASE WHEN unix_timestamp(m_date) BETWEEN unix_timestamp(cast(date_sub(cast('2017-02-01' as date),60) as date)) AND unix_timestamp(cast('2017-02-01' as date)) THEN m_date ELSE 0 END)
         ,count(CASE WHEN unix_timestamp(m_date) BETWEEN unix_timestamp(cast(date_sub(cast('2017-02-01' as date),60) as date)) AND unix_timestamp(cast('2017-02-01' as date)) THEN m_date ELSE 0 END)
         ,count(distinct CASE WHEN unix_timestamp(m_date) BETWEEN unix_timestamp(cast(date_sub(cast('2017-02-01' as date),15) as date)) AND unix_timestamp(cast('2017-02-01' as date)) THEN m_date ELSE 0 END)
         ,count(CASE WHEN unix_timestamp(m_date) BETWEEN unix_timestamp(cast(date_sub(cast('2017-02-01' as date),15) as date)) AND unix_timestamp(cast('2017-02-01' as date)) THEN m_date ELSE 0 END)
 From DB.TABLE2 GROUP BY id limit 10;

It returns something bad like this:
 111007001010439 0       0       1       0
 111007001026963 0       0       1       0
 111007001028001 0       0       1       0
 111007001032987 0       0       1       0
 111007001048710 0       0       1       0
 111007001052415 0       0       1       0
 111007002008374 0       0       1       0
 111007003000644 0       0       1       0
 111007003002210 0       0       1       0

I work on hadoop cluster and I don't if it's caused by the map reduce.
Thanks
[EDIT]
As I answered to @pashaz comment, the first problem is the results from the two same queries (with and without distinct) which give 1 for distinct and 0 for non distinct.
The second problem is the results between the two distinct queries and the two non-distinct queries. If you check the timestamps you'll see that the first queries contains the seconds because the two firsts count occurrences between "2017-02-01" and 60 days before, the 2nds count occurrences between "2017-02-01" and 15 days before.
[UPDATE]
If I put a WHERE clause it works
 WHERE id="111007001007633" OR id="271011604404359" OR id="122213250512607" OR id="111007001033217"

111007001033217 0       0       0       0       0       0
122213250512607 1       3       8       14      0       0
271011604404359 12      21      26      42      5       9
111007001007633 14      19      24      34      5       5

The LIMIT clause seems to be the problem.
Comment: Is the second query returning those results (0,0,1,0) for every single row?  What happens if you run the second query for one of the rows that the first query returns "valid" results for, like 111007001000141?
Comment: @Andrew I don't know, I will check and give you the result ASAP
Answer: Nothing bad in provided results. In both queries present "limit 10". There no garantee that the same ID will be returned.
In first query results present "111007001007633" which absent in second query.
Comment: Check the query ! Each time the 1st is distinct, the 2nd is the same without the distinct , so it's incorrect to have 1 then 0... not sure there is nothing bad


Excel VBA If Then Function conditional on cell values

Question: I want to calculate a price based on a proposed discount % or calculate a discount based on a proposed price.
I need users to be able to use either parameter and adjust back and forth to determine their ideal price.
I have coded the formulas so that nothing is overwritten by the user but have a problem as the 'value if false' element of the "IF" formula is dependent on a zero value in one column and so resets if the user doesn't manually adjust this before inputting a figure into another.  This results in the new figure being reset.
Ideally I would like the sheet to reset the value in column "Proposed Promo POR%" to zero if a value is input in "Promo Price per Unit".  Is this possible?
This is the code I have at the moment.
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Intersect(Target, Range("b21:b26")) Is Nothing Then Exit Sub

Application.EnableEvents = False
ActiveSheet.Range("$i21:$i26").Formula ="=IF(Proposal!$b21>Formulae!$a$5,Proposal!$g21-(Proposal!$g21*Proposal!$b21),  (Proposal!$g21-Proposal!$i21)/Proposal!$g21)"
Application.EnableEvents = True

End Sub

For clarity Formulae!$a$5 is zero and it is column $i21:$i26 that the user will enter a price in if they want to.  If they do enter something here then column b should reset to zero.
This is a screenshot of the columns and headers in my sheet
Answer: The Worksheet_Change event will help you. Worksheet_SelectionChange fires each time a user changes the active cell, whereas Worksheet_Change fires anytime a user makes an edit to any cell(s).
Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("$i21:$i26"")) Is Nothing _
    And Target.Rows.Count = 1 and Target.Columns.Count = 1 Then
    'assumes event will fire only on changing one cell at a time

    Application.EnableEvents = False
    Target.Offset(0,-7).Value = 0
    Application.EnableEvents = True

End If

End Sub

Comment: *(+1) from my side.* Still, I am not sure if you might want to add the condition `IF` something has been actually entered. Maybe something like `If Trim(Target.Value2) <> vbNullString And Isnumeric(Target.Value2) Then`... just a thought.
Comment: Good thought @Ralph. Will leave for OP to add at his discretion.
Comment: Thank you for the responses.  I think I know what you're getting at but I'm quite new to VBA so would appreciate a bit more guidance as to how I actually construct the code with my specific conditional calculations included.
Comment: @LBow509 - *I would like the sheet to reset the value in column "Proposed Promo POR%" to zero if a value is input in "Promo Price per Unit".* - This is what I have done in code in this answer.
Comment: Also, you can use R1C1 notation for the formula. It will be a lot easier.
Comment: Thank you for your help with this I really appreciate it.  Unfortunately though the code you've provided isn't working for me - I'm getting a compile error message.   In a nutshell I want the sheet to perform the following steps:
Comment: 1: If a value is entered in col b then formula based on this value. 2: If a manual value is entered in col I then reset col b to 0 and formula based on new value. I was close with my original code in that I could do either calculation but the new value in I was always being overridden by the value in col B. Sorry if I'm not being clear but I really appreciate any help you can offer!
Comment: I am unclear on the formula. If value is entered in column B, you want to the formula in column I to be as stated in original question. However, this formula refers to column I in it, so that is not possible, as you want to a formula to refer to itself. If I misunderstanding, please clarify.
Comment: Thanks @Scott.  So to clarify I want the following to happen.    1) If % in Column B is greater than zero calculation in Column I is 'Col G-(Col G*Col B).   2) If a value manually entered in Column I, reset Column B to zero and run, in Column H, calculation (Col G - Col I)/Col G.    I want users to be able to adjust either column B or Column I alternately to try and determine final price without overwriting formulas needed to make the calculations work in the columns detailed above or the rest of the sheet.  I hope that clarifies and thank you again for your help!


String.format() for multiple attributes in the same row

Question: I am trying to compress my code and I get four String.format() in the same line. Is there a way to do it in a cleaner and more simple way?
My code block:
String startX = String.format("%03d", mission.getStartX());
String startY = String.format("%03d", mission.getStartY());
String endX = String.format("%03d", mission.getEndX());
String endY = String.format("%03d", mission.getEndY());

Thanks :)
Answer: The only way I can see to tidy up a bit, to have a DRY (don't repeat yourself) code, is to define a method, say format03d() as follow:
private String format03d(int x) {
    return String.format("%03d", x);
}

One advantage is that your code is centralized in one place. If one day you want to change the way you convert your decimals to strings, you change it there.
You can then call the method on your variables:
String startX = format03d(mission.getStartX());
String startY = format03d(mission.getStartY());
String endX = format03d(mission.getEndX());
String endY = format03d(mission.getEndY());

I assume that your variables are integers.
If you want to go down the road of collections, you can use streams.
Stream.of(
      mission.getStartX(),
      mission.getStartY(),
      mission.getEndX(),
      mission.getEndY())
   .map(x -> String.format("%03d", x))
   .collect(Collectors.toList())

This will give you a list of your formatted integers.
Comment: Yes, following your idea I will send to the method the variables as a List of Integers and then format them there and operate them as I want
Comment: If you want to go down the road of collections, see my edit.


EntityState - Como funciona

Question: O que seria e pra que serve o EntityState do Entity Framework?
Quando ele pode ser aplicado? Algúem tem algum exemplo de porque usar ele?
Answer: Pra você entender como funciona o EntityState você tem que entender o ciclo de vida da entidade (Entity Lifecycle).
Qualquer operação CRUD é feita através do contexto (context) que criamos do banco de dados. Esse contexto guarda uma referência para todos objetos e suas modificações nas propriedades (change tracking).
Então, quando você pega um objeto existente do contexto, ele se torna uma entidade e tem seu estado monitorado. Se você modifica a entidade editando suas propriedades, você a passará para o estado de modificada. Depois, salva as mudanças no contexto e ele no banco de dados.
Exemplos de uso
Adicionando uma nova entidade ao contexto:
var cliente = new Cliente { Name = "Marcos" };
context.Entry(cliente).State = EntityState.Added;
context.SaveChanges();

Adicionando uma entidade ao contexto que não esta sendo monitorada por ele:
context.Entry(ClienteExistente).State = EntityState.Unchanged;

Adicionando as modificações de uma entidade ao contexto:
context.Entry(ClienteExistente).State = EntityState.Modified;

Mudar o estado da entidade (você pode alterá-lo):
// Mudando para unchanged
context.Entry(existingBlog).State = EntityState.Unchanged;

Por fim, vale lembrar que o uso do EntityState explicitamente não é obrigatório, você pode usar apenas quando necessário.
Comment: Qual vantagem em utilizar a mesma? Por exemplo, no primeiro item, não daria no mesmo aplicar: Cliente cli = new Cliente();
            cli.nome = txtNome.Text;
            cli.email = txtEmail.Text;

            Cliente c = ctx.Clientes.Add(cli);

            ctx.SaveChanges();
Comment: Como ficaria um exemplo de update com EntityState? (onde eu queira atualizar apenas 1 campo, por exemplo)
Comment: Daria na mesma. O comando Add esta fazendo a mesma coisa que aquele comando. Você esta trabalhando com o estado da entidade da mesma forma. A questão não é vantagem ou desvantagem e sim entender como funciona o Entity Framework.
Comment: Entendi, tem como colocar um exemplo de atualizar um field no modelo que citou acima: context.Entry(ClienteExistente).State = EntityState.Modified;
Comment: Você mudará quantas propriedades que quiser na view e no controller você usa o exemplo que dei "adicionando as modificações...) seguido de um contexto.SaveChages()
Comment: Se voce quiser um exemplo completo posso te mostrar no chat
Comment: Oi Sim, porque eu fiz um exemplo de update e está funcionando, e gostaria de saber da maneira de fazer via EntityState.Modified e a diferença técnica ou em performance de um pro outro!
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/57953/discussion-between-luhhh-and-fabri-damazio).

EntityState - Como funciona


Wolframalpha - how to get value of function in a specific point?

Question: For example , given this function  -
$f(x) = x^3-x^2-x-1$
and I want to check it in the point $x=1.6$.
What should I have to write in the command line of wolframalpha in order to get it  ?
Answer: The input
<code> evaluate x^3-x^2-x-1 at 1.6
</code>
seems to work. Here is the link. Here is an image:
Answer: Asking politely:
<code>please compute x^3-x^2-x-1 at x=1.6
</code>
did the work for me.
Comment: Indeed. I removed the "please" and it did not work :)
Comment: It's rather charming to see such an insistence on manners.
Answer: You could do it like this:
http://www.wolframalpha.com/input/?i=evaluate+x%5E3-x%5E2-x-1+at+x+%3D+1.6
However, you could also do a table like this:
http://www.wolframalpha.com/input/?i=Table%5B%28x%5E3-x%5E2-x-1%29%2C+%7Bx%2C+0%2C+16%2C+1.6%7D%5D
Answer: "evaluate x^3-x^2-x-1 at x=1.6" works for me.


Listview ocupar toda a tela

Question: Tenho este listview
main.xml
 <ListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/praias"
    android:layout_above="@+id/adView"
    />

Eu tava Querendo que o item deste listview ocupasse a largura total , ele ja esta como fillparent então eu acho que ele deveria estar ocupando a tela toda ne. Como eu faço para não ficar esses espaços em branco nas bordas
itens.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Bertioga"
    android:textColor="#000000"
    android:gravity="center"
    android:id="@+id/nomePraia"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/fotoPraia"
    android:layout_below="@+id/nomePraia"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/bt" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Coemçar a descrição ...."
    android:id="@+id/descricao"
    android:maxLength="400"
    android:textColor="#000000"
    android:layout_alignTop="@+id/btFavorito"
    android:layout_toEndOf="@+id/btFavorito"
    android:gravity="left"
    android:layout_toStartOf="@+id/bt"
    android:layout_toRightOf="@+id/btFavorito"
    android:layout_toLeftOf="@+id/bt" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btVerMais"
        android:id="@+id/btVerMais"
        android:background="#fff"
        android:textColor="@color/wallet_link_text_light"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btFavorito"

        android:background="@drawable/ic_action_favorite"
        android:layout_alignTop="@+id/bt"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt"
        android:background="@drawable/ic_action_overflow"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Comment: E quanto ao layout dos itens desta lista? Coloque-o também na pergunta, provavelmente nele está o problema.
Comment: ata vou colocar
Answer: Tente isso:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context="${relativePackage}.${activityClass}" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="0dp" >

    <ListView
        android:id="@+id/listViewIntervalDetails"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/checknormal"
        android:cacheColorHint="#00000000"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:longClickable="true"
        android:padding="2dp" >
    </ListView>
</LinearLayout>

Comment: não entendi testar aonde
Comment: troca onde está seu listview por esse:  ...continua

Listview ocupar toda a tela


Understanding a basic ergodic theory physical analogy

Question: The following excerpt is from the Wikipedia article on ergodic theory:

Ergodic theory is often concerned with ergodic transformations. The intuition behind such transformations, which act on a given set, is that they do a thorough job "stirring" the elements of that set. E.g. if the set is a quantity of hot oatmeal in a bowl, and if a spoonful of syrup is dropped into the bowl, then iterations of the inverse of an ergodic transformation of the oatmeal will not allow the syrup to remain in a local subregion of the oatmeal, but will distribute the syrup evenly throughout. At the same time, these iterations will not compress or dilate any portion of the oatmeal: they preserve the measure that is density.
The formal definition is as follows:
Let $ T: X \rightarrow X$  be a measure-preserving transformation on a measure space $(X, \Sigma, \mu)$, with $\mu(X)=1$. Then $T$ is ergodic if for every $E $ in  $\Sigma$ with $\mu(T^{-1}(E) \Delta E)=0$, either  $\mu(E)=0$ or $\mu(E)=1$,

How could I formalize pouring the syrup into my oatmeal? Would I describe the oatmeal by a density function in $\mathbb{R}^n$? Say $\mu$ is Lebesgue measure on $\mathbb{R}^n$, then I have some density describing the location of the oatmeal, say $\rho d\mu$. Would the transformation be ergodic w.r.t. $$m(A) =\int_A fd\mu$$ or with resepct to $\mu$? When I describe the combination of the syrup and the oatmeal, would this create a new density at time $t$? This is confusing as I would assume the oatmeal and syrup have their own densities so I am unsure which measure the transformation is ergodic with respect to.
Comment: You need an action $T$ to describe mixing. Integration is one possibility, but is rather degenerate. Measure preserving tells us how $\mu(T)$ acts, which is a global concern, while ergodicity tells us how subspaces act. I'm not a huge fan of the definition your source gives, but it essentially comes down to saying that given a set $A$, the flow into $A$ came from and is exactly $A$ iff $A$ has full or null measure.
Comment: For example, if break a vial of gas in a box and track a nondegenerate subspace of the box, then the gas must "flow" out of the subspace unless we had chosen the whole box. A degenerate case could be the boundary, where the notion of flow can be hazy. In any case, this "flowing" is the action, and it's an action that's ergodic. To muddy the water a bit, we do call the measure with to respect to which $T$ is ergodic an "ergodic measure" which might have confused you.
Comment: To actually answer the question, in the analogy the "syrup" is a subspace of the "oatmeal", so it's with respect to the oatmeal measure that mixing the syrup throughout the mixture is "ergodic" (the analogy arguably better describes a mixing system rather than an ergodic system, though these are related notions)
Comment: @BrevanEllefsen So everything exists say in $\mathbb{R}^3$, and oatmeal measure, say $\mu_{\text{oatmeal}}$ is a measure on $\mathbb{R}^3$? Thus,  our measure space is $(\mathbb{R^3}, \mathcal{B}_{\mathbb{R}},\mu_{\text{oatmeal}}) $? Would this mean that to describe where the oatmeal is, we don't necessarily say it is in some definitive set, but rather we say in this region, this is how much oatmeal there is? Would we be able to describe the set in which the oatmeal lies by say the support of $\mu_{\text{oatmeal}}$?
Comment: The oatmeal just inherits the Lebesgue measure from ambient space. The property of playing nicely with the ambient measure (the "density" part of the quote) is just stating that $T$ is measure preserving (sortaish, at least up to injectivity). You could describe the support, but for the purpose of defining ergodicity it shouldn't matter where the oatmeal is or how we choose to formalize or describe it. (all that matters is that it's compact, which is generally a requirement to give a well-defined probability measure)
Comment: @BrevanEllefsen So the interior of the bowl is the oatmeal with lebesgue meausre and I don't need to hink about a mass measure here? It's more the densities w.r.t. that notion of volume which describe the two?
Answer: When you pour a glop of syrup into your oatmeal, the contents of the bowl can be modelled as a set $X$ broken into a disjoint union of two measurable subsets $X = S \sqcup O$: $S$ represents the glop of syrup; and $O$ represents the original oatmeal.
Letting $\chi_S,\chi_O : X \to \{0,1\}$ be the characteristic functions, we have $\chi_S(x)+\chi_O(x)=1$ for all $x \in X$.
The volume measure on $X$ can be modelled as Lebesgue measure $\mu$ restricted to $X$, and normalized so that $\mu(X)=1$. You could then express both the syrup and the oatmeal as densities $\chi_S d\mu$, $\chi_O d\mu$.
The transformation itself is being modelled (somewhat unrealistically) as a measure preserving bijection $T : X \to X$.
I do not know what you mean by $f$, it is not otherwise mentioned in your post. But what I'll say is that $\mu$ itself is invariant under the transformation $T$, and so $\mu(A) = \mu(T(A))$ for all $A$, which can be written as $\int_A d\mu = \int_{T(A)} d\mu$.
One key point of ergodicity, as applied to this "syrup/oatmeal" picture, is that neither $S$ nor $O$ is invariant under $T$: neither $\mu(T^{-1}(S) \Delta S)$ nor $\mu(T^{-1}(O) \Delta O)$ is zero. To put it another way neither of the two characteristic functions $\chi_S$, $\chi_O$ is invariant under $T$.
Nonetheless, as one iterates $T$ more and more (as one stirs the oatmeal more and more), the real key point is that function $\chi_S \circ T^{-n}$ has a limit in some appropriate sense, that limit is $T$-invariant, and that limit is actually the constant function $\mu(S)$ with associated distribution $\mu(S) d\mu$ ($T$ will "distribute the syrup evenly throughout"). For this to work one has to take the limit of the function sequence $\chi_S \circ T^{-n}$ very carefully, usually in $L^2(X)$ or $L^1(X)$.
By the way, I have written my answer under the assumption that $T$ is a bijection, which allows me to be careless and write things like $\chi_S \circ T^{-n}$. One can certainly be more careful and rewrite all of this in the general case that $T$ is not a bijection.
Comment: Why do we consider $T^{-n} o\chi_S$ and not $T^{-n} o \chi_X$, since we are stirring both the oatmeal and the syrup? Would this correspond to at every point there is both oatmeal and syrup so it's meaningless? Also, how is this well defined since $T^{-n}:X\to X$ but $\chi_X : X\to {0,1}$?
Comment: Did you mean $\chi_S o T^{-n}?$
Comment: Ah, yes, I'll fix that.
Comment: Regarding your comment about $\chi_X \circ T^{-n}$ versus $\chi_S \circ T^{-n}$, note that $\chi_X$ is the constant function with value $\chi_X(x)=1$ for all $x$. So also $\chi_X \circ T^{-n}(x)=1$ for all $x \in X$. This is a very boring situation.
Comment: On the other hand the sequence of functions $\chi_S$, $\chi_S \circ T^{-1}$, $\chi_S \circ T^{-2}$, $\chi_S \circ T^{-3}$,... is very interesting: $\chi_S d\mu$ is the original distribution of the syrup after it has first plopped into the oatmeal; $\chi_S \circ T^{-1} d\mu$ is the distribution of the syrup after one turn of the mixer; $\chi_S \circ T^{-2} d \mu$ is the distribution of the syrup after two turns of the mixer, and so on.
Comment: How does this indicator function know where the new elements of $S$ ended up? Wouldn't it not pick up the new locations and simply just "light up" over the set $S$ where it started?
Comment: That's a straightforward set-theoretical issue. For example, $\chi_S(x)=1$ if and only if $x \in S$, by definition. Next, $\chi_S \circ T^{-1}(x) = 1$ if and only if $\chi_S(T^{-1}(x)) = 1$ if and only if $T^{-1}(x) \in S$ if and only if $x \in T(S)$ if and only if, after one turn of the mixer, the subset representing the new position of the glop of syrup includes the point $x$.
Comment: Here, perhaps, is one other set theoretic point to understand about modelling this situation: the set $S$ represents the initial glop of syrup; the set $T(S) = \{T(x) \mid x \in S\}$ represents where the syrup has moved to after one turn of the mixer; ... ; for general $n \ge 1$ the set $T^n(S) = \{T^n(x) \mid x \in S\}$ represents where the syrup has moved to after $n$ turns of the mixer.
Comment: Is it true that $\chi_{T^n(S)}(x) = \chi_S(T^{-n}(x))$?
Comment: Something like that, but not exactly that: $\chi_{T^n(S)}(x)=1$ if and only if $x \in T_n(S)$ if and only if $T^{-n}(x) \in S$ if and only if $\chi_S(T^{-n}(x))=1$. Therefore, $\chi_{T^n(S)}(x) = \chi_S(T^{-n}(x))$.
Comment: This makes much more sense thank you very much. So if the transformation is ergodic, in the limit, the density will take over the whole space uniformly, rather than clumping up at some other location.
Comment: Although again I am assuming $T$ is invertible to allow me to write $T^{-n}(x)$; with care something similar can be derived in general.
Comment: Yes, your last comment is exactly the point.
Comment: One more question, if I were to look at the oatmeal in a physical setting without approximations, would the distribution be an atomic measure? Since oatmeal is made up of atoms and particles in a physical setting. Of course it would be insane to model this way, and would be much better to just say the density of the oatmeal is uniform and nonatomic throughout the bowl.
Comment: That's quite a bit beyond my expertise. I don't know the source of that quote, but I'm quite sure the whole "oatmeal, syrup" thing was just a way to try to impart some intuition to the concept of ergodicity. After all, most mathematical models of physical phenomena are just that, models.
Answer: I would like to make a few comments; complementary to Prof. Mosher's answer.

It might be helpful to consider the following characterization of ergodicity of $(\mu,T)$: Given two measurable subsets $A,B\subseteq X$, the measure $\mu(T^{-n}(A)\cap B)$ (which models the chance of a point $x\in X$ that starts somewhere in $B$ to end up somewhere in $A$ at time exactly $n\in\mathbb{Z}_{\geq1}$ under the time evolution $T$) is comparable to $\mu(A)\mu(B)$ for large $n$, on average, that is, $(\mu,T)$ is ergodic iff

$$\forall A,B\in\Sigma: \lim_{n\to \infty} \dfrac{1}{n}\sum_{k=0}^{n-1}\left[\,\mu(T^{-n}(A)\cap B)-\mu(A)\mu(B)\,\right]=0.$$
The term over which we average here can be thought of as a "correlation" or "covariance"; the fact that it decays in time in some sense means that events get independent asymptotically. (see my answer at What's so special about standard deviation? for more on this.)
I should remark that in the above characterization of ergodicity if one replaces the square brackets with absolute value, one obtains a stronger property called "weak mixing", and if one further drops the averages one obtains an even stronger property called "strong mixing" (the "mixing hierarchy" goes further than that, but the definitions get more sophisticated, at least with this formalism.)

There is something to be said about the time parameter being discrete. One could make sense of this by referring to the fact (?) that human perception is discrete (biologically there is a minimum time length beyond which we don't perceive), and ergodic theory is supposed to model (human) observation. Or else one could think that for one reason or another (due to the fault or low precision of the instruments, or the cost etc.) we make stroboscopic observations. Of course mathematically there is a well-developed ergodic theory of continuous time (and beyond).

This is more of a historical comment. Arguably one of the earliest such heuristics regarding mixing properties is from Halmos's Lectures on Ergodic Theory (p.37), where he mixes vermouth and gin. There is a nice discussion of this in Brown's Ergodic Theory and Topological Dynamics (p.15); here is an excerpt:

To borrow an illustrative example from Halmos [32], suppose that a
mixture is made containing 90% gin and 10% vermouth. If the process of
stirring the mixture is ergodic, then after sufficient stirring any portion
of the container will contain on the average (with respect to the number of
stirrings) about 10% vermouth.

The correspondence is as follows: $A$ represents an anonymous part of the container one is observing, $B$ represents that part of the container where the vermouth is originally located. Thus $\mu(B)=0.1$. In order for the observation to be nontrivial, say $\mu(A)>0$, so that the observed part has positive volume. Then renormalizing the correlation above, we get that for $n$ large, on average
$$\dfrac{\mu(T^{-n}(A)\cap B)}{\mu(A)}\approx \mu(B) = 0.1,$$
that is, approximately 10% of the part we are observing will be occupied by vermouth. (How large $n$ ought to be depends on $A,B$ and how good of an approximation one wants, assuming $(\mu,T)$ is fixed.)
For the record, this heuristic only started making sense to me after getting accustomed to being able to think of the direction of time consistently (formally the difference between the past and the future may be confusing, and it depends on the interpretation).