prove\disprove if $f\circ g$ is invertible then $g\circ f$ is invertible

Question: The question is to prove\disprove that if $f\circ g$ is invertible then $g\circ f$ is invertible. $f:A\to B$, $g:B\to A$. (f,g are functions)
I tried to prove it but always got stuck, so I began wondering it's a disapproval.
To disprove I chose g as injective and non-surjective function, while f chosen to be surjective and non-injective.
Thus, I get $f\circ g$ as invertible, however $g\circ f$ isn't a function and thus can't be invertible (as a disproof).
Is it correct what I did here? would appreciate your notes.
Comment: If $f : A \to B$ and $g : B \to A$ are functions, then $g \circ f$ will always be a function. Whether or not is it invertible is another story.
Comment: Why do you say $g\circ f$ is not a function?
Comment: @Ami: It's best to construct a counterexample. (A "failure to prove" is inconclusive. :) Suggestion: Let $A$ be a set of two elements and $B$ be a set of one element. You don't have much choice for $f$ and $g$; what do you conclude in this case?
Comment: So is it a proof??
Comment: No. If $g \circ f$ is a function, it *can* be invertible.
Comment: If, in addition, $f$ is one-one and $g$ is onto, the claim becomes true.
Comment: Of course it's always a function — you *can't* prove *that*. But it doesn't have to be invertible. $g$ might be a one-sided inverse of $f$. The same as non-square matrices.
Answer: Hint: suppose $B=\{0\}$ and $A=\{1,2\}$. For any function $g\colon B\to A$ and any function $f\colon A\to B$, the function $f\circ g\colon B\to B$ is invertible.
Answer: The implication is false for a very general reason: it would imply that all surjections are bijections, as would also be all injections, which is known to be trivially false.
Indeed, if $f\colon A\to B$ is a surjection, there exists a map $g\colon B\to A$ such that $f\circ g=\operatorname{id}_B$, which is a bijection. If the implication were true, $g\circ f$ would be a bijection, which implies $f$ is an injection. Hence $g$ would be a bijection.
A similar argument  shows all injections would be  surjections, hence bijections.
As a consequence, all natural numbers would be equal.
Comment: and that would be a serious contradiction. thus - the assume was wrong - then gf isn't invertible?
Comment: I didn't say that: $g\circ f$ *need not*  be invertible – but it may. If $f$ is bijective, it is true.


Train Mask R-CNN with some classes having no masks but only bounding boxes

Question: I want to train a model to detect three different types of defects. I have a training dataset where two of these classes contain segmentation masks, but one contains only bounding boxes. Can I train a shared model or do I need to separate the training dataset and train a Faster R-CNN and a Mask R-CNN?
(I only care about bounding box output for the class containing no masks in the training data.)
Answer: You can create 'weak' masks from those bounding boxes and then combine those two datasets. Something like below:
mask = np.zeros((256, 256), dtype=np.float32)
mask[y:y+h, x:x+w] = 255.

If the two datasets are small, combining them will yield better results. But if the datasets are big enough (>2000 images) then you can use FasterRCNN + MaskRCNN approach.


Ponticello notation in Guitar Pro 6

Question: Is it possible to add a ponticello (near the bridge, bright sound) notation in Guitarpro 6 for Classical Guitar compositions?
Answer: Just add the text sul ponticello next to whatever place in the score that you want it to be seen.
Comment: Thank you for you answer Williams, would it be possible to get a ponticello effect when playing back the track in GuitarPro as well?

Ponticello notation in Guitar Pro 6


Test in R whether coefficient estimates of categorical variables are different in linear regression

Question: How do I check in R whether coefficients of different levels of categorical variables are statistically the same. The model that I have is:
Y = Intercept + X1 + X2 + X3 + X4

Both X1 and X2 are categorical variables with 3 and 4 levels each. X3 and X4 are continuous variables. I came to know that in R we can check whether coefficients of two continuous variables are the same using the following procedure. For instance, if I want to check whether X3 and X4 have the same coefficient, I could do the following:
Model1: lm(y~X1+X2+I(X3+X4))
Model2: lm(y~X1+X2+X3+X4)

Then, I can do an anova test as follows:
anova(Model1,Model2)

Now, how do I check whether the coefficients for different levels of X1 are the same. The regression output will give 2 coefficient estimates (or should I say intercepts?) for X1 as it has three levels. How to check whether these estimates are statistically different from each other?
Answer: There is nothing too special about categorical variables when we use lm. If X1 has three levels, what happens is that we represent X1 in terms of three binary variables whose sum is always one (i.e., only one of them equals one at any observation). So, then we want to test whether all the levels have the same coefficient. Let
set.seed(1)
df <- data.frame(y = rnorm(10), x = factor(sample(1:3, 10, replace = TRUE)))
(mod <- lm(y ~ x - 1, data = df))
#
# Call:
# lm(formula = y ~ x - 1, data = df)
#
# Coefficients:
#       x1        x2        x3
#  0.64897  -0.30579  -0.02534

Hence, we want to test H0 that x1, x2, and x3 have the same coefficients.
library(car)
linearHypothesis(mod, c("x1 = x2", "x2 = x3"))
# Linear hypothesis test
#
# Hypothesis:
# x1 - x2 = 0
# x2 - x3 = 0
#
# Model 1: restricted model
# Model 2: y ~ x - 1
#
#   Res.Df    RSS Df Sum of Sq      F Pr(>F)
# 1      9 5.4838
# 2      7 3.5987  2    1.8852 1.8335 0.2289

As expected, we cannot reject the null in this example.

Then there's another, somewhat simpler way to see this. Let now
(mod <- lm(y ~ x, data = df))
#
# Call:
# lm(formula = y ~ x, data = df)
#
# Coefficients:
# (Intercept)           x2           x3
#      0.6490      -0.9548      -0.6743

so that now the interpretation of the coefficients of x2 and x3 is "additive". E.g., when the level of x is 2, how much higher is y than when the level is 1? So, in this case, if the effect of all three levels is the same, in this specification x2 and x3 will have zero coefficients. Thus,
linearHypothesis(mod, c("x2 = 0", "x3 = 0"))
# Linear hypothesis test
#
# Hypothesis:
# x2 = 0
# x3 = 0
#
# Model 1: restricted model
# Model 2: y ~ x
#
#   Res.Df    RSS Df Sum of Sq      F Pr(>F)
# 1      9 5.4838
# 2      7 3.5987  2    1.8852 1.8335 0.2289

gives, as expected, the same p-value.

On the other hand, if all the levels have the same effect, then x is nothing but a constant variable, like the intercept. So then the first testing option above can be seen as testing that x is as useful as the intercept, while the second one, equivalently, that x doesn't add anything useful over the intercept.


Probabilities of Dice Pools

Question: Given 5 fair, 6-sided dice, calculate the probability of an equal or greater number of dice showing 1 appearing than the number of dice showing 4,5, and 6 combined.
For example: if 5 dice are rolled and show:
1,1,1,4,5: this means 3 dice showing 1's > 2 dice showing 4+ = fulfills condition
1,1,2,5,6: this means 2 dice showing 1's = 2 dice showing 4+ = fulfills condition
5,2,1,3,5: this means 1 dice showing 1 < 2 dice showing 4+ = fails condition
Edit:
I began by listing combinations that fulfill the condition from most number of 1's rolled to least:
1,1,1,1,1 = 1
1,1,1,1,2+ = 5 possibilities * 5 positions = 25
1,1,1,2+,2+ = (5*5) possibilities * (5+5) positions = 250
1,1,(2,3),2+,2+ = (5*5*2) possibilities * (5*5) positions = 1250
1,(2,3),(2,3),(2,3),2+ = (5*2*2*2) possibilities * (5*4) positions = 800
So Probability = (1+25+250+1250+800)/5^6
which is: 0.1488
This seems high!
Comment: It seems relatively simple (possibly somewhat tedious) to list all the relevant cases and add their probabilities together. Perhaps if you could describe what you tried and where you ran into trouble (or if you solved it, show your solution to be checked) then you could get some more useful advice.
Answer: Your $1,1,1,2+,2+$ should have $5 \choose 2$ positions, which happens to be equal to $5+5$.  Your $1,1,(2,3),2+,2+$ includes some cases like $1,1,2,5,6$ which fail.  It should be $1,1,(2,3),(2,3),2+$.  It also triple counts cases like $1,1,2,2,3$, because each of $2,2,3$ can be the $2+$  Both are true in the next line as well.  Finally, the denominator should be $6^5$, not $5^6$
Answer: Let $a$ represent ones, $b$ represent two and three, and $c$ represent four, five, and six.
$(a+b+c)^5 =
a^5+5 a^4 b+5 a^4 c+10 a^3 b^2+20 a^3 b c+10 a^3 c^2+10 a^2 b^3+30 a^2 b^2 c+30 a^2 b c^2+10 a^2 c^3+5 a b^4+20 a b^3 c+30 a b^2 c^2+20 a b c^3+5 a c^4+b^5+5 b^4 c+10 b^3 c^2+10 b^2 c^3+5 b c^4+c^5$
provides the representation of possible outcomes, where the coefficient is the number of ways some outcome can happen, and the exponents are the number of each of the three types, e.g., $10a^2b^2c$ shows there are ten ways that the five rolls can be two of type $a$ and two of type $b$ and one of type $c$.
By inspection, remove the terms where the exponent of $c$ is greater than that of $a$,
leaving
$a^5 + 5 a^4 b + 10 a^3 b^2 + 10 a^2 b^3 + 5 a b^4 + b^5 + 5 a^4 c +
 20 a^3 b c + 30 a^2 b^2 c + 20 a b^3 c + 10 a^3 c^2 + 30 a^2 b c^2$
Substitute the probabilities of each type ($1/6$ for $a$, $2/6$ for b and $1/2$ for $c$), resulting in a probability of $\frac{77}{324}$ ~ $0.24$.
If the requirement exludes the case where neither ones or 4/5/6 are present, simply remove the isolated $b$ term, resulting in a probability of $\frac{227}{972}$ ~ $0.23$
Comment: The new user G Cab says this: Just a little flaw:  the example you gave "eg. $10a^{\,2} b^{\,2} c$ .." should be corrected to $30a^{\,2} b^{\,2}  c$.

Probabilities of Dice Pools


How to make Object bound to WPF control thread safe

Question: I have an Observable collection object whose value I am updating from my code. This collection is bound two way to a data grid. Now, is this collection thread safe - that is if I try to modify the value of the collection from the code and at the same time the user tries to modify it(as a result of editing the data grid), would the program throw an exception? If yes, can you please explain how to avoid this?
Thanks...
Answer: This looks like a duplicate here, and here but the short answer is that you're safe if you're modifying a property.
As you're working with a collection there's a bit more you need to do if you're trying to modify an ObservableCollection on multiple threads and not just the UI thread. This has been covered a lot, and you can check out at either this link or this one
However if you're doing your modifications within the UI thread, you are safe as this is what the ObservableCollection is intended for. The events will be created and handled on the UI theread as long as you are properly marshaling via Dispatcher.BeginInvoke().
Comment: I am using the Dispatcher.BeginInvoke method to update the observable collection in the UI thread. So is it like - when a user edits the data grid, a lock is obtained on the Observable collection and the method I am calling using Dispatcher.BeginInvoke will wait for it to complete?
Comment: @Manoj as your marshaling your work onto the UI thread via Dispatcher.BeginInvoke you are fine. Problems **do** arise when you try to change the collection on a different thread, but I don't believe that's what you're doing. I am looking to confirm my understanding, but as far as I understand it, it's not a "lock" per se, but rather you are creating a NotifyCollectionChanged event that is added to a queue of such events that will read by the UI components that are bound, and will thus update themselves with the new contents of the collection
Comment: @Manoj this convinces me that I am not crazy: "_When an ObservableCollection is modified, it raises an event. Events are handled synchronously. Event handlers respond on the same thread as the modification. The handler completes before the Add or Remove method returns. This means that you can't modify an ObservableCollection in a background thread._" which comes from [this link](http://updatecontrols.net/doc/tips/common_mistakes_observablecollection) about three-quarters of the way down the page.


Central limit theorem for sample medians

Question: If I calculate the median of a sufficiently large number of observations drawn from the same distribution, does the central limit theorem state that the distribution of medians will approximate a normal distribution? My understanding is that this is true with the means of a large number of samples, but is it also true with medians?
If not, what is the underlying distribution of sample medians?
Comment: You need some regularity conditions so that the median will have a normal distribution under rescaling in the limit. To see what can go wrong, consider any distribution over a finite number of points, say, $X$ uniform on $\{-1,0,1\}$.
Comment: Regarding regularity conditions: If the underlying distribution has a density that is differentiable at the (true) median, then the sample median will have an asymptotic normal distribution with a variance that depends on said derivative. This holds more generally for arbitrary quantiles.
Comment: @cardinal I believe you need additional conditions: when the density is second differentiable, is equal to zero at the median, and has zero first derivative there, then the asymptotic distribution of the sample median will be bimodal.
Comment: @whuber: Yes, because the density (not its derivative as I inadvertently stated earlier) enters into the variance as a reciprocal, the value of the density at that point must not be zero. Apologies for dropping that condition!
Comment: Elementary counterexamples can be created using any distribution that assigns probability of $1/2$ to an interval $(-\infty,\mu]$ and probability $1/2$ to $[\mu+\delta,\infty)$ where $\delta\gt 0,$ such as a Bernoulli$(1/2)$ ($\mu=0,\delta=1$). Sample medians will be less than or equal to $\mu$ as often as they are greater than or equal to $\mu+\delta$. The chance that the median is not in $(\mu,\mu+\delta)$ approaches $0$ for large samples, effectively leaving a "gap" in $(\mu,\mu+\delta)$ in the limiting distribution--which obviously then will be non-normal, no matter how it is standardized.
Comment: Example for [median of Cauchy sample](https://stats.stackexchange.com/questions/487518/clt-for-medians-for-distributions-without-means/487542#487542).
Comment: Is the Sample Median an unbiased estimator of the population median? "Clearly so for Normal distributions, but not clear if true for others; specially non-symmetric ones.
Answer: The key idea is that the sampling distribution of the median is simple to express in terms of the distribution function but more complicated to express in terms of the median value.  Once we understand how the distribution function can re-express values as probabilities and back again, it is easy to derive the exact sampling distribution of the median.  A little analysis of the behavior of the distribution function near its median is needed to show that this is asymptotically Normal.
(The same analysis works for the sampling distribution of any quantile, not just the median.)
I will make no attempt to be rigorous in this exposition, but I do carry out it out in steps that are readily justified in a rigorous manner if you have a mind to do that.

Intuition
These are snapshots of a box containing 70 atoms of a hot atomic gas:

In each image I have found a location, shown as a red vertical line, that splits the atoms into two equal groups between the left (drawn as black dots) and right (white dots). This a median of the positions: 35 of the atoms lie to its left and 35 to its right.  The medians change because the atoms are moving randomly around the box.
We are interested in the distribution of this middle position.  Such a question is answered by reversing my procedure: let's first draw a vertical line somewhere, say at location $x$.  What is the chance that half the atoms will be to the left of $x$ and half to its right?  The atoms at the left individually had chances of $x$ to be at the left.  The atoms at the right individually had chances of $1-x$ to be at the right.  Assuming their positions are statistically independent, the chances multiply, giving $x^{35}(1-x)^{35}$ for the chance of this particular configuration.  An equivalent configuration could be attained for a different split of the $70$ atoms into two $35$-element pieces.  Adding these numbers for all possible such splits gives a chance of
$${\Pr}(x\text{ is a median}) = C x^{n/2} (1-x)^{n/2}$$
where $n$ is the total number of atoms and $C$ is proportional to the number of splits of $n$ atoms into two equal subgroups.
This formula identifies the distribution of the median as a Beta$(n/2+1, n/2+1)$ distribution.
Now consider a box with a more complicated shape:

Once again the medians vary.  Because the box is low near the center, there isn't much of its volume there: a small change in the volume occupied by the left half of the atoms (the black ones once again)--or, we might as well admit, the area to the left as shown in these figures--corresponds to a relatively large change in the horizontal position of the median.  In fact, because the area subtended by a small horizontal section of the box is proportional to the height there, the changes in the medians are divided by the box's height.  This causes the median to be more variable for this box than for the square box, because this one is so much lower in the middle.
In short, when we measure the position of the median in terms of area (to the left and right), the original analysis (for a square box) stands unchanged.  The shape of the box only complicates the distribution if we insist on measuring the median in terms of its horizontal position.  When we do so, the relationship between the area and position representation is inversely proportional to the height of the box.
There is more to learn from these pictures.  It is clear that when few atoms are in (either) box, there is a greater chance that half of them could accidentally wind up clustered far to either side.  As the number of atoms grows, the potential for such an extreme imbalance decreases.  To track this, I took "movies"--a long series of 5000 frames--for the curved box filled with $3$, then with $15$, then $75$, and finally with $375$ atoms, and noted the medians.  Here are histograms of the median positions:

Clearly, for a sufficiently large number of atoms, the distribution of their median position begins to look bell-shaped and grows narrower: that looks like a Central Limit Theorem result, doesn't it?

Quantitative Results
The "box," of course, depicts the probability density of some distribution: its top is the graph of the density function (PDF).  Thus areas represent probabilities.  Placing $n$ points randomly and independently within a box and observing their horizontal positions is one way to draw a sample from the distribution.  (This is the idea behind rejection sampling.)
The next figure connects these ideas.

This looks complicated, but it's really quite simple.  There are four related plots here:

The top plot shows the PDF of a distribution along with one random sample of size $n$.  Values greater than the median are shown as white dots; values less than the median as black dots.  It does not need a vertical scale because we know the total area is unity.

The middle plot is the cumulative distribution function for the same distribution: it uses height to denote probability.  It shares its horizontal axis with the first plot.  Its vertical axis must go from $0$ to $1$ because it represents probabilities.

The left plot is meant to be read sideways: it is the PDF of the Beta$(n/2+1, n/2+1)$ distribution.  It shows how the median in the box will vary, when the median is measured in terms of areas to the left and right of the middle (rather than measured by its horizontal position).  I have drawn $16$ random points from this PDF, as shown, and connected them with horizontal dashed lines to the corresponding locations on the original CDF: this is how volumes (measured at the left) are converted to positions (measured across the top, center, and bottom graphics).  One of these points actually corresponds to the median shown in the top plot; I have drawn a solid vertical line to show that.

The bottom plot is the sampling density of the median, as measured by its horizontal position.  It is obtained by converting area (in the left plot) to position.  The conversion formula is given by the inverse of the original CDF: this is simply the definition of the inverse CDF!  (In other words, the CDF converts position into area to the left; the inverse CDF converts back from area to position.)  I have plotted vertical dashed lines showing how the random points from the left plot are converted into random points within the bottom plot.  This process of reading across and then down tells us how to go from area to position.

Let $F$ be the CDF of the original distribution (middle plot) and $G$ the CDF of the Beta distribution.  To find the chance that the median lies to the left of some position $x$, first use $F$ to obtain the area to the left of $x$ in the box: this is $F(x)$ itself.  The Beta distribution at the left tells us the chance that half the atoms will lie within this volume, giving $G(F(x))$: this is the CDF of the median position.  To find its PDF (as shown in the bottom plot), take the derivative:
$$\frac{d}{dx}G(F(x)) = G'(F(x))F'(x) = g(F(x))f(x)$$
where $f$ is the PDF (top plot) and $g$ is the Beta PDF (left plot).
This is an exact formula for the distribution of the median for any continuous distribution.  (With some care in interpretation it can be applied to any distribution whatsoever, whether continuous or not.)

Asymptotic Results
When $n$ is very large and $F$ does not have a jump at its median, the sample median must vary closely around the true median $\mu$ of the distribution.  Also assuming the PDF $f$ is continuous near $\mu$, $f(x)$ in the preceding formula will not change much from its value at $\mu,$ given by $f(\mu).$  Moreover, $F$ will not change much from its value there either: to first order,
$$F(x) = F\left(\mu + (x-\mu)\right) \approx F(\mu) + F^\prime(\mu)(x-\mu) = 1/2 + f(\mu)(x-\mu).$$
Thus, with an ever-improving approximation as $n$ grows large,
$$g(F(x))f(x) \approx g\left(1/2 + f(\mu)(x-\mu)\right) f(\mu).$$
That is merely a shift of the location and scale of the Beta distribution.  The rescaling by $f(\mu)$ will divide its variance by $f(\mu)^2$ (which had better be nonzero!).  Incidentally, the variance of Beta$(n/2+1, n/2+1)$ is very close to $n/4$.
This analysis can be viewed as an application of the Delta Method.
Finally, Beta$(n/2+1, n/2+1)$ is approximately Normal for large $n$.  There are many ways to see this; perhaps the simplest is to look at the logarithm of its PDF near $1/2$:
$$\log\left(C(1/2 + x)^{n/2}(1/2-x)^{n/2}\right) = \frac{n}{2}\log\left(1-4x^2\right)  + C' = C'-2nx^2 +O(x^4).$$
(The constants $C$ and $C'$ merely normalize the total area to unity.)  Through third order in $x,$ then, this is the same as the log of the Normal PDF with variance $1/(4n).$  (This argument is made rigorous by using characteristic or cumulant generating functions instead of the log of the PDF.)
Putting this altogether, we conclude that

The distribution of the sample median has variance approximately $1/(4 n f(\mu)^2)$,

and it is approximately Normal for large $n$,

all provided the PDF $f$ is continuous and nonzero at the median $\mu.$
Comment: 'Tis a thing of beauty.
Comment: @Engr And behold--you had commented on it over six years ago!  After so much time and so many posts, we easily forget so much... .
Comment: @Tim I do not understand the relevance of the reference to a prior, but I do appreciate you pointing out that the correct *name* of the Beta distribution identified in the "Intuition" section is Beta$(n/2+1,n/2+1)$.  I'll fix that wherever it occurs (which is in several places in the discussion).
Comment: I was re-reading this and thought to myself "this looks like a whuber answer".  Lo and behold it was a whuber answer.
Comment: I like that 4th figure.  Did you make it using R?
Comment: @Engr I probably could have made one like it in `R`, perhaps using `layout`, but in fact it was done with *Mathematica* 9.
Comment: @whuber isn't it Beta(n/2+1, n/2+1) under Beta(1,1) prior? See e.g. https://www.ine.pt/revstat/pdf/rs080204.pdf
Comment: I think I have my new favourite statistical graph. The fourth figure is truly amazing.
Comment: This is such a beautiful explanation. I think it deserves a short article to American Statistician.  Would you consider that?
Comment: @user67724 Thank you for that comment.  I have had poor luck with TAS.  I submitted an enhanced version of https://stats.stackexchange.com/a/18200/919 a couple years ago and it was rejected, without substantial review, as being too trivial.  I remain open to suggestions and encouragement, though ;-).
Answer: If you work in terms of indicator variables (i.e. $Z_i = 1$ if $X_i \leq x$ and $0$ otherwise), you can directly apply the Central limit theorem to a mean of $Z$'s, and by using the Delta method, turn that into an asymptotic normal distribution for $F_X^{-1}(\bar{Z})$, which in turn means that you get asymptotic normality for fixed quantiles of $X$.
So not just the median, but quartiles, 90th percentiles, ... etc.
Loosely, if we're talking about the $q$th  sample quantile in sufficiently large samples, we get that it will approximately have a normal distribution with mean the $q$th population quantile $x_q$ and variance $q(1-q)/(nf_X(x_q)^2)$.
Hence for the median ($q = 1/2$), the variance in sufficiently large samples will be approximately $1/(4nf_X(\tilde{\mu})^2)$.
You need all the conditions along the way to hold, of course, so it doesn't work in all situations, but for continuous distributions where the density at the population quantile is positive and differentiable, etc, ...
Further, it doesn't hold for extreme quantiles, because the CLT doesn't kick in there (the average of Z's won't be asymptotically normal). You need different theory for extreme values.

Edit: whuber's critique is correct; this would work if $x$ were a population median rather than a sample median. The argument needs to be modified to actually work properly.
Comment: I think one logical piece of this explanation may be missing: how exactly does one use indicators to obtain *sample* medians? I can see how when $x$ is the *underlying* median, the indicator $X_i\le x$ will work: but this indicator does *not* coincide with the sample median or any function of it.
Comment: How do you go from asymptotic normal distributions for $F^{−1}_X (\overline{Z})$ to get asymptotic normality for fixed quantiles of X? Edit: I got it, that $\overline{Z}$ becomes a percent value 0-100% thus quantile values are asymptotically normal
Answer: @EngrStudent illuminating answer tells us that we should expect different results when the distribution is continuous, and when it is discrete (the "red" graphs, where the asymptotic distribution of the sample median fails spectacularly to look like normal, correspond to the distributions Binomial(3), Geometric(11), Hypergeometric(12), Negative Binomial(14), Poisson(18), Discrete Uniform(22).
And indeed this is the case. When the distribution is discrete, things get complicated. I will provide the proof for the Absolutely Continuous Case, essentially doing no more than detailing the answer already given by @Glen_b, and then I will discuss a bit what happens when the distribution is discrete, providing also a recent reference for anyone interested in diving in.
ABSOLUTELY CONTINUOUS DISTRIBUTION
Consider a collection of i.i.d. absolutely continuous random variables $\{X_1,...X_n\}$ with distribution function (cdf) $F_X(x) = P(X_i\le x)$ and density function $F'_X(x)=f_X(x)$. Define $Z_i\equiv I\{X_i\le x\}$ where $I\{\}$ is the indicator function. Therefore $Z_i$ is a Bernoulli r.v., with
$$E(Z_i) =  E\left(I\{X_i\le x\}\right) = P(X_i\le x)=F_X(x),\;\; \text{Var}(Z_i) = F_X(x)[1-F_X(x)],\;\; \forall i$$
Let $Y_n(x)$ be the sample mean of these i.i.d. Bernoullis, defined for fixed $x$ as
$$Y_n(x) =  \frac 1n\sum_{i=1}^nZ_i$$
which means that
$$E[Y_n(x)] = F_X(x),\;\; \text{Var}(Y_n(x)) = (1/n)F_X(x)[1-F_X(x)]$$
The Central Limit Theorem applies and we have
$$\sqrt n\Big(Y_n(x) - F_X(x)\Big) \rightarrow_d \mathbb N\left(0,F_X(x)[1-F_X(x)]\right) $$
Note that $Y_n(x) = \hat F_n(x)$ i.e. non else than the empirical distribution function.
By applying the "Delta Method" we have that for a continuous and differentiable function $g(t)$ with non-zero derivative $g'(t)$ at the point of interest, we obtain
$$\sqrt n\Big(g[\hat F_n(x)] - g[F_X(x)]\Big) \rightarrow_d \mathbb N\left(0,F_X(x)[1-F_X(x)]\cdot\left(g'[F_X(x)]\right)^2\right) $$
Now, choose $g(t) \equiv F^{-1}_X(t),\;\; t\in (0,1)$ where $^{-1}$ denotes the inverse function. This is a continuous and differentiable function (since  $F_X(x)$ is), and by the Inverse Function Theorem we have
$$g'(t)=\frac {d}{dt}F^{-1}_X(t) = \frac 1{f_x\left(F^{-1}_X(t)\right)}$$
Inserting these results on $g$ in the delta-method derived asymptotic result we have
$$\sqrt n\Big(F^{-1}_X(\hat F_n(x)) - F^{-1}_X(F_X(x))\Big) \rightarrow_d \mathbb N\left(0,\frac {F_X(x)[1-F_X(x)]}{\left[f_x\left(F^{-1}_X(F_X(x))\right)\right]^2} \right) $$
and simplifying,
$$\sqrt n\Big(F^{-1}_X(\hat F_n(x)) - x\Big) \rightarrow_d \mathbb N\left(0,\frac {F_X(x)[1-F_X(x)]}{\left[f_x(x)\right]^2} \right) $$
.. for any fixed $x$. Now set $x=m$, the (true) median of the population. Then we have $F_X(m) = 1/2$ and the above general result becomes, for our case of interest,
$$\sqrt n\Big(F^{-1}_X(\hat F_n(m)) - m\Big) \rightarrow_d \mathbb N\left(0,\frac {1}{\left[2f_x(m)\right]^2} \right) $$
But $F^{-1}_X(\hat F_n(m))$ converges to the sample median $\hat m$. This is because
$$F^{-1}_X(\hat F_n(m)) = \inf\{x : F_X(x) \geq \hat F_n(m)\} = \inf\{x : F_X(x) \geq \frac 1n \sum_{i=1}^n I\{X_i\leq m\}\}$$
The right-hand side of the inequality converges to $1/2$ and the smallest $x$ for which eventually $F_X \geq 1/2$, is the sample median.
So we obtain
$$\sqrt n\Big(\hat m - m\Big) \rightarrow_d \mathbb N\left(0,\frac {1}{\left[2f_x(m)\right]^2} \right) $$
which is the Central Limit Theorem for the sample median for absolutely continuous distributions.
DISCRETE DISTRIBUTIONS
When the distribution is discrete (or when the sample contains ties) it has been argued that the "classical" definition of sample quantiles, and hence of the median also, may be misleading in the first place, as the theoretical concept to be used in order to measure what one attempts to measure by quantiles.
In any case it has been simulated that under this classical  definition (the one we all know), the asymptotic distribution of the sample median is non-normal and a discrete distribution.
An alternative definition of sample quantiles is by using the concept of the "mid-distribution" function, which is defined as
$$F_{mid}(x) = P(X\le x) - \frac 12P(X=x)$$
The definition of sample quantiles through the concept of mid-distribution function can be seen as a generalization that can cover as special cases the continuous distributions, but also, the not-so-continuous ones too.
For the case of discrete distributions, among other results, it has been found that the sample median as defined through this concept has an asymptotically normal distribution with an ...elaborate looking variance.
Most of these are recent results. The reference is Ma, Y., Genton, M. G., & Parzen, E. (2011). Asymptotic properties of sample quantiles of discrete distributions. Annals of the Institute of Statistical Mathematics, 63(2), 227-243., where one can find a discussion and links to the older relevant literature.
Comment: (+1) For the article. This is an excellent answer.
Comment: Can you please explain why $F^{-1}_X(\hat F_n(m))$ converges to the sample median $\hat m$?
Comment: @kasa I elaborated a bit on the matter.
Comment: I know that $\hat F_n(m) \to F_X(m) $ in distribution, but I cannot see how sample median $\hat m$ is equal to $F^{-1}_X(\hat F_n(m))$
Comment: I am sorry to keep bringing this up again: But the smallest $x$ for which eventually $F_X(x) ≥ 1/2 $, is the population median, not the sample median, isn't it?
Comment: @AlecosPapadopoulos I accept that your proof is elegant and intuitive but I have a few claims. $F^{-1}_X(\hat F_n(m))$ is the statistic that has a normal distribution around the mean. Approximating $F^{-1}_X(\hat F_n(m))$ by sample median can distort the variance and other properties of the normal distribution. Probably, this is one of the reasons why delta method is not widely used approach in proving the distribution of  sample median. For e.g: https://goo.gl/bKXQte
Nevertheless, thank you very much for your time and effort in clarifying my doubts.
Comment: @kasa The population median is the smallest $x$ for which $F_X(x) \geq 1/2$ _always_. And the sample median is the statistic that converges to it.
Answer: Yes it is, and not just for the median, but for any sample quantile. Copying from  this paper,  written by T.S. Ferguson, a professor at UCLA (his page is here), which interestingly deals with the joint distribution of sample mean and sample quantiles, we have:
Let $X_1, . . . ,X_n$ be i.i.d. with distribution function $F(x)$, density $f(x)$, mean $\mu$ and finite variance $\sigma^2$. Let $0 < p < 1$ and let $x_p$ denote the $p$-th
quantile of $F$, so that $F(x_p) = p$. Assume that the density $f(x)$ is continuous and positive at $x_p$. Let $Y_n = X_{(n:\lceil np\rceil)}$ denote the
sample $p$-th quantile. Then
$$\sqrt n(Y_n − x_p) \xrightarrow{d} N(0, p(1 − p)/(f(x_p))^2)$$
For $p=1/2 \Rightarrow x_p=m$ (median), and you have the CLT for medians,
$$\sqrt n(Y_n − m) \xrightarrow{d} N\left(0, [2f(m)]^{-2}\right)$$
Comment: Nice. It is worth mentioning that the variance of the sample median is not as easy to estimate as the one for the sample mean.
Comment: @EngrStudent  The system allows it, it just asks you to verify that you want  indeed to add a second answer.
Comment: @Alecos - how did you get two answers for this question?
Answer: I like the analytic answer given by Glen_b.  It is a good answer.
It needs a picture.  I like pictures.
Here are areas of elasticity in an answer to the question:

There are lots of distributions in the world.  Mileage is likely to vary.
Sufficient has different meanings.  For a counter-example to a theory, sometimes a single counter-example is required for "sufficient" to be met.  For demonstration of low defect rates using binomial uncertainty hundreds or thousands of samples may be required.

For a standard normal I used the following MatLab code:
<code>mysamples=1000;

loops=10000;

y1=median(normrnd(0,1,mysamples,loops));

cdfplot(y1)
</code>
and I got the following plot as an output:

So why not do this for the other 22 or so "built-in" distributions, except using prob-plots (where straight line means very normal-like)?

And here is the source code for it:
<code>mysamples=1000;

loops=600;

y=zeros(loops,23);

y(:,1)=median(random('Normal', 0,1,mysamples,loops));

y(:,2)=median(random('beta', 5,0.2,mysamples,loops));
y(:,3)=median(random('bino', 10,0.5,mysamples,loops));
y(:,4)=median(random('chi2', 10,mysamples,loops));
y(:,5)=median(random('exp', 700,mysamples,loops));

y(:,6)=median(random('ev', 700,mysamples,loops));
y(:,7)=median(random('f', 5,3,mysamples,loops));
y(:,8)=median(random('gam', 10,5,mysamples,loops));
y(:,9)=median(random('gev', 0.24, 1.17, 5.8,mysamples,loops));
y(:,10)=median(random('gp', 0.12, 0.81,mysamples,loops));

y(:,11)=median(random('geo', 0.03,mysamples,loops));
y(:,12)=median(random('hyge', 1000,50,20,mysamples,loops));
y(:,13)=median(random('logn', log(20000),1.0,mysamples,loops));
y(:,14)=median(random('nbin', 2,0.11,mysamples,loops));
y(:,15)=median(random('ncf', 5,20,10,mysamples,loops));

y(:,16)=median(random('nct', 10,1,mysamples,loops));
y(:,17)=median(random('ncx2', 4,2,mysamples,loops));
y(:,18)=median(random('poiss', 5,mysamples,loops));
y(:,19)=median(random('rayl', 0.5,mysamples,loops));
y(:,20)=median(random('t', 5,mysamples,loops));

y(:,21)=median(random('unif',0,1,mysamples,loops));
y(:,22)=median(random('unid', 5,mysamples,loops));
y(:,23)=median(random('wbl', 0.5,2,mysamples,loops));

figure(1); clf
hold on

for i=2:23
    subplot(4,6,i-1)

    probplot(y(:,i))
    title(['Probplot of ' num2str(i)])
    axis tight

    if not(isempty(find(i==[3,11,12,14,18,22])))
        set(gca,'Color','r')
    end

end
</code>
When I see the analytic proof I might think "in theory they all might fit" but when I try it out then I can temper that with "there are a number of ways this doesn't work so well, often involving discrete or highly constrained values" and this might make me want to be more careful about applying the theory to anything that costs money.
Good luck.
Comment: @SeF - some of the other answers are very illuminating here.
Comment: Am I wrong or the distribution for which the median is not normally distributed are discrete?


What are the differences between Ash and Alder wood for electric guitar?

Question: Ever since the 50's both Ash wood and Alder wood have remained the most popular choice for building electric guitars.
What are the major differences between these two woods for an electric guitar? (Tone, weight, cost etc).
Comment: Welcome! There are a few related questions: https://music.stackexchange.com/q/24282, https://music.stackexchange.com/q/30488, https://music.stackexchange.com/q/118392, https://music.stackexchange.com/q/66990
Answer: In case there are readers of this answer who don't already know, I want to clarify that ash and alder are the two most common woods that have been used since the 1950s for the bodies of Fender and Fender-style guitars, such as the Telecaster, Stratocaster, and copies of those two types of guitars. Ash and alder are rarely (maybe never - I've never heard of examples) used for necks or fingerboards, and also not generally used for Gibson style solid body electrics like the Les Paul or SG.
The point is, my answer is going to focus on Fender and Fender-style guitars with two or three single coil pickups with ash or alder bodies.
Tone
Important edit:
In this video, a diligent tester of the sources of electric guitar tone provides very compelling evidence that no type or amount of wood has any significant effect on the tone of an electric guitar:

Preliminary disclaimer: Some believe that the tonal effects of the choice of body wood in solid body electric guitars is negligible or non-existent. I strongly believe I hear a difference, and I'm not the only one, although it's hard to completely rule out confirmation bias. Even those who hear a difference between tone woods usually agree it's usually not a huge difference. For the type of guitars in question (explained above), the tonal difference is very minor, in my opinion. That said, every difference makes a difference to most musicians.
EVP of Fender Products, Justin Norvell said about ash vs alder tone:

I would say ash has a great sound, especially when you are jamming at home by yourself. When you are playing with a band and need to cut through, the alder has a better peak and allows you to claim more space in the song. But there's a warmth to ash, that's what people love about it.

source
My take is that ash has a more complex, interesting tone, while alder has a more reliable, predictable, focused tone. Another way I think about it is ash sounds more "rebellious" and alder sounds more "professional".
Weight
The ash that has been most used to date for guitars is often called "swamp ash", which means it's from a part of an ash tree that has been submerged in flood waters and then harvested when the flood recedes. I don't know the mechanism but apparently this method of sourcing ash yields wood that is less dense than harvesting from trees that have not been flooded.
Typical ash wood is denser (and therefore heavier for the same body) than alder, but swamp ash as sourced above has a density very similar to alder. As all wood varies, bodies for Fender style guitars made from alder can be heavier or lighter than identical bodies made from ash. Usually the difference is less than a couple pounds either way.
Appearance
You didn't mention this but it is often a factor for many guitar buyers. Swamp ash has a more apparent, swirling grain compared to alder. You will usually see ash bodies having translucent or burst finishes, while alder bodies usually have solid color finishes, and this is because of the difference in grain. Most people agree the visible grain on ash is more attractive than alder, but of course it's a matter of taste.
Cost
Up until recently, there hasn't been a huge difference in price between ash and alder bodies based solely on the wood. Translucent finishes and bursts are more expensive to apply than solid colors, so a guitar made from ash might be 5% - 10% more expensive than the same model in alder simply because of the different finish options on the ash model - offered because of the attractive grain of the ash as mentioned above.
However, as this article details, a borer beetle that destroys ash and climate change causing longer flood duration are combining to make ash much more difficult to source. According to the article, swamp ash as has been sourced and used for guitars may become essentially unobtainable in the near future. This means that Fender (and likely other builders will do the same) will be saving their ash for signature and custom shop models. The resale value of existing ash guitars will likely increase as new models made from ash start to disappear. Ash is not necessarily more expensive at this time, but there's a chance it soon will be, and prices may have already changed.
Note: Currently, the price difference between otherwise identical G&L ASAT Classic Deluxe Bluesboy guitars (Telecaster style) with swamp ash & translucent finish vs alder with solid finish is only $75, which is less than a 4% price difference. There are also two Deluxe ASAT Classic models that are the same price and only differ in ash vs alder body wood (as far as I can tell). Reference: https://www.sweetwater.com/store/search?s=g%26l+guitars+asat&sb=high2low#search-header
Summary
If you're looking for an affordable, reliable, and durable guitar, a Fender or Fender-style guitar with an alder body is an excellent choice. If you're looking for the best guitar possible for your tastes and playing style, you should definitely get to some kind of retailer and play various options to see what really speaks to you. Whether the guitar is ash or alder will almost certainly be secondary to how it feels and responds in your hands. There are excellent, top-notch guitars made from ash and alder.
Comment: Imo the type of wood will affect the sound mostly in different behavior of dampening, which also strongly depends on the construction of the guitar (e.g. neck through will mostly behave like sycamore/maple). Very importantly this effect is by far dominated by aspects like the pickup position and the pickup height.
Comment: Excellent answer! +1. Question - if a guitar has a solid finish, how does one tell if it's ash or alder? I've long thought that if the grain pattern wasn't too clever, the body would go straight into the paint shop regardless, thus a not-so-good ash *could* be solid-painted, making the answer difficult to determine.
Comment: @Tim Same way one would tell what any of the woods are on any guitar with a solid finish.
Comment: @ToddWilcox - you mean scrape some paint off, or saw it in half..?
Comment: @Tim I've never needed to know the wood on a guitar in a situation where that information wasn't readily available. So I guess I have no idea how to answer your question. Maybe it's a good question to ask as a question and not as a comment.
Answer: My understanding is that Leo Fender used Alder as it was easily available in the 1950s. There may indeed be a small tonal difference, but I doubt its so extreme that as  Justin Norvell is quoted as saying above, it "lets you claim more space in the song"; a simple tweak of your amp settings would do just as much.
Ash does look better in a  clear or sunburst finish but my $0.02 its that that is the only real-world difference you'd notice . Swamp Ash is a generic term for Ash that grows near water. It varies wildly in Janka hardness (White Ash is 1320, Black Ash 850) and so cannot be reliably stated to give anything consistently aginst a dry-grown wood like Alder. The best you could say, in my humble opinion, is that this specific piece of ash is very resonant and might make a good sounding instrument. That kind of piece by piece-by-piece anaysis doesnt lend itself to high volume manufacture, though you might get that from a luthier.


How did n2 / n lg n = n / n lg n?

Question: I recently stumbled on this equation

so how did $n^2 / n \lg n  = n / n \lg n$ ?
Comment: can you use $$\LaTeX$$ please?
Comment: divide by $n$ the numerator and denominator
Comment: yes! just simplification!
Comment: @Dr.SonnhardGraubner Hi sorry. I don't know how yet do you have any reference for latex?
Comment: @ArnaldoNascimento why divide both sides n? for simplification?
Comment: Here is the [$\LaTeX$ guide](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Read your image closer.
$\dfrac{n^2}{n\lg n}$ did not become $\dfrac{n}{n\lg n}$. It became $\dfrac{n}{\lg n}$, by dividing both numerator and denominator by $n$.

How did n2 / n lg n = n / n lg n?


Bind to command from within a treeview

Question: I'm building a treeview with HierarchicalDataTemplates and would like to bind the nodes to a command from my MainViewModel. I guess there is some conflict with the scopes, since the binding works if I e.g. use a button and define it outside of the treeview. If I define it inside, however, it does not work.
I've searched through Stackoverflow and found several solutions but none that worked for me. Jehof e.g. suggested here to use
<Button Command="{Binding DataContext.Command,
    RelativeSource={RelativeSource AncestorLevel=2, AncestorType=TreeViewItem}}"
    CommandParameter="{Binding}" />

but that did not work. Thank you for any suggestions!
<TreeView ItemsSource="{Binding _questions}" Grid.Row="0" Margin="10" BorderThickness="1">
<TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:Question}" ItemsSource="{Binding Converter={StaticResource QuestionConverter}}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="{x:Type local:MainOption}" ItemsSource="{Binding MainOptions}">
        <StackPanel Orientation="Horizontal">
    <CheckBox Content="{Binding Path=Name}" />

/////////////////////////////////////
    <Button Command="{Binding ThisIsMyCommand}" Content="Click Me"/>
/////////////////////////////////////

</StackPanel>
    </HierarchicalDataTemplate>
</TreeView.Resources>

Answer: Is your TreeView-Control inside a Window or UserControl?
If you are inside a Window:
<Button Command="{Binding DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" CommandParameter="{Binding}" />

and for UserControl
<Button Command="{Binding DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding}" />

Comment: Thank you very much! It's inside a window - worked like a charm!

Bind to command from within a treeview


How to estimate standard error of prediction error in Table 3.3 of Hastie el al (2017)?

Question: On page 63 Table 3.3. of "The Elements of Statistical Learning" by Hastie el al. (2017) 12th print. It gives the summary results of different regression results on the cancer data. However I don't understand how the std err in the last line is calculated (esp. for the LS column).
The authors on page 61 have the following explanations: "The last two lines of the table give the average prediction error (and its estimated standard error) over the test set."
Still could anyone please help me understand how we get the std err in the last line especially the LS column? Thanks!
Answer: Looks like to me that a 10-fold cross validation was used where the dataset was split into 10 equal parts and 9 parts was used to train the model and test on the last part. Repeating this for each of the 10 parts would produce 10 sets of prediction error.
The "Test error" in the table refers to the average of the 10 cross validation errors which can be calculated this way:
For each tuning parameter $\theta$ in the model,
$CV(\theta) = \frac{1}{10} \sum\limits_{k=1}^{10} CV_k(\theta)$
where $CV_k(\theta) = \frac{1}{|F_k|} \sum\limits_{i\in F_k} (y_i -\hat{f_\theta} ^{-k}(x_i))^2 $
The "Standard Error" refers to the error made on the cross-validation estimate which can be obtained by first calculating the SD of the 10 CV errors, and estimating the SE by correcting by a factor:
$SD(\theta)=\sqrt{var(CV_1 (\theta),CV_2(\theta),...,CV_{10}(\theta))}$
$SE(\theta) = \frac{SD(\theta)}{\sqrt{10}}$
Note that this can be generalised to a $K$-fold CV by replace $10$ by $K$ in the formula. Hope this helps!
Comment: Really appreciate your answer. However, I am pretty sure that the Test Error is calculated using the "test" set, not using the cross validation on the "training" set. According to http://waxworksmath.com/Authors/G_M/Hastie/WriteUp/weatherwax_epstein_hastie_solutions_manual.pdf (page 16) there seems to be a formula to derive the std_err(variance_estimate) based on the sample size and variance_estimate. But I cannot get the same answer even using page 16's formula...
Comment: Yes, what I meant was the model was trained on the "training" set and then tested on the "test" set to obtain errors.
Comment: @Hiromi, this formula seems to assume that the $CV_k(\theta)$'s are fairly independent. What is the formula if the $CV_k(\theta)$'s are highly correlated as in the case of leave-one-out CV estimator?


Confusion with exact sequences

Question: Consider the sequence:
$$0\rightarrow \mathbb{Z} \xrightarrow{f} \mathbb{C}\xrightarrow{g}\mathbb{C}\setminus\{0\}\rightarrow 0$$
Now this sequence is exact in the sense that $\text{Im}\space f=\mathbb{Z}$ and $\text{ker} \space g= \mathbb{Z}$ and thus they are equal and by the definition of exact sequences, this sequence is exact. However I kind of had to guess that $\text{ker}\space g= \mathbb{Z}$ just so the condition holds, and I am not quite sure why the $\text{ker}\space g$ is equal to $\mathbb{Z},$ because from my understanding of kernel, it is all the set of elements of $\mathbb{C}$ such that $g(c\in \mathbb{C})=\text{id}_{\mathbb{C}\setminus\{0\}}.$ But I do not see why the set of integers if the kernel for the homomorphism $g$?
Could anyone please explain why this is the case?
Edited: $f$ is the inclusion map taking some $z\in \mathbb{Z}$ to itself $z\in \mathbb{C}$ and $g$ is the map taking some $c\in \mathbb{C}$ to $e^{2\pi i c} \in \mathbb{C}\setminus \{0\}$
Comment: What are $f$ and $g$ in your question? I think they need to be specified.
Comment: If $g$ is the exponential map, its kernel is $2\pi i\Bbb Z$ which is isomorphic to $\Bbb Z$ as a group.
Comment: If, on the other hand, $g(z)=e^{2\pi iz}$, then its kernel is literally $\mathbb Z$, not just up to isomorphism.  But the same holds if $g(z)=e^{-2\pi iz}$.
Comment: @Andreas Blass This is now my reasoning for why kernel of $g$ is infact the whole $\mathbb{Z}$.
Reasoning: With the defined function of $g,$ since the identity can no longer be $0$, it is now $1$, and the only value of the function $g$ where it takes the value $1$ is if all the values in $\mathbb{C}$ is infact $\mathbb{Z}$ simple because of the exponential function, the multiples of $2\pi$ continuously gives the value of $1$. is this correct?
Answer:
from my understanding of kernel, it is all the set of elements of $\mathbb{C}$ such that $g(c\in \mathbb{C})=\text{id}_{\mathbb{C}\setminus\{0\}}.$

Correct. What is $\text{id}_{\mathbb{C}\setminus\{0\}}$? (What's the group structure on $\mathbb{C}\setminus\{0\}$?)

$g$ is the map taking some $c\in\mathbb{C}$ to $e^{2\pi i c} \in \mathbb{C}\setminus \{0\}$

When is $e^{2\pi i c}$ equal to the identity you've just found above?
Comment: I have made my reasoning in the above comments, I would appreciate if you can check if its correct. Thank You.
Comment: I don't think your reasoning above makes much sense. *Why* is the identity 1? Saying "the identity can no longer be 0" is not enough.
Comment: @because the image of $g$, excludes ${0}$, so we cannot take 0 in to consideration.
Comment: I agree with you that the identity can obviously no longer be 0. But why is it 1, and not e.g. pi, or 25, or sqrt(2)?
Comment: I guess because the binary operation defined is multiplication? Hmm I just automatically thought it was 1, now that seems to be a good question. Why is it 1? Can you help me understand why it it the case?
Comment: Correct, the operation defined *is* supposed to be multiplication. (They haven't said that, but you're supposed to know that that's implicitly what they meant.) Can you prove that the identity is 1 from here?
Comment: Then its simply $ e^{2\pi i c} * i = e^{2\pi i c}$ which implies $i =1.$
Comment: Yes. More generally, for *any* $x\in \mathbb{C}\setminus \{0\}$, we have that $xa = x$ implies $a = 1$. So now you know what the identity is - it's 1. So you can solve the equation $e^{2\pi i c} = 1$ for $c\in \mathbb{C}$.

Confusion with exact sequences


Select from drop-down menu

Question: On website there is a drop-down menu "Best Time to Contact" and I click on it but I can't choose from the d-d menu. Suggestions?
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome(executable_path="D:\ChromeDriverExtracted\chromedriver")
driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407")

select = Select(driver.find_element_by_id("RESULT_RadioButton-9").click())
select.select_by_visible_text("Morning").click()

Answer: I ran the below code
driver.maximize_window()
wait = WebDriverWait(driver, 30)
select = Select(wait.until(EC.visibility_of_element_located((By.ID, "RESULT_RadioButton-9"))))
select.select_by_visible_text('Evening')

Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

and it did the trick. This is with explicit waits, which is recommended in Selenium automation.
You should not use .click() here
select = Select(driver.find_element_by_id("RESULT_RadioButton-9").click())

Also, I tested your code without .click(), it works as well.
select = Select(driver.find_element_by_id("RESULT_RadioButton-9"))
select.select_by_visible_text("Morning")

Comment: Yea I know, but need to wait a couple of minutes. Then it will not be a problem :)
Comment: You were very close, you had extra `.click()` with you.
Answer: This worked for me
driver.find_element(By.CSS_SELECTOR, "#RESULT_RadioButton-9 > option:nth-child(2)").click()

Select from drop-down menu


Alter statement Conflict with foreign key, but ID exisits in both table

Question: I've 2 tables, here I'm trying to insert a FK relationship. But, I'm getting errors when I try to alter the table to create an FK relationship please help...  I have club ID in both tables, I commented below, but I am not sure why I'm still getting the Constraint error.
What is causing the constraint error?
CREATE TABLE [dbo].[Clubs](
[ClubID] [int] IDENTITY(1,1) NOT NULL,  // ClubID is here
[Name] [nvarchar](128) NOT NULL,
[Description] [nvarchar](2047) NULL,
[Created] [datetime] NOT NULL,
[Modified] [datetime] NULL,

CONSTRAINT [PK_Clubs] PRIMARY KEY CLUSTERED
(
    [ClubID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[MemberClubs](
[MemberClubID] [int] IDENTITY(1,1) NOT NULL,
[MemberID] [bigint] NOT NULL,
[ClubID] [int] NOT NULL,              //Club ID is here as well
 CONSTRAINT [PK_MemberClubs] PRIMARY KEY CLUSTERED
(
    [MemberClubID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO    SET IDENTITY_INSERT [dbo].[MemberClubs] ON
GO    INSERT [dbo].[MemberClubs] ([MemberClubID], [MemberID], [ClubID]) VALUES (1, 1, 1)
GO    INSERT [dbo].[MemberClubs] ([MemberClubID], [MemberID], [ClubID]) VALUES (2, 2, 1)
GO    INSERT [dbo].[MemberClubs] ([MemberClubID], [MemberID], [ClubID]) VALUES (3, 3, 1)
GO    INSERT [dbo].[MemberClubs] ([MemberClubID], [MemberID], [ClubID]) VALUES (4, 4, 1)
GO    INSERT [dbo].[MemberClubs] ([MemberClubID], [MemberID], [ClubID]) VALUES (5, 5, 1)
GO    SET IDENTITY_INSERT [dbo].[MemberClubs] OFF
GO

// *** The error is over here
ALTER TABLE [dbo].[MemberClubs]  WITH CHECK ADD  CONSTRAINT [FK_MemberClubs_Clubs] FOREIGN KEY([ClubID])
REFERENCES [dbo].[Clubs] ([ClubID])
GO

// $$$ The second FK constraint error is over here
ALTER TABLE [dbo].[MemberClubs] CHECK CONSTRAINT [FK_MemberClubs_Clubs]
GO

ALTER TABLE [dbo].[MemberClubs]  WITH CHECK ADD  CONSTRAINT [FK_MemberClubs_Members] FOREIGN KEY([MemberID])
REFERENCES [dbo].[Members] ([MemberID])
GO

ALTER TABLE [dbo].[MemberClubs] CHECK CONSTRAINT [FK_MemberClubs_Members]
GO

The error:
Msg 547, Level 16, State 0, Line * * * (Above)
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_MemberClubs_Clubs". The conflict occurred in database "newDb", table "dbo.Clubs", column 'ClubID'.

Msg 4917, Level 16, State 0, Line $$$ (Above)
Constraint 'FK_MemberClubs_Clubs' does not exist.

Msg 4916, Level 16, State 0, Line $$$ (Above)
Could not enable or disable the constraint. See previous errors.

Comment: This looks like an intermediate table between Members and Clubs. The standard way to do this is to make a composite key of MemberID and ClubID instead of creating an identity column in this table for the primary key.
Comment: @SeanLange ok that changes the design and impacts some code. But I could possibly do that if it makes it simpler or cleaner. I 'm not sure I understand how a composite key is better that (associative table), i.e. I'm thinking composite key like C#. Unless there is something different in Sql
Comment: The point is that you already have the values needed for a primary key. It is using a simple natural key instead of just making up a magic number. It would be preferred from a design perspective imho.
Answer: You add 5 rows into table MemberClubs referencing Club.ClubId = 1, before then adding a Foreign Key relationship to Clubs.
So in order to maintain referential integrity, you'll need to add a row with ClubId = 1 into Clubs before adding / enabling the foreign key constraint:
SET IDENTITY_INSERT [dbo].[Clubs] ON
INSERT INTO [dbo].[Clubs](ClubId, Name, Description, Created, Modified)
       VALUES (1, 'Foo', 'Bar', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
SET IDENTITY_INSERT [dbo].[Clubs] OFF

Then the foreign key creation succeeds:
ALTER TABLE [dbo].[MemberClubs]  WITH CHECK
    ADD  CONSTRAINT [FK_MemberClubs_Clubs] FOREIGN KEY([ClubID])
REFERENCES [dbo].[Clubs] ([ClubID])
GO

Comment: The odd thing is, if I run the `ALTER TABLE [dbo].[MemberClubs] CHECK CONSTRAINT [FK_MemberClubs_Clubs]
GO

ALTER TABLE [dbo].[MemberClubs]  WITH CHECK ADD  CONSTRAINT [FK_MemberClubs_Members] FOREIGN KEY([MemberID])
REFERENCES [dbo].[Members] ([MemberID])
GO`  after the script errors out-- it works and creates the relationship!!
Answer: If this is not an example and is what you're actually trying to accomplish, one thing I can see just by looking at your scripts is you're attempting to create a FK relationship with table using inconsistent data.
In order to create the constraint, consistent data must exist.  In your posted code, Clubs has no data, so a constraint cannot be successfully created due to MemberClubs having "orphaned" data - e.g. MemberClubs is attempting to reference items in Clubs that does not exist.
Comment: Are you saying if I leave the couple rows of data out, this might work. I am trying it right now.


When is a definition via properties considered valid?

Question: How one would define the validity of a definition of an object by its properties?
Little background: I'm trying to implement a kind of framework of mathematics in which the user is not restricted to any formal system, but can define anything at will just like in english but imposing logical constraints on the steps possible during a proof preventing mistakes. This obviously requires to prove that the definition is "valid".
Example: If we consider $G$ to be a group and $+$ its group operation, we can define $0\in G$ s.t. $\forall x\in G : x+0=0+x=x$, we can prove that two sets with such property are equal ($0_1 = 0_1 + 0_2=0_2$) so the definition is solid. Here equality is by definition $x=y :\iff (\forall z:(x\in z \iff y\in z)\land \forall w:(w\in x \iff w\in y)$, so basically in any formula of set theory we can freely replace $x$ with $y$ and vice versa. But what if we don't want to be restricted to set theory? Then what seems reasonable is to require for every definition a list of formulas(not necessarily of set theory) which constitutes the notion of "equality" and then proving that in these formulas they are indeed interchangeable. This issue does not arise when considering objects defined through expressions($3:=2+1$) as they are just directly replaceable short-hand notations.
Comment: "Not restricted to any formal system" makes this question very daunting to answer. It makes it sound like either you want an answer that work for _every possible_ formal system, or you want an answer that makes sense _without even having a formal system_ -- and both of these feel like an invitation to an unproductive goalpost-moving expedition. Would you be happy with an answer that assumes we're working within standard first-order logic?
Comment: thank you, I would appreciate it, it has to suffice until I manage to formalize my question (which, considering is a quest to formalize a system in which one can express any formalized system, might be a bust)
Answer: A partial answer that works in first-order logic is to have a definitional principle that says that if you can prove $\forall x_1, \ldots x_n\exists_{1}y\phi(y, x_1, \ldots, x_n)$, then you can introduce a new $n$-place function symbol $f$, whose defining property is $\forall x_1, \ldots, x_n\phi(f(x_1, \ldots, x_n), x_1, \ldots, x_n)$. The special case when $n = 0$ lets you introduce new constant symbols. For a proof that this definitional principle is conservative (i.e., that it doesn't increase the logical strength of the theory), see Mendelson's Introduction to Mathematical Logic section 2.9.
Definitional principles along these lines are implemented in interactive proof systems such as the various members of the HOL family. The definitional principles are formulated as inference rules (they have one or more antecedent theorems) that make theory extensions (the signature of the language is extended in the theorem that is the succedent of the rule).
Comment: I have never encountered the term "full abbreviation power" in a reasonably long acquaintance with the relevant literature. The only google hits I get for it are quotations from you. So I think the OP will find it more helpful to have an answer that uses standard terminology. Predicate symbols are trivial to deal with: if $\phi(x_1, \ldots, x_n)$ is any formula whatsoever with only the listed free variables, then it is conservative to introduce a new $n$-place predicate $P$ whose defining property is $\forall x_1, \ldots x_n(P(x_1, \ldots, x_n) \Leftrightarrow \phi(x_1, \ldots, x_n))$.
Comment: By the way, your "definitional principle" is simply "full abbreviation power" that I mentioned in my answer. And you don't just want function symbols but also predicate symbols so that you can do restricted quantification.
Comment: Actually I didn't invent that term. It came from FOM posts. Yes predicates are simple but functions are not hard either. If you can prove $\exists! y\ ( φ(x_{1..k},y) )$ then it is conservative to introduce a new function symbol $f$ with the axiom $\forall x_{1..k},y\ ( φ(x_{1..k},y) \leftrightarrow f(x_{1..k}) = y )$. This is the same way that we define whether functions are representable (or can be captured) by a formula, because there is a (computable) translation from one to the other that preserves provability.
Comment: By the way, the book "A Concise Introduction to Mathematical Logic" by Wolfgang Rautenberg uses the term "definitorial extension of $T$" for the **extension** of $T$ by adding new predicate symbols or function symbols defined by a formula. It also says that in less formalized theories the ability to introduce such new symbols can be regarded as a mechanism for "abbreviation of explicit definitions". But if you have a reference that describes formal systems which can internally create new abbreviations or temporarily move to definitorial extensions, tell me and I'll switch terminology.
Answer: As Henning has already said, you need to decide on an underlying logical system, because there are incompatible logical systems and you cannot prove anything without using any logic. Suppose you pick (classical) first-order logic. Then once you implement the deductive system, you basically can use it for any finitely axiomatized first-order theory; to verify $T \vdash P$ where $T$ has axioms $X$, you simply prove $\bigwedge_{A \in X} A \to P$.
However, if you want to be able to handle any recursively axiomatizable first-order theory, you clearly need something more. One way would be to have meta rules for assuming schemas. Also, presumably you want to be able to define new constants, functions and predicates, so you would probably want to add full abbreviation power. You might want to have namespaces so that you can restrict added stuff to only where they are needed.
It would be a good idea to study how programming languages are designed, since a lot of issues for formal systems have already been studied and solved by programming language designers long ago.
Comment: The critique of the question in your comment is not justified. It is very common to develop set theory as a first order theory in a language with membership as its only predicate symbol and to define equality by extensionality as the OP did. E.g., see the development of axiomatic set theory in Mendelson's  *Introduction to Mathematical Logic*.
Comment: And equality is **not** defined like in your question. It's weaker than the standard first-order equality. There is no point in changing it, because any alternative notion of equality can be axiomatized as a new binary predicate; why should we disturb the standard intuitive equality?
Comment: @RobArthan: I know that but the asker explicitly asked for a general framework not restricted to set theory, and so it makes no sense to even want to have any ingrained notion of objects as sets!
Comment: @RobArthan: Also, it just occurred to me that for any theory over first-order logic without equality, adding the equality symbol and the inference rules for equality is in fact conservative! This shows that we can indeed use a new binary predicate for any other desired notion of equality, instead of changing the standard equality rules, which are not reliant on set-theoretic foundations.
Answer: If we go into the mathematical realm a "thing which does not exist" is just a set of properties which cannot be satisfied.


Como alterar dll de Referencia com o aplicativo em execução?

Question: Estou com um projeto onde preciso utilizar uma referencia com versões diferentes em uma unica execução, exemplo:
Trocar a referencia System.Drawing versão 2.0.0 para a System.Drawing versão 1.0.0
É possivel fazer isso?
Comment: fiquei curioso pra saber o motivo de querer isso, pra mim não faz sentido
Comment: Por que isso é necessário? Descreva melhor o seu problema, pois talvez existam outras formas de resolver e que podem não ter nada a ver com a versão da `System.Drawing`
Comment: @RovannLinhalis Exato... porque até dá para fazer copiando, renomeando e utilizando alias... Mas não consigo enxergar algum sentido nisso.
Comment: @LeandroAngelo acho que nem assim... mas vou aguardar o motivo da coisa
Comment: Estou lidando com integração de sistema, onde as versões mais antigas do sistema utiliza dll com uma versão mais antiga e quando o programa estiver fazendo calculos em sistemas mais recentes, ele precisa mudar a referencia dessa dll antiga para uma versão mais nova. Basicamente eu não consigo usar essa dll recente em um sistema antigo, por isso tenho que alterar ela. E preciso fazer isso na mesma execução. Pois vou fazer calculos em sistemas de versões diferentes com a mesma dll (com versões diferentes).
Comment: É possível carregar uma dll dinamicamente, mas não é possível referenciar.
Se você já adicionou essa referência à seu projeto, ela não pode ser mudada e o programa utilizará essa referência. No seu caso você não poderá referenciar essa dll e depois carregar as que precisa dinamicamente utilizando `Assembly.Load(path)`. Depois você pode usar os métodos da dll utilizando reflection.
Answer: É possível através de uma invocação dinâmica do assembly:
<code>// caminho da DLL antiga
var assembly = Assembly.LoadFile("caminho");

// tipo da classe desejada
dynamic instancia = assembly.CreateInstance("tipo");

// chamar o método que está procurando ou fazer o que precisar com a variável
instancia.MetodoDesejado();
</code>


how to get the Linkbutton's text to string type in it's Click event

Question: i am posting the question in gridview ... while posting, question will get converted from textbox text to linkbutton control in the gridview in the button click event
upto this i have got what i want but
i am not able to fetch the LinkButton text in string type to post again same question on top of its child page and view it's replies alone under the same page
doing ASP.net C# 2.0
protected void QuestionLinkButton_Click(object sender, EventArgs e)
    {
string LBQ = linkbutton.text;
}

Comment: you can use Damith's answer or string LBQ = (sender as LinkButton).Text;
Answer: protected void QuestionLinkButton_Click(object sender, EventArgs e)
{
    LinkButton btn = sender as LinkButton;
    string LBQ = btn.Text;
}

Answer: i used below code and got my result
protected void QuestionLinkButton_Click(object sender, EventArgs e)
    {
        Session["LBQ"] = (sender as LinkButton).Text;
        Response.Redirect("Thread.aspx");
    }

and
protected void Page_Load(object sender, EventArgs e)
    {
 string Ques = Convert.ToString(Session["LBQ"]);
        Questionlabel.Text = Ques;
    }


Laravel validation with input field as array "title[]" throws always the same error

Question: No matter which validation rule i brake as long as i have an array notation in input name like this

  {!! Form::label('titile', '* Eventname: ', ['class' => 'control-label']) !!}
  {!! Form::text('title[]', null, ['class' => 'form-control', 'required']) !!}

i get this error:

I have tried to use simple plain html input like this
<input type="text" name="title[]" />
and even like this
{!! Form::text('title', null, ['name' => 'title[]','class' => 'form-control', 'required']) !!}
But nothing works.
Only if i make the input field without array notation [] the validation works properly...
my validation rule is this
    $this->validate($request, [
        'title' => 'required|min:2',
    ]);

I don't know what else to do, if anyone had similar problem please help.
UPDATE:
i have tried it like this now with only one form input:

        {!! Form::label('title', '* Eventname: ', ['class' => 'control-label']) !!}
        {!! Form::text('title', null, ['name' => 'title[]','class' => 'form-control', 'required', 'placeholder' => 'z.B. Deutscher Filmpreis']) !!}

-
public function rules()
{
    $rules = [

    ];

    foreach($this->get('title') as $key => $val)
    {
        $rules['title.'.$key] = 'numeric';
    }

    return $rules;
}

Comment: Its because you can't insert an array in it, it wants a string. if you want many  titles under each other or a select you should consider using a loop to generate them.
Comment: can you describe this with little more details? do you mean i should use variable names without [ ] in my form or how?
Comment: Why do you have a validator on a title/label? That validator should be on input fields. And also why do you want to use an array on a single item instance? please explain the goal you want to achieve so I can tell you how to solve it.
Comment: The title field is only for example....i have other fields that are important....but it seems to me that the problem was with empty brackets [ ], in order to have an array you need to put something inside for example [0]
Answer: Write your validation in individual request file. This ('title' => 'required|min:2') validation does not work for array input. Try this technique for dynamic field validation.
public function rules()
{
  $rules = [

  ];

  foreach($this->request->get('title') as $key => $val)
  {
    $rules['title.'.$key] = 'required|min:2';
  }

  return $rules;
}

Comment: i will try to implement this and then i will accept your answer if it works
Comment: I tried this and i still get the same error. i will update my question so you can see and maybe help me further
Comment: I don't get it how can he do that in this video??? https://laracasts.com/series/whats-new-in-laravel-5-2/episodes/4
Comment: Don't put blank array like title[] use like below
Comment: {!! Form::text('title['.$id.']', null, ['class' => 'form-control', 'required']) !!}
Answer: Very Good example at laravel news site.
https://laravel-news.com/2015/11/laravel-5-2-a-look-at-whats-coming/
Answer: OK i finally solved this. In Laravel 5.3 something is changed and you can't put empty array brackets for field name.
You must declare indices inside...for example:
this doesn't work
{!! Form::text('title[]', null, ['class' => 'form-control', 'required']) !!}

but this works
{!! Form::text('title[0]', null, ['class' => 'form-control', 'required']) !!}

UPDATE
So after solving this now i know that if you put empty [ ] brackets this will work if you have multiple input fields with same name...but if you put empty brackets and you have an option to add new fields dynamically like i did...then that single field with empty array brackets will fail because you actually don't have an array...and you must put [0] some indices inside...
and then it works


Comparing angle measurements from two different techniques

Question: I'm working on a research project wherein we have 50 subjects. We have 3 x-rays per patient that all show a slightly different view of the same anatomic region. I am trying to compare an angle measurement made by a computer software based on the three x-ray types.
I want to identify if there are any significant differences in the angle measured by each x-ray type.
My data looks like this:
<code>Patient 1, Angle from XrayA, Angle from XrayB, Angle from XrayC
Patient 2, Angle from XrayA, Angle from XrayB, Angle from XrayC
</code>
I was hoping someone could explain to me which test to use and why.
Comment: What are the possible values of the angle? Could it be (e.g.) any angle from $0^\circ$ to $360^\circ$?
Comment: yes. most are in the 15-50 range though.
Comment: i was thinking of doing something like: subtract one measurement from the other to get the differences. then construct a confidence interval and see if it spans 0.   not really sure how to approach this logically though
Comment: But you are comparing three measurements, not two. For angles over a small range, analysis of variance is a simple place to start, although I worry what "most" means.
Comment: Shouldn't the analysis be done in some sort of pair/trio-wise fashion since there are three measurements for one patient?
Comment: Depending on what your aims are and perhaps partly on how your experiment is set up, you could either treat patients as fixed blocks (with patient as a blocking factor) or as random effects (in a mixed model). If your patients are thought of as randomly selected from some population, you'd likely choose the second.
Comment: I'm leaning towards the former. One patient's angle is in no way predictive of another patient's angle, but his angle should be similar to the one measured by other x-rays.
Answer: To gain a better understanding of the data I'd consider drawing three pairwise Bland-Altman-Plots and/or three plots plotting eacht method's result against the mean of all three measurements.
If I understand "any significant differences in the angle" correctly, that might be a job for Friedman's test.
Bernhard


Port Security / MAC lock with Netgear GS752TXS

Question: Has anybody here has in use the Netgear GS752TXS (52 Port Stackable Smart Switch with 10GE uplink) with port security active?
I would like to activate port security on specific ports to allow only one specific device (MAC) on this port. That´s what I understand from "port security" here and should be possible with this device - according to the documentation.
If I activate port security, I have to options: lock down the number of dynamically learned addresses - or the number of statically learned adresses.
Lock dynamically learned makes nearly no sense. It´s possible to prevent somebody to plug in a switch in between - buts thats it. The problem with dynamically learned adressing is that all dynamic entries are aging (default 300s - then they are renewed or lost) AND if you plug in a device into another port, the entry is also updated to the other port and the entry of the old port is lost. So limiting the dynamic entries on a specific port to "1" does not help here. Since if somebody plugs in his device in another port the "locked" port is free for reassignment :-(
The problem with "static assignment": If you assign a MAC address to the port statically, it works in first line.... the port won´t accept another MAC/device....
BUT the device also cannot be plugged in into another port! It´s limited to this specific port. That´s not what I exactly want... :-(
I really would like to have ports to accept just specific MACs and some ports to support multiple ports (like meeting rooms etc).
Does anybody know if thats possible with this device?
Another good thing would be the possibility to specify a list of allowed MAC addresses all over the switch and block all other.... but I don´t think this is possible....
Answer: I went through the Netgear GS752TXS Software Administration Manual and what you are looking for is on pages 220-223.
You said you want "to activate port security on specific ports to allow only one specific device (MAC) on this port."
Specifically the steps to do this are provided on page 221.

Click Security
Click Traffic Control
Click Port Security
Click Port Security Configuration
Select Enable
Click Apply
Click Interface Configuration
Select the ports you want to enable port security on
Select Enable in the Port Security field
Set Max Allowed Dynamically Learned MAC to 0 (according to the manual this effectively disables dynamically learning MAC addresses)
Set Max Allowed Statically Locked Mac to the number of MAC addresses that will be connected to this port.
Set Enable Violation Traps to Yes

I need to stop and emphasize a point here. If you are plugging an unmanaged switch into a port that you are using port security on (not recommended) then you need to allow the MAC address of each device that will be connected to that unmanaged switch.

You will need to specify which MAC addresses are permitted for each port that you are enabling port security on.
If you have a computer that is running a VM and the VM is configured to connect to the network via bridged mode, then you must also include the MAC of the VM in your port security configuration on the physical port that the host is connected to. If you do not port security will shutdown traffic to both MACs on that port.
Comment: This is what I did as written. But then the device statically enabled on a specific port cannot be plugged into another port because the MAC is written into the static ARP routing table.
I think there is no solution...
Comment: That is what it is supposed to do.
Comment: No, what it is supposed to do in my view is to lock down the one port to one MAC address... but allow the MAC address to also connect to other ports.... otherwise its useless for me and works different on Cisco switches f.e.
Comment: Unfortunately that is not how port security often works. The idea is not only does it tie a MAC to a port but it keeps the user of that MAC from changing what port they are plugged into thereby circumventing whatever you put in place that required their MAC address being associated with a specific port. Different brands implement port security differently but from my understanding of the Netgear documentation this is the intended behavior.
Comment: I do see that what you are describing should work on Cisco devices because what you are saying is using a secure MAC on a non secure port. That appears to work on Cisco devices but it may not on netgear. If that is what you are trying to do I would ask what are you trying to accomplish? Why do you need to be able to move a secure MAC from a secure port to a non secure port?
Comment: I want to lock down our network to specific MACs at all - one idea was to lock down each user port to their specific device - but allow them to use their devices also in meeting rooms. Since this won´t work as expected I´ll give 802.1X a try.... never done that before but seems to be quiet easy since we already have a radius server.
Comment: Have you considered using ACLs by MAC instead of port security? Your Netgear switch supports that.


Converge in Sum vs Convergence

Question: Let $X_1, X_2, \ldots$ be a sequence of independent, integrable, random variables on $(\Omega, F, P)$, with $E[ X_k] = 0$ for all $k=1,2,\ldots$ Show that
$$
\mbox{If } \frac{S_n}{n} \xrightarrow{P} 0 \mbox{ then } \frac{X_n}{n} \xrightarrow{P} 0
$$
I am having difficulties solving this problem, I am not sure how the 0 mean conditions are used here. We know that $E[S_n]=0$ as well but apart from that I dont see how this is used any further.
Let $X_1, X_2, \ldots$ be a sequence of independent, integrable, random variables , with $E X_k = 0$ for all $k=1,2,\ldots$ Show that
$$
\mbox{If } \frac{S_n}{n} \xrightarrow{\mbox{a.s.}} 0 \mbox{ then }  \sum_{n=1}^\infty P\{|X_n| \ge \epsilon n\} < \infty \quad
\mbox{for all $\epsilon > 0$.}
$$
For this second one, there is a statement that $\sum_{n=1}^\infty P\{|X_n| \ge \epsilon\} < \infty$ if and only if $X_n\to 0$ (easily proved from Borel Cantelli lemmas). I think that is used here but I am not sure how. And help will be great. Thanks!
Answer: First Question
By definition $\frac{S_n}{n} \xrightarrow{P} 0$ if and only if  $P\left(\frac{|S_n|}{n} \geqslant \epsilon\right) \to 0$ as $ n \to \infty$ for all $\epsilon > 0$.
We also have,
$$\tag{*}\frac{X_n}{n} = \frac{S_n}{n} - \left(\frac{n-1}{n} \right)\frac{S_{n-1}}{n-1}$$
Since $(n-1)/n \to 1$ it is easy to show that the second term on the RHS of (*) converges to zero in probability (as well as the first term by hypothesis).
That the LHS of (*) converges to zero in probability follows from the fact that $A_n \xrightarrow{P} 0$ and $B_n \xrightarrow{P} 0$ implies $A_n + B_n \xrightarrow{P} 0$.
To prove this note that
$$\left\{|A_n| < \epsilon/2 \right\} \cap \left\{|B_n| < \epsilon/2 \right\} \subset \left\{|A_n + B_n| < \epsilon \right\}$$
Taking complements, it follows that
$$\left\{|A_n + B_n| \geqslant \epsilon \right\} \subset \left\{|A_n| \geqslant \epsilon/2 \right\} \cup \left\{|B_n| \geqslant \epsilon/2 \right\}, $$
and
$$P(|A_n + B_n| \geqslant \epsilon) \leqslant P(|A_n| \geqslant \epsilon/2 ) + P(|B_n| \geqslant \epsilon/2) $$
Second Question
Hint: $\frac{S_n}{n} \xrightarrow{\mbox{a.s.}} 0 \implies \frac{X_n}{n} \xrightarrow{\mbox{a.s.}} 0$
Comment: I see, so $X_n/n\to 0$ a.s. iff $\sum P(X_n/n>\varepsilon)$ converges and then you're done. However why does $S_n/n\to 0$ a.s. imply $X_n/n\to 0$? You can't use Slutksy's like you did in problem 1. Thanks!
Comment: Well -- again -- $X_n/n$ is a sum (difference) of two random sequences that converge to $0$ almost surely and almost sure convergence is preserved in finite sums.  This is proved in the solution of exercise 2 [here](https://www.statlect.com/asymptotic-theory/almost-sure-convergence).

Converge in Sum vs Convergence


Is there another way to code a loop that selects from one of many with LINQ?

Question: I have numerous examples of code like this in my application:
   foreach (var setting in vm.PTI)
   {
     if (setting.Name == name)
     {
        setting.IsSelected = true;
        App.DB.UpdateIntSetting(SET.Pti, setting.Id);
     }
     else
        setting.IsSelected = false;
   }

Loops that run through an array, pick the one row that matches and then set properties in the array.
Although this works well, I am wondering if there are other ways to write this code using LINQ or other. I suspect this might be the best ways but would be interested to get feedback from others as this is something I do maybe 20 times in my code and if there's a better way to do it I would like to try using the better way.
Here is the class that is used:
    ParamViewModel[] _pti;
    public ParamViewModel[] PTI
    {
        get => _pti;
        set => SetProperty(ref _pti, value);
    }

public class ParamViewModel: BaseViewModel
{

    int _id;
    public int Id
    {
        get => _id;
        set => SetProperty(ref _id, value);
    }

    string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set => SetProperty(ref _isSelected, value);
    }

}

Comment: This is better than LINQ because you are actually modifying data and LINQ should be used for querying and not manipulating data. 20 times is nothing, that's pretty much what programming is all about: conditions, loops etc.
Comment: Having said that, you can query like this: `vm.PTI.Where(x => x.Name == name);` and then loop them and do the part in your `if` condition. Then another query like this: `vm.PTI.Where(x => x.Name != name);` and loop them and do the part in the `else` part. I still think what you have is better.
Comment: I would agree with CodingYoshi. Its better this way than in linq. Even both are enumerating the collection. I basic choice i do if i'm querying something or transforming i will use linq or something like this can stay in `foreach`.
Always strive for readability & maintainability.
Answer: You can get the setting first with LINQ, then set it.
var setting = vm.PTI.FirstOrDefault( s => s.Name == name );
if (setting != null)
{
    setting.IsSelected = true;
    App.DBUpdateIntSetting(SET.Pti, setting.Id);
}

Comment: How about else?
Comment: A bool field is defaulted to false
Comment: A better way will be via First rather than Where, unless there can be multiple matching records. First will return as soon as the 1st match is found and 2nd will continue till the end
Comment: This is not correct because it is only affecting the first item and it is also missing the `else` part.
Comment: There will be one (maybe different) setting.IsSelected will be true before this runs.
Answer: For your particular case you can write extension method:
    public static void ModifyCollection<T>(this IEnumerable<T> source, Predicate<T> selectedPredicate,Action<T> selectedAction, Action<T> othersAction=null)
    {
        if (selectedPredicate == null) throw new ArgumentNullException(nameof(selectedPredicate));
        if (selectedAction == null) throw new ArgumentNullException(nameof(selectedAction));
        foreach (var element in source)
        {
            if (selectedPredicate(element))
            {
                selectedAction(element);
            }
            else
            {
                othersAction?.Invoke(element);
            }
        }
    }

How to use it:
PTI.ModifyCollection(
      selectedPredicate:(s) => s.Name == name,
      selectedAction:(s) =>
           {
             s.IsSelected = true;
             App.DB.UpdateIntSetting(SET.Pti, setting.Id);
           },
      othersAction:(s) => s.IsSelected = false);

You can go further and specify constraints to T. 'where T is INamed' and put predicate code inside extension method.
You can write your own extension method:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");
    foreach (var element in source)
    {
        action(element);
    }
}

Comment: @Alan2 Updated my answer.
Comment: @CodingYoshi it just a matter of convenience. You can't for example do that collection.Where(...).foreach(var c in collection){}; But with this extension you can do that collection.Where(...).ForEach((e)=>dosomething);
Comment: @CodingYoshi Why do you use Linq if foreach and for loop existed long before that?
Comment: @CodingYoshi from that thread:
1. Type checking: foreach is done at runtime, ForEach() is at compile time (Big Plus!)
2. The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething);
3. ForEach() could be chained
Comment: Not sure what you are trying to say, I am saying `ForEach` is already available as an extension method so why are you suggesting to create something which already exists?
Comment: @CodingYoshi not sure what you mean, try this:  IEnumerable words = new string[] { "a","b"};  words.ForEach((s)=>Console.WriteLine(s));;
Comment: Try `words.ToList().ForEach` ;)
Comment: @CodingYoshi just confirm that it does not exist. : ) And my extension method makes sense.
Comment: +1 You can argue whether this extension method should be this or that way. However, I like the idea of implementing once and reuse. We do not know the actual repetitive pattern. Probably `IsSelected ` is always handled the same. It could be part of this method. Probably selecting by `Name` is always the same. We don't know.
Comment: @CodingYoshi There is no such method for IEnumerable. There is a method for List, but it does not make sense to Convert collection to List to get some method. ToList() will create a copy for value types and structs, so it could be expensive operation.
Comment: @Access Denied Can you give an example of an extension method that I could use for this case.  I did add some more details on the array that I am using.


At what BPM (Beats per Minute; quarter note = beat) will we hear the top note as F4?

Question:
My question comes from MUS 204: At what BPM (Beats per Minute; quarter note = beat) will we hear the top note as F4?
Now, I understand this polyrhythm would generate a perfect fourth when sped up to an audio frequency. However, I do not know how to find the BPM of a note if given this information. How would you answer the question correctly?
Comment: @Aaron I think in this question, it is considered that the notes are played extremely fast, with the F4 note frequency.
Comment: Do you know the standard frequency for F4? If you don't you can find it easily. If you do, you know that you'll listen to *that many beats* per seconds, and each beat is one of the note above. Since a bar is 4 of those notes, you then know the frequency of that bar. Then you can compute the frequency of the beats below.
Comment: There's something I'm not understanding here. How are sound-wave cycles supposed to correspond to rhythmic beats? Aren't the two concepts unrelated (or at least, independent)? Is there information missing from the question, like the starting pitch and tempo of one or both notes?
Comment: @Aaron Like something Adam Neely demonstrates here: https://youtu.be/-tRAkWaeepg
Comment: @Renée if something happens once a second, how many times does it happen in a minute?  If something happens twice a second, how many times does it happen in a minute?  Answering those questions should help you to identify the factor that converts things-per-second to things-per-minute.
Comment: @Renée you were almost there. 350 beats per second means that each bar is ~87bpm, and then you can get the value of each beat (4 per bar) by multiplying that by 4).
Comment: @user1079505 So one quarter-note = one sine wave cycle?
Comment: @Aaron The question is about the top note, so one note under the 4-tuple. Yes.
Comment: @Aaron also I would say "one cycle", not "one sine wave cycle", since the shape of the cycle would be whatever is the waveform of the note played. But yes, repeated it would have a sine wave component of that frequency.
Comment: @Renée : does this clarify things for you? If not, could you write more specifically what do you need help with and what attempts did you made to solve it?
Comment: @musicamante Let me see if I am understanding this correctly. The frequency of F4 is 349.23 Hz, so there are approx. 350 beats per second. Would I multiply this frequency by 4?
Comment: @user1079505 I was *exactly* thinking about that video :-)
Comment: both the answers given are correct, the trick is that neither "C4" nor "F4" actually refer to any specific frequency, they refer to a range of frequencies that are we hear as "in tune" and equivalent to "C4" or "F4" in an arbitrary (in this case, unstated) context. unless you want to argue that a singer one cent flat isn't actually singing the note that we all hear.
Answer: The target frequency (F4) is approximately 349.23Hz.
You have to find a common divisor between those two frequencies, which coincidentally is the bar.
So, assuming the frequency above, you can find that each bar happens at frequency/4. Then, you can find the frequency for the beat by multiplying it by 3 (since the meter is 3/4 - aka, 3 beats per bar), and finally get the actual BPM by multiplying by 60:
F4 = 349.23
barsPerSecond = F4 / 4
>>> 87.3075
beatsPerSecond = barsPerSecond * 3
>>> 261.9225
beatsPerMinute = beatsPerSecond * 60
>>> 15715.35

Consider that the answer from Aaron is perfectly right, but it is based on the ratio of an interval that uses the frequency of the second note as reference. Since you might not know the precision of that reference, it's up to you to decide if you should use the known ratio of the interval (not knowing the tuning it's based on), or the rhythm ratio shown in the example.
Comment: A calculation doesn't yield a greater precision than the input; you should round that final number to five significant figures
Comment: I appreciate the shout-out, but can you clarify the part about interval vs. rhythm ratios. OP says the interval is a perfect fourth based on the polyrhythm, so both are 4:3. There's no difference in the reference point except the order of operations of the math. But since multiplication is commutative, that doesn't influence the result.
Comment: You've claimed that F4 is an approximation, so your conclusion can only be an approximation of the same precision.

Your calculation is fine [now], and you should leave the calculated number as is, but you should add another line that concludes BPM = 15715.  The '.35' is meaningless/inaccurate for a conclusion.
For consistency if you want a 7 sig. fig. conclusion you need to define/assume a 7 figure value for F4.

It is more accurate [and easier] to compare [your] 15715 to [Aaron's] 15698.
Comment: @ElementsinSpace you're technically right (especially considering the frequency in use), but I think we still have to consider that not all platforms/languages use the same kind of approximation/precision, and, most importantly, precision might be much more important for lower frequencies. While we might not hear any difference between `15715` and `15715.35`, it's not a difference *that* difficult to consider, and we should probably consider it anyway, at least for consistency, in case we need to do further computations. For instance, Aaron's answer already shows an interesting difference.
Answer: The top and bottom notes are in a speed ratio of 4:3. This means that if the upper pitch is F4, the lower pitch will be C4.
Since BPM = quarter-notes per minute, and one quarter-note = one frequency cycle, then to convert beats to Hertz, we divide BPM by 60. (That is, convert quarter-notes per minute to quarter-notes per second.)
C4 is approximately 261.63 Hz (SOURCE), so X BPM / 60 = 261.63. Therefore X = 261.63 x 60 = 15,697.8
Thus, to produce an upper pitch of F4, the BPM must be approximately 15,697.8.
Comment: @musicamante It's just a rounding error. Freq(F4) = Freq(C4) * 4/3. So given C4 = 261.63 Hz, that would put F4 at 348.84 Hz. The table gives F4 = 349.23, which would result in C4 = 261.92. 261.92 * 60 = 15715.2.
Comment: F4 is given; C4 is not.  Therefore, the pitch that is out of tune with equal temperament is the lower pitch, not the upper one.  The lower pitch, in other words, is not 261.63 Hz.
Comment: @phoog I don't understand your comment. The exercise is clearly based on the idea that perfect fourths are in an exact 4:3 ratio. At that level, it makes no difference whether one uses C4 or F4 as the "fixed" frequency. Any difference based on that is just rounding error, as musicamante and I discussed in the previous comments. The exercise is designed to focus on the mathematical process, which is effectively the same either way.
Comment: Uhm, but the OP is asking about F4, and the BPM has to be related to that. So, assuming that `F4 = 349.23` Hz ("beat per second"), we get the common division (the bar) at `bar = F4 / 4` and the ratio based on the actual beat at `beatPerSec = bar * 3`, which results in `BPM = beatPerSec * 60`: 15715.35.
Comment: oh, right, now I get it, sorry...