Mann Whitney test results interpretation

Question: I have two samples both bigger than 99999 and I get the following result in Python:
MannwhitneyuResult(statistic=2395063024.0, pvalue=2.3093898533164459e-128)
U critical = 135807.32
If I understand it correctly, I cannot reject the null hypothesis that samples (distributions) are the same because U obtained > U critical.
However, If I make boxplots it seems like one distribution is bigger than the other one.

Are my results correct and what can I conclude?
Comment: Something is wrong.  The p-value and critical value do not make sense. Besides the a p-value that low would mean that the observed test statistic is way beyond the critical value when a significance level like 0.05 or 0.01 is used.
Comment: Ah, I see that on the page for `scipy.stats.mannwhitneyu` (I presume that's what you're calling then) that it says that their version of the statistic is significant if it's smaller than the critical value. However, there's a comment higher up that suggests that it may depend on the alternative chosen. You don't say what alternative you actually used.
Comment: Thank you both. I am using scipy.stats.mannwhitneyu. I haven't used the alternative since it was optional but I will try it out.
Answer: Unfortunately, the conclusion is reversed.  Because $p \ll \alpha$, you would reject the null (which assumes the distributions have the same parameter).  Additionally, the sample size all but guarantees that you will reject the null.  In this case, it may be more beneficial to accept that the distributions are different and address the difference between the two samples from a practical significance (an effect size) instead of a statistical significance.
Comment: Thank you very much. I will do that. I just have one more question. Would it be ok to conclude which one is bigger based just on the boxplots?
Comment: You could conclude that by comparing the boxplots, or the medians, or other target percentiles of interest (e.g., 75th, 90th, 99th, etc.)


In ANOVA, why are $\text{MS}_\text{between}$ and $\text{MS}_\text{within}$ defined by divisions by k-1 and N-k?

Question: I realize that the divisions are meant to take into account the number of factor levels (which will tend to push up $\text{SS}_\text{between}$), and the number of observations (which will tend to push up $\text{SS}_\text{within}$). However, I can't understand why we don't obtain these Mean Squares by dividing $\text{SS}_\text{between}$ by k and $\text{SS}_\text{within}$ by N.
For example, in the following data there were three levels to the factor, and 18 observations in total.
Answer: Under the null hypothesis (and the assumptions of ANOVA), $SS_\text{between}$ has expected value $(k-1)\, \sigma^2$ and $SS_\text{within}$ has expected value $(N-k)\, \sigma^2$.
(the reason why the sum of $N$ residuals-squared has expectation $(N-k)\, \sigma^2$ rather than $N \sigma^2$ is because each group's sample mean is closer to the data (in sum of squares sense) than the true mean is.
[If the alternative hypothesis is the case, the numerator has a larger expected value, but the denominator's expected value is unchanged. This is why we reject when $F$ is large.]
So when you divide by the appropriate degrees of freedom, both MS terms are estimates of the same quantity, $\sigma^2$, the variance of the error term when the null is true.
Taking their ratio then cancels out the $\sigma^2$, leaving something typically close to 1 under the null hypothesis (and typically larger than 1 under the alternative) and which has an F-distribution.


How to get rid of unwanted thin borders in SVG? Different behavior (IE, Chrome, etc.)

Question: I am creating some SVG image that consists of multiple rectangles. Those rectangles are one next to the other, the edges "touch" each other, some browsers (e.g., Chrome, Vivaldi) and image converters render unwanted tiny lines between those rectangles. Meanwhile, some other browsers (IE, Edge) displays the SVG in the desired way.
I checked the SVG in several browsers and in the Inkscape editor (I have exported the SVG into PNG, and the lines were also present).
I can solve there problem with adding some tiny overlap, but I don't like such a solution.
Is that a bug in SVG libraries used in browsers and Inkscape? Or shall I use some SVG feature to fix it?
Chrome example
Inkscape example
Edge example
<svg height="10cm" viewBox="0 0 10 10" width="10cm" xmlns="http://www.w3.org/2000/svg">
    <rect fill="#ff00ff" height="1" opacity="1" width="1" x="1" y="1"/>
    <rect fill="#ff00ff" height="1" opacity="1" width="1" x="2" y="1"/>
    <rect fill="#ff00ff" height="1" opacity="1" width="1" x="3" y="1"/>

    <rect fill="#167f81" height="1" opacity="1" width="1" x="1" y="2"/>
    <rect fill="#167f81" height="1" opacity="1" width="1" x="2" y="2"/>
    <rect fill="#167f81" height="1" opacity="1" width="1" x="3" y="2"/>

    <rect fill="#000000" height="1" opacity="1" width="1" x="1" y="3"/>
    <rect fill="#000000" height="1" opacity="1" width="1" x="2" y="3"/>
    <rect fill="#000000" height="1" opacity="1" width="1" x="3" y="3"/>
</svg>

Answer: These edges are the result of tradeoffs renderers make when borders don't match with screen pixels or printer dots. You can state
shape-rendering="crispEdges"

to give a hint to the renderer to set the edges such that they should always coincide with pixels, even if the result of computing the conversion from userspace coordinates to real-world cm units would give a fraction.
Note that this is a hint that renderers may or may not honor.
In addition, some renderers have a bit of a hard time with rounding routines when dealing with small numbers. If you multiply all of your rects sizes and positions with ten, and consequently raise the viewBox size by the same factor, but leave the <svg> width and height unchanged, results may improve.


cross domain htaccess config

Question: I need to route
http://domain.fr/subpage
to
http://domain.com/fr/subpage
using htaccess.
Any ideas how?
All the small config elements of .htaceess are driving me batty on this cold Monday morning.
Comment: I should add that both domains are on the same server and working just fine :)
Comment: RewriteCond %{HTTP_HOST} ^domain.fr/subpage[nc]
RewriteRule ^.*$ http://domain.com/fr/subpage [r=301,nc]

Gives a 404?
Comment: Gothere in the end

[code]
#RewriteCond %{HTTP_HOST} ^domain.fr$ [NC]
#RewriteCond %{REQUEST_URI} subnavfolder
#RewriteRule ^.*$ http://domain.com/fr/subnavfolder [R=301,L][/code]
Answer: Try this:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.fr$ [NC]
RewriteCond %{REQUEST_URI} ^/subpage[/]?$
RewriteRule (.*) http://domain.com/fr/subpage [R=301,L]

Those rules will check if the domain is domain.fr and if the URI is /subpage or /subpage/ and will then redirect with statuscode 301 (permantly moved) to the actual address you wish.

cross domain htaccess config


Prove that the commutator subgroups of $G$ are normal in $G$

Question: If $G$ is a group, show that all $G^{(k)}$ are normal subgroups of $G.$
Here, $G^{(1)}$ denotes the subgroup generated by $aba^{-1}b^{-1} = [a,b]$ for every $a,b \in G.$
For every $a \in G,$ one has $$g [a,b] g^{-1} = [gag^{-1},gbg^{-1}] \in G^{(1)}$$
Now observe that
$$gaba^{-1}b^{-1}g^{-1} = gag^{-1}gbg^{-1}ga^{-1}g^{-1}gb^{-1}g^{-1} = (gag^{-1})(gbg^{-1})(gag^{-1})^{-1}(gbg^{-1})^{-1}= [gag^{-1},gbg^{-1}]$$
Hence $G^{(1)}  \triangleleft G.$ Let $\varphi \in \operatorname{Aut}(G).$ Then $$\varphi(aba^{-1}b^{-1}) = \varphi(a) \varphi(b) \varphi(a)^{-1} \varphi(b)^{-1} \in [a,b]$$
Since $\varphi$ is a group automorphism if the generators of $[a,b]$ are mapped to itself, it follows that $\varphi([a,b])=[a,b].$ Thus the commutator subgroup is a characteristic subgroup.
Comment: The claim $gag^{-1}gbg^{-1}ga^{-1}g^{-1}gb^{-1}g^{-1} = (gag^{-1})(gbg^{-1})$ is false, and it looks like you're assuming that $\phi$ is an inner automorphism.
Comment: @CuddlyCuttlefish fixed, thanks
Answer: Careful! I am not entirely sure what you're writing, but recall that normality is not transitive, so that an argument of the form $K\lhd H\lhd G\implies K\lhd G$ is incorrect. What you can show is that the commutator subgroup of a group $G$ is a characteristic subgroup: if $\psi: G\to G$ is an automorphism, $\psi(G')=G'$, for $\psi[g,h]=[\psi g,\psi h]$. Since characteristicness is transitive, it follows from $G' \,{\rm char}\, G$ that $G^{(k)}\,{\rm char}\, G$ for every $k$. Since inner automorphisms are in particular automorphisms, it follows every derived subgroup is in particular normal.


How to indicate expand/collapse points when writing code in Visual C# Express 2008?

Question: When coding in Visual C# Express 2008, you can expand/collapse code segments using the +/- symbols on the left hand corner of the text-editor. These appear automatically when a function is created.
Is their anyway I can manually add an expand/collapse point to a code segment?
Comment: Not worth an answer, but it *is* possible to create arbitrary code folds exactly like the automatic ones. ViEmu is one plugin that does this to mimic Vim's text folding behaviour, but if you don't use Vim, you won't want ViEmu.
Answer: Yes, you can define a region manually
<code>#region myRegion
// your collapsible code here
#endregion
</code>
Comment: I slightly changed the code to have "endregion" instead of "end region"
Comment: thanks,

the keyboard shortcut after highlighting the code is
ctrl+K, ctrl+S, #re and then hit enter

after that change the name

cheers :)
Comment: Thanks for the fix, Eilon!  If it wasn't for good IDE editors, my code would never compile...  :)
Answer: #region Any region name goes here

... code goes here ...

#endregion
Note that the #endregion has no space in it.


rewrite url with domain as condition

Question: I'm using apache with mod_rewrite and codeigniter to do my routing.
I've got two seperate (wildcard)domains pointing to my website, say: *.foo.com and *.bar.com
*.foo.com/somepath should to rewrite to *.foo.com/index.php/somepath
and *.bar.com.somepath should to rewrite to *.bar.com/index.php/bar/somepath
This is my .htaccess:
<code>RewriteEngine on

RewriteCond %{HTTP_HOST} [^.]{3}\.bar\.com [NC]
RewriteCond $1 !(index\.php|assets|favicon|bar)
RewriteRule ^(.*)$ /index.php/pzdossier/$1 [L]

RewriteCond $1 !(index\.php|assets|favicon)
RewriteRule ^(.*)$ /index.php/$1 [L]
</code>
This gives me the correct result when I go to dev.foo.com/whatever
but when I go to dev.bar.com/whatever it just rewrites to dev.bar.com/index.php/whatever instead of pzdossier.
If I change
<code> RewriteRule ^(.*)$ /index.php/pzdossier/$1 [L]
</code>
to
<code> RewriteRule ^(.*)$ /index.php/pzdossier/$1 [L,R=302]
</code>
It works, I get redirected to /index.php/pzdossier/whatever.
What am I doing wrong? why does a redirect work, but a rewrite doesnt?
Answer: Codeigniter was using the $_SERVER['request_info'] to determine what controller to call.
When I changed that to $_SERVER['PATH_INFO'] it correctly using the .htaccess rules as I wanted.
So change application/config/config.php $config['uri_protocol'] to PATH_INFO

rewrite url with domain as condition


Prove that $C$ is a basis in $\mathbb{R^3}$

Question: Prove if $B = \{ \vec v_1, \vec v_2, \vec v_3 \}$ is a basis in $\mathbb{R^3}$, then so is $C = \{ v_1+v_2, v_2+v_3, v_1+v_3 \}$.
I've already proven that $C$ is linearly independent. How do I prove that $C$ is a subset of $\mathbb{R^3}$ and that it spans it? It seems that I can write $C$ as a combination $x(v_1+v_2)+y(v_2+v_3)+z(v_1+v_3)$, where $x, y, z \in \mathbb{R^3}$
Comment: There is no need to "prove" that $C$ is a subset of $\Bbb R^3$. If $v$ and $w$ are elements of $\Bbb R^3$, then by the definition of addition it holds that $v + w$ is an element of $\Bbb R^3$.
Comment: How did you prove that $C$ is linearly independent? If this proof was correct, then there's probably a way to leverage your proof so that we also show that the vectors span $\Bbb R^3$.
Answer: You proved that $\dim \operatorname{span} C = 3$. But $C$ is a subspace of $\mathbb{R}^3$ and $\mathbb{R}^3$ has dimension $3$. Hence...
Answer: The answer is simple. There is a theorem, Steinitz exchange lemma, that states that if $C$ is linearly independent with $n$ elements, then it is also a basis of $\mathbb{R}^n$. It is what you want, isn't it?


High quality screen capture

Question: I'm making a manual for a web-based app. I take screenshots and put them into adobe illustrator and they lose their quality extremely fast when zooming in. Is there anyway I can take high resolution or vector based screenshots that don't loose image quality when zoomed in? This seems to be only a problem with illustrator, with photoshop when I zoom in it gets slightly fuzzy but thats it.
Comment: The quality of the screenshot directly depends on your monitors resolution, i.e. bigger monitor = higher resolution. I don't believe there is anything you can do about that.
Comment: photoshop is probably doing a better job at interpolating the pixels of your screenshot or illustrator just don't alter your original image on purpose.
Answer: There is no exact way to capture as a vector. Because of the capture program, not knowing of any geometry shapes.
Although, you can capture a raster image and convert it to a vector. There are numerous tools out there, that will allow you to do this conversion. Then you will have to do a little bit of tweaking. But in reality you cannot take a capture as a vector, or convert it and have it be "pixel-perfect".
Hope this helps!
Zachary

High quality screen capture


How Different is an Eigenvalue Problem from an Ordinary Differential Equation

Question: I have been thinking about how different an eigenvalue problem such as that of the Sturm-Liouville Equation (SL) with that of a second-order linear differential equation. It doesn't seem to be the case to be the difference between a boundary value problem vs. an initial value problem, as we may also have BVPs that do not involve eigenvalues, in which case solutions might not exist in abundance as opposed to the case with IVPs. Perhaps, the eigenvalue parameter is there to allow us to speak of to which values of the parameter there exist a solution.
However, that brought me to the question as to what happens when no boundary values are imposed, such as in the case of the famous Simple Harmonic Oscillator (SHO) SL problem in Quantum Mechanics (QM), where the wavefunction, i.e. the solution of the "eigenvalue" problem, is defined throughout the entire real line without any restriction - except for the fact that they approach the $x$-axis asymptotically, which actually follows from square-integrability. I put the word "eigenvalue" in quotation marks because I am now questioning it. Let me explain.
The SHO problem is the seeking of the solution $\psi$ to the "eigenvalue" problem $\displaystyle-\frac{\hbar^2}{2m}\frac{d^2\psi}{dx^2}+\frac{1}{2}m\omega^2x^2\psi=E\psi$. We can clean up the equation by absorbing constants, but we will keep them. It is well-known in QM that solutions to this eigenvalue problem are products of Hermite polynomials with a Gaussian and the eigenvalues $E$ form a discrete set and are given by $E_n=\left(n+\frac{1}{2}\right)\hbar\omega$. Note that no boundary conditions are imposed although, of course, we are seeking for square-integrable functions. Herein lies the question:
If we rewrite the SHO equation as $\displaystyle-\frac{\hbar^2}{2m}\frac{d^2\psi}{dx^2}+\left(\frac{1}{2}m\omega^2x^2-E\right)\psi=0$, it does look to me like a legit 2nd order variable-coefficient linear ODE that has a solution for any $E$. Specifically, $E$ does not have to assume specific values that form a discrete set.
What am I missing here? That not all $E$s give square-integrable solutions? How is the SHO an eigenvalue problem and not a mundane differential equation problem?
Appreciate your insights.
Comment: Having solutions to be asymptotically $0$ is just a way to impose boundary conditions on an unbounded interval, the "boundary" is at infinity. SHO does have solutions for any $E$, but only for a discrete subset of values do they asymptotically vanish. This is no different from SL, it also has solutions for any $\lambda$, but boundary conditions can be met only for a discrete subset of them. If by "mundane" problem you mean a general solution to DE, with no initial, boundary or asymptotic conditions, then there are two differences: no such conditions, and no parameter like $\lambda$ or $E$.
Comment: Thanks for replying, Conifold, but I am afraid I don't quite understand what you mean, especially the last statement. Are you saying that only a discrete set of functions satisfy the equation? Actually, in essence, what I am asking is, if you look at the last equation in my question, think of $E$ as being given, isn't that an ordinary 2nd order linear ODE with variable coefficients and so there is a solution (since the coefficients remain continuous)? And since $E$ is arbitrary, the equation is a family of parametric equation whose solutions are also parameterized (by $E$).
Comment: Only a discrete set of functions that vanish at infinity satisfy it. If $E$ is fixed there will be a solution, but it will not vanish at infinity unless $E$ is from a discrete set. It is the same as for $x''+k^2x=0$ on $[0,\pi]$, $\sin kx$ is always a solution, but only for integer $k$ it vanishes at the endpoints.
Answer: Your problem has always the zero function as solution. So the real question to ask is how to get solutions apart from that. So in effect you are asking for a singular situation that only isolated values of $E$ will satisfy.
You can transform this into an ordinary boundary value problem by

(zeroth reducing the infinite interval to some finite interval $[x_0,x_2]$)

first adding $E$ as component with equation $\frac{dE}{dx}=0$, and

then add the square integral as fourth component with equation $\frac{dI(x)}{dx}=|ψ(x)|^2$.

Now you have 4 state components and thus 4 slots for boundary conditions, which are
$$ψ(x_0)=ψ(x_1)=0~\text{ and }~I(x_0)=0, ~~I(x_1)=1.$$
As with many BVP there will not be a unique solution, if you employ a numerical solver, the initial guess has to be close to some eigenfunction to get predictable results.
Comment: Thanks, Lutz, but I am afraid I don't quite understand what is "zeroth reduce." I do need the problem to be on the entire real line. Do you mean a map that takes -infinity to 0 and infinity to 1?
Comment: For the function to be square-integrable, it has to fall to zero at infinity. It falls below numerically representable values (different from zero) at some finite point. Thus it is justifiable to reduce to a finite interval. You could use the WKB approximation to supply estimates for the missing parts, somewhere that was called the "far field solution".
Comment: Thanks, Lutz! I think your second point is very illuminating. I now see a way to look at an eigenvector-eigenvalue problem!
Answer: From the point-of-view of Quantum Mechanics, a valid solution of the harmonic oscillator equation must be square integrable in $x$, because the square of a valid solution is a probability distribution. That does not mean that the solution cannot be built from non-square-integrable solutions of $H\psi_{\lambda}=\lambda \psi_{\lambda}$ through a Fourier transform type of integral. But it would mean that there would not be exact energy levels for the oscillator if there were no $L^2$ eigenfunction solutions of $H\psi_{\lambda}=\lambda\psi_{\lambda}$ for some real $\lambda$.
When looking at the solutions of $H\psi= \lambda\psi$, where $\lambda$ is a separation constant that is also constant of energy, there's no reason to assume a priori that there will be $L^2(\mathbb{R})$ solutions for a given real $\lambda$. You let the chips fall where they may, and you find out that there is a discrete, countably infinite set of $\lambda_0 < \lambda_1 < \lambda_2 < \cdots < \lambda_n \rightarrow\infty$ for which there are $L^2(\mathbb{R})$ solutions and, furthermore, the null space of $\mathcal{N}(H-\lambda_n I)$ is one-dimensional for all $n=0,1,2,3,\cdots$. You can prove there is no continuous spectrum based solely on the fact that the normalized eigenfunctions $\{\varphi_n \}$ of $H$ form a complete orthonormal basis, which can be proved directly. The conclusion is that the Harmonic Oscillator has an infinite, discrete set of possible energy levels, with the only cluster point of energy being $\infty$. There is no continuous range of spectrum corresponding to unbound states. This seems reasonable from a Physics point-of-view, and is verified with Mathematics.
To follow this up: there is always one non-trivial solution of $H\psi_{\lambda}=\lambda\psi_{\lambda}$ that is square integrable on $(-\infty,0]$ and there is another non-trivial solution, say $\phi_{\lambda}$, that is square integrable on $[0,\infty)$. $\lambda$ is an eigenvalue iff $\psi_{\lambda}$ and $\phi_{\lambda}$ are linearly dependent and, in that case,  $\psi_{\lambda}$ is square integrable on $\mathbb{R}$. So the eigenvalue equation is determined by finding $\lambda$ such that $\{ \psi_{\lambda},\phi_{\lambda} \}$ is a dependent set of eigenfunctions, which becomes a Wronskian condition. This is similar to the formalism that works for determining eigenvalues and eigenfunctions in cases where there is a left endpoint condition and a right endpoint condition to be satisfied in order to have an eigenfunction. That's why it is common to find that eigenvalues are zeros of a holomorphic function.


Compute approximate quantiles for a stream of integers using moments?

Question: migrated from math.stackexchange.
I'm processing a long stream of integers and am considering tracking a few moments in order to be able to approximately compute various percentiles for the stream without storing much data. What's the simplest way to compute percentiles from a few moments. Is there a better approach that involves only storing a small amount of data?
Comment: Do you know anything specific about the distributional properties of your stream? For example, are they, say, positive? Bounded? Any other details you can provide will be helpful. Moments are pretty easy to calculate and store for a stream. There are also previous questions here about directly estimating *quantiles* from a stream, which sounds like what you *really* are trying to do. You might search for, and look through, those.
Comment: They represent processing times, so they are positive, and mostly tightly clustered unless there is some sort of technical problem or overload in the system. I'll look for the quantile questions; they might be good enough. Still I'm curious how to go from moments to computing the value associated with an arbitrary percentile. I know storing moments is easy, it's how to use them that I don't know.
Comment: Did you see [this question](http://stats.stackexchange.com/questions/7959/algorithm-to-dynamically-monitor-quantiles)?
Answer: You don't state this explicitly, but from your description of the problem it seems likely that you're after a high-biased set of quantiles (e.g., 50th, 90th, 95th and 99th percentiles).
If that's the case, I've had a lot of success with the method described in "Effective Computation of Biased Quantiles over Data Streams" by Cormode et al. It's a fast algorithm that requires little memory and that's easy to implement.
The method is based on an earlier algorithm by Greenwald and Khanna that maintains a small sample of the input stream along with upper and lower bounds on the rank of the values in the sample. It requires more space than a collection of few moments, but will be much better at describing the interesting tail region of the distribution accurately.
Comment: Yes, this is indeed the way to go. in fact it's a little easier to get estimates of the high quantiles, especially if you're willing to tolerate error in the rank of the form $\epsilon n$ where $n$ is the total number of items, and \epsilon > 0$ is some user defined error term
Answer: There is a more recent and much simpler algorithm for this that provides very good estimates of the extreme quantiles.
The basic idea is that smaller bins are used at the extremes in a way that both bounds the size of the data structure and guarantees higher accuracy for small or large $q$. The algorithm is available in several languages and many packages. The MergingDigest version requires no dynamic allocation ... once the MergingDigest is instantiated, no further heap allocation is required.
See https://github.com/tdunning/t-digest
Comment: Also in python https://github.com/CamDavidsonPilon/tdigest


Is $\mathbb{R}$ compact under the co-countable and co-finite topologies?

Question: We know that $\mathbb{R}$ with the usual topology is not compact.

Do we know the compactness of $\mathbb{R}$ equipped with either co-finite or
  co-countable topology?

I am stuck on constructing a proof in both cases and I need help.
Proof attempt:

(Educated Guess: since no one has ever made a big deal about these
  spaces being compact, I guess they are not compact)
Let $\mathbb{R}_{co-f}$ be the reals with the co-finite
  topology. Suppose $\mathcal{U}$ is an open cover of
   $\mathbb{R}_{co-f}$. Suppose $\mathbb{R}_{co-f}$ is compact. We wish to
  derive a contradiction.
Let $U = \{U_i |i \in F, F \text{ is a finite subset of }
 \mathbb{R}_{co-f}\}$ be the finite subcover. Then since $\mathbb{R}_{co-f}$ is compact, $\bigcup_{i\in F}
 U_i = \mathbb{R}_{co-f}$
(Hmmmm....This proof is going no where)
  Take an arbitrary open set $V$, then $\mathbb{R}_{co-f} \backslash V$ is finite. Then $\mathbb{R}_{co-f} \backslash V$ must be covered by some open sets in the subcover..
Let $\{U_i| i \in I \subseteq F\}$ be the subcover that covers
  $\mathbb{R}_{co-f} \backslash V$, whch means $\{\mathbb{R}_{co-f}
 \backslash U_i| i \in I \subseteq F\}$ covers $V$. However, each
  $\mathbb{R}_{co-f} \backslash U_i$ is a finite set. A finite union of
  finite set is finite. But since $V$ is co-finite in $\mathbb{R}$,
  which is uncountable, therefore $V$ cannot be covered by finite sets.
Therefore $\mathbb{R}_{co-f}$ is not compact as claimed.

Next proof:
Claim: $\mathbb{R}_{co-c}$ is not compact.

Proof: This time take $V$ as above. Since $\mathbb{R}_{co-f}
 \backslash V$ is countable, it cannot be covered by finite open sets.
  Since $V$ is not finite, it cannot be covered by finite open sets
  either.

Can someone verify if these are correct?
Comment: $\mathbf{R}$ with co-finite is compact. $\mathbf{R}$ with co-countable is not compact. Neither of your proofs are correct.
Answer: Any set $A$ endowed with the co-finite topology is compact.
Let $\mathcal F$ be an open cover for $A$, select $F\in \mathcal F$. Let $\{a_1,a_2\dots a_n\}=\mathbb R \setminus F$ and for each $i\in\{1,2\dots n\}$ let $F_{i}$ be an element of $\mathcal F$ that contains $a_i$
Then $\{F,F_1,F_2\dots F_n\}$ is a finite subcover for $A$.

$\mathbb R$ with the co-countable topology is not compact.
Consider the sets $F_n=\mathbb R\setminus \{n,n+1\dots\}$
Clearly $\mathcal F=\{F_1,F_2\dots \}$ is an open cover for $\mathbb R$
On the other hand it has no finite subcover, because such a subcover would be of the form $\{F_{a_1},F_{a_2}\dots F_{a_n}\}$ with $a_1<a_2<\dots< a_n$.  Notice $a_n$ is in none of those sets.
Comment: Thanks you just saved my final exam
Comment: No problem, good luck with your test.
Answer: The cofinite topology is compact, while the cocountable is not.
For the cofinite, let $\mathscr U$ be a collection of opens that cover $\Bbb R$, and take a non-empty $A\in \mathscr U$. Then the complement of $A$ is finite, so for each point $x_i$ in the complement, pick a $B_i\in \mathscr U$ with $x_i\in B_i$. Then $\{A,B_1,\ldots,B_n\}$ is a finite covering of $\Bbb R$.
For cocountable, let $\mathscr V =\{A_1,A_2,\ldots\}$ with $$A_i=(\Bbb R\setminus \Bbb N)\cup \{i\}$$Then $\mathscr V$ covers the real line, but no proper subset of $\mathscr V$ does, and specifically no finite subset (a subset of $\mathscr V$ not containing $A_n$ does not cover $n$).
Answer: An  equivalent def'n of compact in terms of closed sets is: $X$ is compact iff any non-empty closed family $F$ in $X$ with  the F.I.P. satisfies $\cap F\ne \emptyset.$
Translation: A closed family in $X$ is a set of closed subsets of $X.$ And "$F$ has the F.I.P. (Finite Intersection Property )" means that any non-empty finite $G\subset F$ satisfies $\cap G\ne \emptyset.$
$\quad$1.For the co-countable topology on $\mathbb R,$ let $F=\{f_n:n\in \mathbb N\}$ where $f_n=\{x\in \mathbb N : x\geq n\}.$ Then $\quad \; F$ is  a non-empty closed family with the F.I.P. but $\cap F=\emptyset.$

For the co-finite topology on $\mathbb R,$ let $F$ be a non-empty closed family with the F.I.P. Consider the family $F^*$ of non-empty finite subsets of $F.$ For each $G\in F^*$ we have $\cap G\ne \emptyset$  (by F.I.P.), and $\cap G$ is finite (because $\cap G \subset f\in F$ for any $f\in G).$
Take any $G\in F^*$ such that the number of members of $\cap G$ is the least possible. Then $\cap F\supset \cap G. $ Because if not, then there exist $f\in F$ and $x\in \cap G$ with $x\not \in f.$ But then $G\cup \{f\}\in F^*$ and $\cap (G\cup \{f\})$ has fewer members than $\cap G, $ which is impossible.... And so $$\cap F\supset \cap G \ne \emptyset.$$ (We actually have $\cap F=\cap G$.)

Any statement about open sets has a dual statement about their complements, the closed sets. Many of the dual forms are useful in themselves.


Is CiviCRM data vulnerable to the Drupageddon bug?

Question: Would CiviCRM data have been exposed to a Drupageddon exploit if it happened before I updated the site to Drupal 7.32?
CiviCRM is in a separate MySQL database. However, the site uses Views/CiviCRM integration so all the tables in the CiviCRM database are listed in Drupal's settings.php file.
Answer: Since a potential attacker got access to the database, and through the evil php module, could execute code, everything on the same server must be considered compromised.
Comment: @Shai No, as database access means the attackers are able to turn it on.
Comment: Does it make a difference if the PHP module is turned off?
Answer: I probably would guess, yes to this one especially if you have added the civicrm db to the drupal settings file and/or share the civicrm tables in the same drupal db.
the primary reason for this is, drupal's db access layer (and code) can access the civi db the same way as the drupal db and hence any exploit in that code can be used against the civi db
lobo
Answer: To expand on Letharion's answer, any files on the server were vulnerable due to the nature of the exploit. "Arbitrary PHP execution" means server-level access is possible. https://www.drupal.org/SA-CORE-2014-005
With PHP execution you can now have back doors allowing malicious file uploads.
Per the Drupal security team PSA https://www.drupal.org/PSA-2014-003, you should consider starting on a clean server entirely.


Tomcat CORS: Preflight successful, but actual request fails with 403 forbidden

Question: My REST services are deployed under Tomcat 7.0.64 (http://localhost:8080/xxx). I invoke these services from using a JavaScript library sourced by HTML pages. These HTML pages are served from another orgin (http://localhost:9090/html/yyy.html).
To enable cross origin requests, on server, I have configured CORSFilter in web.xml as follows:
<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,PATCH,DELETE</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,X-CUSTOM1,X-CUSOM2,X-CUSTOM3</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials,X-CUSTOM3</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.preflight.maxage</param-name>
        <param-value>10</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

From following output from RequestDumper, you can notice that preflight request from browser has received successful response(200). However, the actual request that followed failed with 403 Forbidden:
Preflight Request and Response
http-apr-8080-exec-6 ===============================================================
http-apr-8080-exec-8 START TIME        =26-Sep-2015 21:28:53
http-apr-8080-exec-8         requestURI=/xxxx/zzzz
http-apr-8080-exec-8           authType=null
http-apr-8080-exec-8  characterEncoding=null
http-apr-8080-exec-8      contentLength=-1
http-apr-8080-exec-8        contentType=null
http-apr-8080-exec-8        contextPath=/xxxx
http-apr-8080-exec-8             header=host=localhost:8080
http-apr-8080-exec-8             header=connection=keep-alive
http-apr-8080-exec-8             header=pragma=no-cache
http-apr-8080-exec-8             header=cache-control=no-cache
http-apr-8080-exec-8             header=access-control-request-method=POST
http-apr-8080-exec-8             header=origin=http://localhost:9090
http-apr-8080-exec-8             header=user-agent=Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.42 Safari/537.36
http-apr-8080-exec-8             header=access-control-request-headers=x-custom1, x-custom2
http-apr-8080-exec-8             header=accept=*/*
http-apr-8080-exec-8             header=referer=http://localhost:9090/html/yyyy.html
http-apr-8080-exec-8             header=accept-encoding=gzip, deflate, sdch
http-apr-8080-exec-8             header=accept-language=en-US,en;q=0.8,ta;q=0.6
http-apr-8080-exec-8             locale=en_US
http-apr-8080-exec-8             method=OPTIONS
http-apr-8080-exec-8           pathInfo=null
http-apr-8080-exec-8           protocol=HTTP/1.1
http-apr-8080-exec-8        queryString=null
http-apr-8080-exec-8         remoteAddr=127.0.0.1
http-apr-8080-exec-8         remoteHost=127.0.0.1
http-apr-8080-exec-8         remoteUser=null
http-apr-8080-exec-8 requestedSessionId=null
http-apr-8080-exec-8             scheme=http
http-apr-8080-exec-8         serverName=localhost
http-apr-8080-exec-8         serverPort=8080
http-apr-8080-exec-8        servletPath=/zzzz
http-apr-8080-exec-8           isSecure=false
http-apr-8080-exec-8 ------------------=--------------------------------------------
http-apr-8080-exec-8 ------------------=--------------------------------------------
http-apr-8080-exec-8           authType=null
http-apr-8080-exec-8        contentType=null
http-apr-8080-exec-8             header=Access-Control-Allow-Origin=http://localhost:9090
http-apr-8080-exec-8             header=Access-Control-Allow-Credentials=true
http-apr-8080-exec-8             header=Access-Control-Max-Age=10
http-apr-8080-exec-8             header=Access-Control-Allow-Methods=POST
http-apr-8080-exec-8             header=Access-Control-Allow-Headers=content-type,x-custom1,access-control-request-headers,accept,access-control-request-method,x-custom2,origin,x-custom3,x-requested-with
http-apr-8080-exec-8         remoteUser=null
http-apr-8080-exec-8             status=200
http-apr-8080-exec-8 END TIME          =26-Sep-2015 21:28:53
http-apr-8080-exec-8 ===============================================================

Actual Request and Response - That failed with 403 Forbidden
http-apr-8080-exec-9 START TIME        =26-Sep-2015 21:28:53
http-apr-8080-exec-9         requestURI=/xxxx/zzzz
http-apr-8080-exec-9           authType=null
http-apr-8080-exec-9  characterEncoding=null
http-apr-8080-exec-9      contentLength=0
http-apr-8080-exec-9        contentType=null
http-apr-8080-exec-9        contextPath=/xxxx
http-apr-8080-exec-9             header=host=localhost:8080
http-apr-8080-exec-9             header=connection=keep-alive
http-apr-8080-exec-9             header=content-length=0
http-apr-8080-exec-9             header=pragma=no-cache
http-apr-8080-exec-9             header=cache-control=no-cache
http-apr-8080-exec-9             header=origin=http://localhost:9090
http-apr-8080-exec-9             header=x-custom1=aaaaa
http-apr-8080-exec-9             header=x-custom2=bbbbb
http-apr-8080-exec-9             header=user-agent=Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.42 Safari/537.36
http-apr-8080-exec-9             header=accept=*/*
http-apr-8080-exec-9             header=referer=http://localhost:9090/html/yyyy.html
http-apr-8080-exec-9             header=accept-encoding=gzip, deflate
http-apr-8080-exec-9             header=accept-language=en-US,en;q=0.8,ta;q=0.6
http-apr-8080-exec-9             locale=en_US
http-apr-8080-exec-9             method=POST
http-apr-8080-exec-9           pathInfo=null
http-apr-8080-exec-9           protocol=HTTP/1.1
http-apr-8080-exec-9        queryString=null
http-apr-8080-exec-9         remoteAddr=127.0.0.1
http-apr-8080-exec-9         remoteHost=127.0.0.1
http-apr-8080-exec-9         remoteUser=null
http-apr-8080-exec-9 requestedSessionId=null
http-apr-8080-exec-9             scheme=http
http-apr-8080-exec-9         serverName=localhost
http-apr-8080-exec-9         serverPort=8080
http-apr-8080-exec-9        servletPath=/zzzz
http-apr-8080-exec-9           isSecure=false
http-apr-8080-exec-9 ------------------=--------------------------------------------
http-apr-8080-exec-9 ------------------=--------------------------------------------
http-apr-8080-exec-9           authType=null
http-apr-8080-exec-9        contentType=text/plain
http-apr-8080-exec-9         remoteUser=null
http-apr-8080-exec-9             status=403
http-apr-8080-exec-9 END TIME          =26-Sep-2015 21:28:53
http-apr-8080-exec-9 ===============================================================

I am using Chrome as my browser.
I am wondering, when a preflight request is successful, is it possible for the actual response to get 403 forbidden?

Also please note that I have tested sending this same request from
  Chrome plugin Postman and I could get the expected response
  successfully without 403 error.

I went through the flow given in: Tomcat CORSFilter flowchart. I am not clear as what is going wrong here. Appreciate your help in solving the issue. Thanks.
Comment: I've tried logging with tomcat in wso2 das 3.10 , but I failed.
log4j.properties:org.apache.catalina.filters=DEBUG

What's your logging settings?
Answer: I had encountered the exact same issue. The solution was quite simple actually.
"There I noticed that the HTTP POST requests are somehow required to have the Content-Type HTTP header filled."
Try adding a Content-Type to your POST request.
Answer: To add onto this answer, the most likely reason for this working in Postman but not in the browser itself is that Postman is probably automatically adding the Content-Type to the request.


Unable to ssh with fedora

Question: I'm new do Fedora and when ever I install the operating systems I am never able to ssh. Whenever I do something like  ssh [email]firstname.lastname@example.com[/email] , I get this error Could not resolve hostname github.com: Name or service not known.
I'm able to  do 'host github.com' and do 'ping github.com'
Both respond as you would expect with the ip.
Comment: Can you please post the output of ssh -v and the full command you are trying to try?
Comment: [anarr@localhost ~]$ ssh -v
OpenSSH_5.6p1, OpenSSL 1.0.0d-fips 8 Feb 2011
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-e escape_char] [-F configfile]
           [-I pkcs11] [-i identity_file]
           [-L [bind_address:]port:host:hostport]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-R [bind_address:]port:host:hostport] [-S ctl_path]
           [-W host:port] [-w local_tun[:remote_tun]]
           [user@]hostname [command]
Comment: [anarr@localhost ~]$ ssh email@example.com
ssh: Could not resolve hostname github.com: Name or service not known
[anarr@localhost ~]$
Comment: can you show us the output of iptables -L? pretty weird if you can ping the hosts (and it responds) but you can't access it..
Comment: Also, can you please post the line from /etc/nsswitch.conf that starts with hosts, plus the current content of /etc/hosts
Comment: #hosts:     db files nisplus nis dns
hosts:      files dns
Comment: Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     icmp --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Comment: Do you have selinux enabled? Run 'getenforce'.
Comment: getenforce says ENFORCING
Answer: Your ssh may try to resolve IP6 and time out doing this. If you are not using IP6 try disabling IP6 in /etc/ssh/ssh_config by changing AddressFamily from 'any' to 'inet'.

Unable to ssh with fedora


Alternative ways of notating this example of metric modulation

Question: At 3:08 Seconds into this video (Johnny Winter, Mama talk to your daughter, Live CPH 1971):

a hemiola cross-rhythm effect, and the guitar strums and bass temporarily mark out a skipple (aka. 'shuffle'/'triplet groove'/'swing') rhythm( )
How could I notate this cross-rhythm so that it can be read intuitively by the performer?
Comment: Doesn't seem to have changed tempo at all. The push makes it feel different, but the speed is the same - to me.
Comment: Generally this is notated the same way you would a triplet - but rather than -3- you use something like -4-. Most music notation programs have a "tuplet" creation tool. You can also notate it with dotted notes and ties, which is probably more common and legible in this case.
Comment: I don't understand why there was a down vote for this question.  This query is not an analysis of a particular piece, but rather using the music as an example concerning metric modulation.
Comment: @DaleNewton Well I certainly hope that isn't true because that would be a downvote for the wrong reason. I had to listen to the clip about two dozen times to hear it as a hemiola - the inconsistent tempo immediately made me think 6/8 as well. Even though you were a little mistaken with what you heard, your questions was (and is) still very valid.  I hope you found my answer helpful.
Comment: Not familiar with this piece, but it feels like a hemiola to me? The underlying pulse seems the same.
Comment: Can anyone qualify 'skipple'? A new one on me!
Comment: @Tim:  Skipple is the term Wayne Chase uses ('How Music Really Works' Roedy Black Publishing) for the blues shuffle/triplet groove/swing/etc pulse because these terms each have their own connotations and end up being less than ideal descriptors. Seems it's not a recognised term, but in the absence of an alternative I use his term for it.     https://www.youtube.com/watch?v=J-vhdGQjqNQ
Comment: The guitar strums and bass rhythm mark out the skipple /shuffle pulse.
Comment: @jjmusicnotes:  As no explanation was given by the down-voter, I still don't know for sure if this was the reason for the down-vote either, but  originally I did miss-hear the change of tempo/metric modulation as  ← half-note = dotted quarter-note → and have since edited the post. The tempo is a little shaky at the change and it threw me. Unfortunate that oftentimes down-voters aren't compelled to provide any reason for down-voting, as the generic info which pops up (poorly researched, not useful, non-sensical) isn't really much help.
Comment: @jjmusicnotes : Yes, thanks - I'm just chewing over your answer below now. When you say 6/8 you mean (8 x eighth-notes pre-change) = (6 x eighth-notes post-change) right?
Comment: @DaleNewton 6/8 refers to the time-signature of the perceived modulation, but yes, coincidentally, I also mean that I heard 8ths in 4/4 move to 8ths in 6/8. Apart from the tempo fluctuations, it's misleading because their 4/4 is actually 12/8, and the "hemiola" rhythm is a very common rhythm in compound meter (dotted 8th -> 16th -> 8th).
Comment: @jjmusicnotes yes I can hear the closeness of those perceived eighths. Perhaps as listeners we automatically give Johnny boy the benefit of the doubt and assume the fluctuation is because he means it. Or maybe maybe Winters saw all this coming and he's just playing with us.  If so mission accomplished.
Answer: You can't really talk about metric modulation without discussing Elliot Carter, a master metric modulator (say that three times fast!)
I agree that the passage discussed in the clip is a hemiola, but not for the discussed reasons.  Much like a tonal modulation, metric modulations are only considered so if you stay where you're going.  For example, if John Winter turned those half-note triplet hemiola into dotted quarter-note pulse, and stayed in 6/8 for the rest of the section, then yes, you could identify that as a metric modulation.
However, the question was not whether or not the clip contained a metric modulation, but how to notate one.
View this excerpt from an Elliot Carter piece:

Looking at the modulation from 7/8 to 2/4, you see very clear notation.  Carter shows the unit beat subdivision equivalency and qualifies it with a tempo marking (bpm).  To be absolutely clear, he also used arrows to indicate that the quarter tied to dotted-eighth only belongs to the 7/8 measure while the quarter note only belongs to the 2/4 measure.  This method is the clearest way to notate metric modulations.
This method is also discussed in two of the most prominent books on music notation: Kurt Stone's Music Notation in the 20th Century as well as Elaine Gould's Behind Bars.
Comment: So in this case , even though the new rhythm lasts a good few measures it generally wouldn't be considered a **modulation** as it doesn't last for at least the remainder of the section?
Comment: @DaleNewton Yes, you're exactly right; I know it seems finicky, but think about it in terms of pitch. You couldn't justify a tonal modulation that only lasted 2-3 measures - you'd call it a tonicization. If the new "key" stayed for the whole verse, then yes, the modulation represents a dramatic shift in tonality.  Metric modulation uses unit subdivision to pivot the very pulse of the music and remain there (much like composers use pivot chords to connect similar keys). Since the song only uses the effect for about 2 measures at most (at any given time), it's not a *true* modulation.
Comment: Yes I sometimes see the threshold for a tonal modulation given as one complete melodic or 'structural' phrase. That seems the least arbitrary to me so I go with it. For a metric/tempo modulation rather than just a temporary change of meter a complete 'section' seems as good a criteria as any to me. Perhaps where a section begins and ends could itself sometimes be up for grabs though? –
Comment: From which piece is the excerpt?
Answer: If I'm understanding correctly, you want to tell people that the speed is reducing to to 0.75 of what it was, though in this piece, I feel more of a hemiola (cross rhythm) effect than an actual modulation.
The way to notate tempo modulations is to use either the beat or the largest division or subdivision of the beat that is as simple as possible.
In this case, I would say that you're changing a single triplet eighth note into a sixteenth note in the new tempo. There are 4 triplet eighths in the old time equal to one quarter note in the new time. Therefore, if you picture the triplet eighth as being equal to the sixteenth, you should be in the correct meter with the least "huh?" going on.
In any case with complex tempo modulation, I would suggest giving approximate markings for the initial run through and make your intention clearer. If you put a ♩ = c. 104 on the main part (tempo pulled out of the air, not related to the song), then you could put ♩ = c. 78 on the new tempo. Put this along with the exact modulation marking (duration = duration) to lower the bar to understanding.
Answer: Just adding to the other answers i would say one could feel this is not a metric modulation and even not and Hemiola. This is a lot subjective so i'm just adding how i listen to it because it's different than the previous answers (which are also valid and solid interpretations).
The idea that starts at 3:08 had already appeared in 2:51 as a kind of rhythmic break. So when this starts on 3:08 it might just sound like a prolonged and repetitive iteration of that same break. It kind of creates tension because it creates a expectation of a return not only to the previous metric but to the previously ongoing musical ideais.
Answer: How could I notate this cross-rhythm so that it can be read intuitively by the performer?
The rhythm being played is actually neither a hemiola nor a cross-rhythm. The entire band places heavy emphasis on the "ands" of beats two and four. This gives the impression of shifting the pulse, but the drummer keeps the basic (back-)beat throughout.
The rhythm would be notated this way (with repeat signs just to keep the example compact.)
<code>X:1
T:Mama...
K:perc stafflines=1
M:4/4
L:1/8
[V:V1 stem=up]B- [|: B2 z B-B2 z B-:|]
</code>
Had the drummer dropped the basic beat and then the band were to have established the offbeat pattern as the new primary beat, the meter would stay the same, but the overall effect would be as if they'd dropped half a beat somewhere.
Comment: V2, while technically correct, obfuscates the division of the division of the bar into two havres, and goes against standard notational practice. A sight-reader would have no problem with v1, but they'd probably stumble over v2.
Comment: @PiedPiper And 2.5 years later, I finally updated this. Thanks for the comment.


Como abrir Pop Up automatico?

Question: Tenho o seguinte codigo de modal

Clique

Análise fiscal?

O status de "Análise Fiscal" prestado pela transportadora significa que sua encomenda foi retida pela Receita Federal para que os mesmos confiram informações constantes na nota fiscal, e verificarem se os impostos estão sendo pagos corretamente, devido às diferenças tributárias de cada estado.

Quando eu clico na palavra "Clique" ele abre. Como eu deveria fazer para ele abrir automaticamente quando abrir a página, sem precisa clicar em algo?
Answer: Vc pode só inverter a lógica. Deixa ele iniciar com opacity:1, e quando vc clicar no botão X para fechar vc usa o :target para colocar opacity:0

.pedido {
    margin-top: -300px;
    margin-left: 40%;
    margin-right: 40%;
    margin-bottom: 100px;
}

.teste {
    padding-top: 100px;
}

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 99999;
    opacity:1;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    /* pointer-events: none; */
}

.modalDialog:target {
    opacity: 0;
    pointer-events: auto;
}

.modalDialog>div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
}

.closeModal {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}

.closeModal:after {
    content: "\d7";
}

.closeModal:hover {
    background: #f00;
}

Análise fiscal?

O status de "Análise Fiscal" prestado pela transportadora significa que sua encomenda foi retida
                pela Receita Federal para que os mesmos confiram informações constantes na nota fiscal, e
                verificarem se os impostos estão sendo pagos corretamente, devido às diferenças tributárias de cada
                estado.

Comment: @JVEUZEBIO eu imaginei que isso poderia acontecer!!, isso acontece pq nesse seu código vc não esta "removendo" o popup da tela, vc está apenas tirando a opacidade,. Ele fica transparente, mas na verdade continua ali por cima de tudo :/.. Esse modelo de popup é meio complicado para usar mesmo. Vou pensar em algo que te ajude com essa opção, ou então vc vai ter que usar outro modelo... me da uns min
Comment: Ah legal, sim ficou mais direto. Mas resolveu meu problema, obrigado!
Comment: Funcionou, mas ao fechar não consigo clicar em nenhum local na pagina. Saberia dizer o que pode estar ocasionando isso? Utilizo a plataforma magento, estou colocando como bloco estatico e escolhendo a pagina a ser mostrada com widget.
Comment: Ah entendi, se você tiver alguma ideia de outro modelo me ajudaria muito
Comment: @JVEUZEBIO cara não vai ficar tão bonitinho com esse efeito de transição, mas se vc trocar onde está opacity:0, por display:none, e onde está opacity:1 por display:block, vc consegue o que uer. usando o display:none vc vai remover o elemento da tela, e consegue clicar no que estiver na tela, só que ele vai sumir de uma vez, e não com essa transição....
Comment: Sabe alguma maneira de esconder o #openModal da url?]
Comment: @JVEUZEBIO só da para limpar usando JS ou jQuery, e eu não manjo nada de JS. O problema é que esse modelo de popup usar o :target para setar o CSS no popup, então é por isso que ele "suja" a url. Acho que já vi coisa aqui no site sobre isso, vc vai ter que pesquisar...
Comment: Ah certo, vou dar uma pesquisada obrigado

Como abrir Pop Up automatico?


VisualSVN on Windows 2012 - how to run "svnadmin hotcopy" (getting Access is Denied)

Question: Following this as a guide:  https://stackoverflow.com/questions/33055/what-is-the-best-way-to-backup-subversion-repositories
I've tried the following commmands:
<code>svnadmin hotcopy "C:\Repositories" > "C:\BackupSVN"

svnadmin hotcopy "C:\Repositories\*" > "C:\BackupSVN"

svnadmin hotcopy "C:\Repositories\TestRepo1" > "C:\BackupSVN"
</code>
However all 3 commands result in "Access is denied"
I've tried them at an "Administrator" command prompt as well, still the same error.
SO:
How can I properly run an svnadmin hotcopy command (or even svnadmin dump) on a Windows 2012 server?  What am I missing?
Answer: Grrr...I figured it out.  Stupid default UAC on Windows 2012.

Deactivating UAC in Windows 2008 R2 was possible via running msconfig
  (for example winkey+r -> msconfig), going to the Tools tab and
  launching "Change UAC settings". There, you select "Never notify" to
  disable UAC. The same approach is still available in Windows Server
  2012, though UAC is still active after you selected "Never notify".
  You have the option to turn off UAC via registry by changing the DWORD
  "EnableLUA" from 1 to 0 in
  "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system".
  You will get a notification that a reboot is required. After the
  reboot, UAC is disabled.

CREDIT: http://social.technet.microsoft.com/wiki/contents/articles/13953.windows-server-2012-deactivating-uac.aspx
Comment: Alternatively you can just run the "svnadmin hotcopy" as Administrator (run it from cmd.exe or PowerShell that was run as Administrator). Disabling UAC is pretty drastic IMO.
Comment: What is UAC and how did you solved the UAC?
Comment: @SyedHaiderHassan - I'll update my answer with details.
Comment: @AlbertoSpelta - not sure what you are talking about.  This question was about getting the command to run properly (which I did), not about what "hotcopy" does.  Not sure why you even posted a comment here.


How many ways to get at least one pair in a seven card hand?

Question: This was the question and answer I saw:
How many different seven-card hands are there that contain two or more cards of
the same rank?
Solution:
There are C(52,7) total hands. To subtract the ones that don't have pairs, we observe
that such hands have cards of 7 different ranks, and there are C(13,7) ways to select
those. Then there are 4 choices for each card. So:
C(52,7) – C(13,7) · 4^7
But my solution was 13·C(4,2)·C(50,5), as you choose which rank is the pair (13 ways to do this), then choose which two cards are the pair out of that rank(4 choose 2), and then you choose the remaining 5 cards from the rest of the 50 (50 choose 5). But these two do not give the same number. Am I going wrong somewhere with my alternate solution?
Answer: Consider a hand which has two pairs, for example
$$\clubsuit A,\,\diamondsuit A,\,\heartsuit 10,\diamondsuit10,\,\spadesuit7,\,\spadesuit K,\,\diamondsuit 2.$$
Your method will count this hand twice:

choose ace, then clubs and diamonds, then $\heartsuit 10,\diamondsuit10,\,\spadesuit7,\,\spadesuit K,\,\diamondsuit 2$; or
choose $10$, then hearts and diamonds, then $\clubsuit A,\,\diamondsuit A,\,\spadesuit7,\,\spadesuit K,\,\diamondsuit 2$.

This is why your answer is wrong.  Similarly, there will be hands which contain three pairs, and which you will count three times.
In fact, if you think about it, your method will count some hands up to nine times!


Finding the intercepts of a hyperbola and a circle

Question: as trivial as this question probably seems to everyone, I have become stuck on my attempts to solve the following question:
Given the hyperbola $y = 2/x$ and the circle $x^2 + y^2 = r^2$, what are the values of $r$ where the two graphs have $4$ points of intersection?
Now, I can do this problem easily if I simply graph out both equations and then find the closest position of the hyperbola to the origin (In this case it's $(\sqrt{2},\sqrt{2})$. The answer is $r > 2$. But when I try to solve the two equations simultaneously I can't do it. Would anyone be able to show some possible working out to find the answer with this method.
Many thanks,
Etched
Answer: substitute $y=\frac2{x}$ into $x^2+y^2=r^2$
$$x^2+\frac{4}{x^2}=r^2$$
$$x^4-r^2x^2+4=0$$
$$x^2= \frac{r^2\pm\sqrt{r^4-16}}{2}$$
If the discriminant is positive, $x^2$ take $2$ distinct positive values and hence $x$ takes $4$ distinct values.
$$r^4>16=2^4$$
Hence $r>2$ or $r<-2$. If we are told that $r$ is positive (as it represents the radius), then $r>2$.
Comment: Geez it's so obvious now :P. Thanks so much!


How to restrict access to files to group members?

Question: I have a chat app where users can send photos in private or group chats. Each private or group chat has a unique chat id: /images/<chat id>/image.jpg
How would one secure the access to this files so that only the chat members can view them? In the Firebase database I have a node with a structure like: /members/<chat id>/member1: true.
Is this actually necessary, since the links are only posted to the corressponding chats?
Can any authed user actually browse through the files saved in the Firebase storage? Or is this prevented by design?
Answer: The eternal question. It's discussed a few places (Google Group, Storage Docs, Github Gist), but the TL;DR is: at present, there's no way to read data from one service in the Rules of another. For services, you can do one of two things:

Convey group information in a custom token
Convey group information in custom metadata in the service

One example of this:
// Allow reads if the group ID in your token matches the file metadata's `owner` property
// Allow writes if the group ID is in the user's custom token
match /files/{groupId}/{fileName} {
  allow read: if resource.metadata.owner == request.auth.token.groupId;
  allow write: if request.auth.token.groupId == groupId;
}

Comment: Linked gist file is not available anymore unfortunately.
Comment: Well, what do you do if a user is allowed to belong to multiple groups?
Comment: Then I usually recommend a solution like in the linked Gist where the ownership information is added to each file vs the user token.
Answer: You can now access the Firebase Firestore database from your Firebase Storage secturity rules as announced here. https://firebase.blog/posts/2022/09/announcing-cross-service-security-rules
Comment: This is not a valid answer. A link can become invalid over time. Besides that, you should provide an answer, that delivers a solution within the answer itself and add links for reference (if needed). Consider to edit your answer in this regard.


Showing this approximation holds

Question:
We see from the formula $(1+t)^2=1+2t+t^2$ that for small $t$, we have the approximate equality $$(1+t)^2\approx 1+2t$$ hence for small $u$, we have $$\sqrt{1+u} \approx 1+\frac u2$$

I know that I could get that second approximation using the Taylor series, but this book implies that it follows directly from the first approximation.  I don't see how.  Could something explain how we can see that $$(1+t)^2\approx 1+2t \implies \sqrt{1+u} \approx 1+\frac u2$$
Comment: It is imperative to quantify what $\approx$ means before performing any rigorous proof.
Comment: See [binomial series](https://en.wikipedia.org/wiki/Binomial_series).
Answer: Let $u = 2t$ (so: $t = \frac{u}{2}$), substitute into the first approximation, square root both sides, and then flip the sides.

Showing this approximation holds


Simple variance question: variance of the whole expression when one variable is random

Question: A very simple question about the variance!
I'm interested in the variance of an expression with a random variable inside it.
For an expression of this form:
$a = \sum_{i=1}^{m}(x_i \cdot y_i - z_i)$
where $y_i$ is a random variable with an expectation $\mathbb{E}(y_i)$, would the expectation of the whole function simply be:
$\mathbb{E}(a)=\sum_{i=1}^{m}(x_i \cdot \mathbb{E}(y_i) - z_i)$
Since variance is $Var(a)=\mathbb{E}(a^2)-(\mathbb{E}(a))^2$, I assume I can simply plug this expression (if correct) into this variance formula. Is this correct?
Thanks!
Answer: If $x_i$ and $z_i$ are deterministic constants for each $i = 1, \ldots, m$, and $m$ is also a known constant--that is to say, $y_i$ for $i = 1, \ldots, n$ are the only random variables involved, and they are independent--then the variance of $a$ is better calculated as $$\operatorname{Var}[a] \overset{\text {ind}}{=} \sum_{i=1}^m x_i^2 \operatorname{Var}[y_i].$$  This is because $z_i$, being deterministic, has zero variance.  If the $y_i$ are not independent, then the variance of $a$ will require knowing the covariances between each $y_i$, $y_j$ for $1 \le i \ne j \le m$ in addition to the variances of each $y_i$.
Comment: Aha, I wasn't aware of the rule about constants being squared in the variance! Thanks. I'm still learning ;)


Salvar configurações do aplicativo

Question: Existe algo que eu possa fazer para salvar configurações do meu aplicativo sem precisar criar uma base de dados, para quando o aplicativo for fechado e depois reaberto ele continuar com as configurações que foram gravadas anteriormente?
Comment: Se uma das respostas resolveu o seu problema, você pode escolher a que melhor resolveu e aceitá-la, veja [aqui](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema.
Answer: Aqui tem o que tu precisa: https://developer.android.com/guide/topics/data/data-storage?hl=pt-BR
Para obter um objeto SharedPreferences para o aplicativo, use um destes dois métodos:

getSharedPreferences() — use esse método se precisar de vários
arquivos de preferência, identificados por nome e especificados no
primeiro parâmetro.
getPreferences() — use esse método se precisar de apenas um arquivo
de preferência para a Activity. Como esse será o único arquivo de
preferências para a Activity, o nome não é fornecido.

Para gravar valores:

Chame edit() para obter um SharedPreferences.Editor.
Adicione valores com métodos como putBoolean() e putString().
Confirme os novos valores com commit()

Para ler valores, use métodos de SharedPreferences como getBoolean()
   e getString().
Exemplo:
public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}

Answer: O mais simples, na minha opinião, é java.util.prefs.Preferences (documentação) que vem junto com o Java.
Uso normalmente para salvar posição e tamanho das janelas, diretório usado para abrir arquivos, ....
Obter instância (membro de cada classe):
// chaves para acessar cada dado
private static final String PREF_TEXTO = "ChaveTexto";
private static final String PREF_INTEIRO = "ChaveInteiro";

private final Preferences preferences = Preferences.userNodeForPackage(getClass());

Salvar:
preferences.put(PREF_TEXTO, texto);
preferences.putInt(PREF_INTEIRO, numero);

Recuperar:
texto = prefrences.get(PREF_TEXTO, "valoe inicial");
numero = preferences.getInt(PREF_INTEIRO, 0);

Além do userNode, que vale para um determinado usuário, existe o systemNode que vale para todos os usuários.

Salvar configurações do aplicativo


Cache tags for all entities of a certain type

Question: I understand how you can add cache tags to a custom query for a particular entity id (or list of them) but is there a way to add cache tags that will invalidate a query if any entity of type FOO is updated/added/deleted?
Comment: See https://www.drupal.org/project/drupal/issues/2145751 for the core issue to add it.
Answer: You could use the module handy_cache_tags, then you would have this type of tags:
handy_cache_tags:[entity_type]
handy_cache_tags:[entity_type]:[entity_bundle]

Answer: In your blockcache_examples.module file:
use Drupal\Core\Cache\Cache;
use Drupal\node\Entity\Node;

/**
  * Invalidate the custom tag if entities of type "page" get updated
  */
function blockcache_examples_node_update(Node $entity) {
  if($entity->getType() === 'page') {
    Cache::invalidateTags(['blockcache_examples_page_updates']);
  }
}

/**
  * Invalidate the custom tag if entities of type "page" get inserted
  */
function blockcache_examples_node_insert(Node $entity) {
  if($entity->getType() === 'page') {
    Cache::invalidateTags(['blockcache_examples_page_updates']);
  }
}

/**
  * Invalidate the custom tag if entities of type "page" get deleted
  */
function blockcache_examples_node_delete(Node $entity) {
  if($entity->getType() === 'page') {
    Cache::invalidateTags(['blockcache_examples_page_updates']);
  }
}

In your src/Plugin/Block/MyBlock.php (or controller, whatever):
/**
 * Only when node(s) of type 'page' are updated/insert/deleted. See .module file
 */
public function getCacheTags() {
  return Cache::mergeTags(parent::getCacheTags(), array('blockcache_examples_page_updates'));
}

Source: this video explaining block caching


If I just change the lyrics and flow (very slightly) of a song is it called a cover or a remix?

Question: Is it referred as to something else? Like my version of a song or tribute.
Answer: If you play and sing it yourself, then it's a cover. If you merely use editing tools to change it around, then it's a remix. A remix generally doesn't include a new performance or recording, it's merely editing and changing what has already been recorded.
A cover is a new recording or performance of a song written by someone else, or sometimes it's a new recording or performance of a song originally performed and/or recorded by someone else, regardless of who wrote it.
A tribute song is an original song, likely in the style of the band or artist that it is a tribute of. A tribute band is a band that performs and/or records several covers all originally written/performed/recorded by the same band. Tribute bands usually also dress up like the bands they are tributes of, and may even replicate stage elements, etc.

Note that covers and remixes require a license from the copyright holder or else they are usually infringing on that copyright. For a live performance of a cover or remix, smaller venues often pay a blanket licensing fee. For larger venues, the act performing the cover (you, in this case) may have to pay the fee directly. Copyright holders can refuse to license their songs for public performance (if I'm not mistaken), but cannot refuse to license their songs for recording. This is called "compulsory licensing", which means you must be allowed to record the song, but the copyright holder can charge you a reasonable fee to do so. I am not a lawyer. Consult a licensed attorney before doing anything with legal ramifications.
Comment: @Kite What are you recording? If you're recording yourself rapping, then that's a cover. The recording is of a performance, even if it's not a public performance.
Comment: @Kite Yes, that's a cover.
Comment: Ah I see so since this is rap and I'm not performing just recording I would assume this is a remix then correct?
Comment: @Kite As my second paragraph says, if you record new material, especially if you record a new vocal track, then it's a cover.
Comment: Yes the only changes to the song Is my voice and few different lyrics everything else is the same. As for the copyright I don't plan to release this in any form it's more for experimentation to keep to myself I was just wondering whether it was called a remix or cover.
Comment: You might add a note about satire/parody:  if you make significant changes to the lyrics with humorous intent, you are exempt from all copyright law.  Because it's parody, use of the original tune is allowed.
Comment: @CarlWitthoft I'm not personally aware of that being the case so I'm not going to assert it. I understand that in the past, whether something is parody has often been decided in the courts, since the law is not precise on that matter, and even going to court is expensive. So generally I would prefer to get permission/license for any use of another's work.


Definition of $L^p(\Omega ; H)$?

Question: I am not sure I understand the definition of the space $L^p(\Omega ; H)$. I am studying Malliavin Calculus, and the derivative operator $D$ is said to be closable from $L^p(\Omega)$ to $L^p(\Omega,H)$. $H$ being a real separable Hilbert Space.
I understand that $L^p(\Omega)$ is the set of random variables $X$ such that
$$ \left(\int_\Omega| X(\omega)|^pd\omega\right)^{\frac{1}{p}} < \infty $$
but i don't understand what is $L^p(\Omega ; H)$.
Thank you for your answer!
Answer: If $F \in L^p(\Omega)$ and $F=f(W(h_1),\cdots, W(h_n))$, with $h_i \in H$ and good conditions on $f$, then
\begin{align}
DF= \sum_{i=1}^n \partial_if(W(h_1),\cdots, W(h_n))h_i
\end{align}
$F$ is a real valued random variable and $DF$ takes its value in $H$. So here $L^p(\Omega, H)$ are all $H-$valued random varaible $Y$ such that $\int_{\Omega}||Y(\omega)||^p_H d\omega <+\infty$, where $||\cdot||_H$ is the norm in $H$

Definition of $L^p(\Omega ; H)$?


When learning a piece, should I try to understand things beyond the notes?

Question: I'm a senior novice at the piano, I have an understanding of rhythm, note values, pitches and their positions, and major and minor scales. I like classical pieces and play comfortably in a relatively slow manner. I have learned many ideas about sight reading and would like to get fairly good at it.
When I play a piece, I do so without an understanding of things beyond the basic notes. In other words, I memorize a piece and play it note by note.   What on a higher level should I be thinking about as I play through a piece such as Bach's Minuet in G major or his Minuet in G minor?
Answer: Well, beware of over-thinking!  Always a pitfall for the adult student who prefers to analysis to the steady plod of sustained practice.
But you could consider the structure of this simple piece. A 2-bar melodic fragment, repeated 'upside down'.  Another three variants of the first half of the theme lead us to a resting point ('cadence')  with an echo of it in the left hand taking us into a repeat with a modified ending - a more final cadence.  The first, 'half-way' cadence rests on the dominant chord (D) and is called an 'imperfect cadence'.  The second 'perfect cadence' takes us home to the tonic (G). (I've seen regional variations in naming these cadence types.  But they refer to the same idea.)
Then we set off in the dominant key (D), with an imperfect cadence in THAT key at bar 20 (resting on the chord of A major - using a C# accidental not in the key signature of the overall key, G major), reaching a perfect cadance in D major at bar 24.  But that D chord immediately has a C natural added to it, making it D7, the dominant of...  yes, our home key G major!   8 bars in that key, still using variants of the melody and rhythms of the opening few bars, and Bach wraps it up.
So, development of a simple musical theme.  A key structure that takes a trip to the dominant then comes home.   We're well on the way towards Sonata Form, the backbone of the 'classical' period.   Have a look at Beethoven's F minor Sonata, op. 2 No. 1.  It's too hard for you to play yet, but it's an excellent demonstration of Sonata form, using basically the same methods as Bach does in the Minuet in G.
Answer:
What on a higher level should I be thinking about as I play through a piece such as Bach's Minuet in G major or his Minuet in G minor?

Once you have the muscle memory of a piece down, there's an important component of music that can often be overlooked by musicians who like to think: the emotion.
One good goal for learning a piece of music is to get it to the point where the playing of it is so automatic that you transcend the concept of playing it correctly and are able to focus on playing it with feeling. Listeners want to feel something, they (almost all of them) are not looking at how many mistakes you make or whether you understand structure, forms, or theory. They want to feel something.
Each piece of music (in any genre) has one or more emotions "encoded" into its composition, and when a piece is performed, the musicians can, and usually should, both interpret the inherent emotions and also communicate their own take and feelings that they are inspired to feel when they hear or play the piece.
So when you have mastered a piece in the technical sense, the next step is to think about how the piece makes you feel, what it reminds you of, what kind of emotional conversation is started inside you when you play it or hear it. Then, your goal is to continue that conversation. Some musicians attempt to relay their best guess at the original intended emotion(s) only, others add a little or a lot of their own take on things, and some even work to subvert the original intent and use the raw material to convey something very different.
When you are engaging in an emotional conversation with the composer and the audience, that is when you are truly making music.
Answer: You might want to try to dig into music theory and understand 'how those pieces work' - modulation, alterations etc. This is a technical part of Bach (and any composer) mastery.
Another interesting part could be to understand a semantics of Bach's music. There are several folks who investigate leitmotifs in Bach's music. Albert Schweitzer was the first. Then Bodki and Boleslav Yavorsky. For instance, and this could be interesting for you, the piece you play (I expect #7 from Anna Magdalena) is based on arpeggios. This texture is commonly accepted as a musical descriptive of angels. Therefore, we can reveal the Annunciation background of the piece.
Comment: Do you mean leitmotifs, or just motives? By "Leitmotiv," we typically mean Wagner or later; if someone extends the concept of Leitmotiv earlier, they usually only go as early as Weber or so.
Comment: In your terms, it is definitely motifs. But if we use the definition of leitmotif as a repeatedly used motif to express the same or close ideas, then those could be cold leitmotifs. If we don't like it, we can say 'rhetoric figures', as Bach's art of fugue follows the same principles of parts interaction as in rhetorics. Some examples of those rhetoric figures: notes B-A-C_H - usually represents a cross and crucifixion; tetrachord up is an assertion of faith, arpeggio on tonics - angels; if the notes line forms a shape of the letter M - symbol of Maria, Stabat Mater etc. See Schweitzer.


How can I get (x, y) of an object in Android Studio which has been rotated?

Question: I am working on a game in Android Studio which has an object rotating around the center of the screen. My problem is that for some reason after rotating the object the x and y position have stayed the same(I am guessing because since the canvas is rotating it still has the same points in that canvas). I need the x an y coordinates in order to calculate collision detection. After realizing the x and y did not change I attempted to write a function which would calculate the x and y using basic trig but it was spitting out strange values for some reason(also attached below). My question is how do I find the x and y position of this object in the main canvas? The code is below.
private int x;
    private int y;

    private int rotate;
    private int width;
    private int height;

    private int color = Color.rgb(226, 255, 243);

    private Paint paint = new Paint();

    public Player(){
        rotate = 0;
        width = Constants.width / 10;
        height = Constants.height / 50;
        x = Constants.width / 2 - width / 2;
        y = Constants.height / 2 + Constants.height / 8;
    }

    public void setRotate(int rotate){
        this.rotate = rotate;
    }
    public int getRotate(){return rotate;}

    public int getX(){return x;}
    public int getY(){return y;}
    public int getWidth(){return width;}
    public int getHeight(){return height;}

    public void update(){
        if(rotate >= 360){
            rotate = 0;
        }
    }

    public void draw(Canvas canvas){
        paint.setColor(color);

        canvas.save();
        canvas.rotate(rotate, Constants.width / 2, Constants.height / 2);
        canvas.drawRect(x, y, x + width, y + height, paint);
        canvas.restore();
    }

The code below is my attempt at finding the x and y coordinates but it only spits out strange values and I cant find the problem. This code is my main class.
        private int getPlayerX(int rotation){
        double angleA;
        double angleC;
        double sideC;
        double sideA;

        angleA = 180 - ((180 - rotation) + 90);
        sideC = Constants.width / 2 + Constants.height / 8;
        angleC = 180 - rotation;

        sideA = ((Math.sin(angleA) * sideC)) / (Math.sin(angleC));

        playerx = Constants.width / 2 + (int) sideA;

        return playerx;
    }
    private int getPlayerY(int rotation){
        double sideC;
        double angleC;
        double angleB;
        double sideB;

        sideC = Constants.width / 2 + Constants.height / 8;
        angleC = 180 - rotation;
        angleB = 90;

        sideB = sideC * (Math.sin(angleB)) / (Math.sin(angleC));

        playery = Constants.height + (int) sideB;

        return playery;
    }

Comment: use `android.graphics.Matrix` API
Comment: It rotates the object but still keeps the x and y in the same place, just like with the canvas.rotate(); function.
Comment: what do you want to achieve actually?  rotate the canvas,  then draw something, then ...?
Comment: did you try Matrix#map* methods?
Comment: I was trying to rotate the object around the center and then find the new x and y points after the rotation. I was finally able to do it with the Matrix Map methods. Thanks a lot!!!
Comment: btw, you dont need `canvas.rotate`, instead rotate your `Matrix`, then call `Canvas#concat`, then draw your stuff
Answer: Try to look to matrices. This is the better practice to define transformation of an object.
Look here https://en.m.wikipedia.org/wiki/Transformation_matrix
Example:
public Player(){
   //...
   //matrix 3x3 with all transformations you need
   Matrix3f m;

   void rotate(float angle) {
       Matrix3f rot = new Matrix3f();
       rot.data = {cos(angle), -sin(angle), 0.0,
                   sin(angle), cos(angle), 0.0,
                   0.0,        0.0,        1.0 }
       m.Multiply(rot);
   }

   //get the world position of a local point
   vec2f getWorld(vec2f inPt) {
       vec3f p = vec3f(inPt.x, inPt.y, 1.0);
       p = m.Transform(p);
       return vec2f(p.x, p.y);
   }

   //get the local position of a world point
   vec2f getLocal(vec2f inPt) {
       Matrix3f invM = m.Invert();
       vec3f p = vec3f(inPt.x, inPt.y, 1.0);
       p = invM.Transform(p);
       return vec2f(p.x, p.y);
   }

Classes Matrix3f, vec3f, vec2f with methods Transform, Invert, Multiply and so on you should provide by yourself (you can find a lot of code samples in the network)
Comment: I have been trying to implement rotations using matrices but I am still getting the same problem, the x and y position do not change, and I dont understand the code above. When I try to use it in my code I get a million and one errors???
Comment: This code is the sample of what you can do with matrices. Look to the link in my previous post and study this question by yourself. If you dont understand it by yourself nobody helps you. I believe that there are a lot of open source game engines in the network (unity for example). Try to use them. If you want to write the engine by self that is good chose but you need to learn some basic things. Matrices are one of them. Good luck. If you want i'll write the implementation of classes that i used in my previous post but i think the better way to learn the question is write it by self


Data transposition from 'clustered rows' into columns

Question: I am facing a difficult challenge, given my very low skills at text mining… Basically, I have a list of approx. 200 individuals described in a plain text file following a simple structure:

N: (name)
Y: (year of birth)
S: (sibling)
N: (name)
Y: (year of birth)
S: (sibling)
[etc.]

Here's the catch:

each individual can have missing data, in which case the line is omitted;
multiple siblings, in which case his/her entry has more than one S: line.

The only real constants in the text file are:

each individual is separated by a blank file from each other;
all lines feature the appropriate N:, Y: or S: prefix descriptor.

Is there a method, using pretty much anything from Excel (!) to Stata to R or even Google Refine or Wrangler, to turn that organised chaos into a standard dataset, by which I mean, one column per descriptor, with S1, S2... Sn columns for siblings?
If that is the wrong forum, please redirect me. I just figured that the stats crew would be the most acquainted with text mining.
Answer: Load data
Assuming fd.txt contains the following
N: toto
Y: 2000
S: tata

N: titi
Y: 2004
S: tutu

N: toto
Y: 2000
S: tata2

N: toto
Y: 2000
S: tata3

N: tete
Y: 2002
S: tyty

N: tete
Y: 2002
S: tyty2

here is one solution in R:
tmp <- scan("fd.txt", what="character")
res <- data.frame(matrix(tmp[seq(2, length(tmp), by=2)], nc=3, byrow=TRUE))

The first command read everything a single vector of character, skipping blank lines; then we remove every odd elements ("N:", "S:", "Y:"); finally, we arrange them in a data.frame (this a convenient way to make each column a factor).
The output is
    X1   X2   X3
1 toto 2000 tata
2 titi 2004 tutu
3 toto 2000 tata2
4 toto 2000 tata3
5 tete 2002  tyty
6 tete 2002 tyty2

Please note that if you have some GNU utilities on your machine, you can use awk
sed 's/[NYS]: //' fd.txt | awk 'ORS=(FNR%4)?FS:RS' > res.txt

The first command uses sed to filter the descriptor (replace by blank); then awk will produce its output (Output Record Separator) as follows:  arrange each record using default Field Separator (space), and put a new Record Separator (new line) every 4 fields. Of note, we could filter the data using awk directly, but I like separating tasks a little.
The result is written in res.txt and can be imported into R using read.table():
toto 2000 tata
titi 2004 tutu
toto 2000 tata2
toto 2000 tata3
tete 2002 tyty
tete 2002 tyty2

Process and transform data
I didn't find a very elegant solution in R, but the following works:
library(plyr)
tmp <- ddply(res, .(X1,X2), mutate, S=list(X3))[,-3]
resf <- tmp[!duplicated(tmp[,1:2]),]

Then, resf has three columns, where column S list the levels of the X3 factor (siblings' name). So, instead of putting siblings in different columns, I concatenated them in a list. In other words,
as.character(resf$S[[1]])

gives you the name of tete's siblings, which are tyty and tyty2.
I'm pretty sure there's a better way to do this with plyr, but I didn't manage to get a nice solution for the moment.

With repeated "S:" motif, here is one possible quick and dirty solution. Say fd.txt now reads
N: toto
Y: 2000
S: tata
S: tata2
S: tata3

N: titi
Y: 2004
S: tutu

N: tete
Y: 2002
S: tyty
S: tyty2

then,
tmp <- read.table("fd.txt")
tmp$V1 <- gsub(":","",tmp$V1)
start <- c(which(tmp$V1=="N"), nrow(tmp)+1)
max.col <- max(diff(start))
res <- matrix(nr=length(start)-1, nc=max.col)
for (i in 1:(length(start)-1))
  res[i,1:diff(start[i:(i+1)])] <- t(tmp[start[i]:(start[i+1]-1),])[2,]
res <- data.frame(res)
colnames(res) <- c("name","year",paste("S",1:(max.col-2),sep=""))

will produce
  name year   S1    S2    S3
1 toto 2000 tata tata2 tata3
2 titi 2004 tutu  <NA>  <NA>
3 tete 2002 tyty tyty2  <NA>

Comment: Thans for your help, especially on building the original matrix. Unfortunately, it fails because your example uses fixed width entries (NYS-NYS-NYS) while the actual file has entries with multiple siblings (NYS-NYSSS-NYS). Yes, I know…
Comment: @Fr. I added a PS (well, it's so ugly code that I have no doubt someone will come with a better one :-)
Comment: Dirty perhaps, but it worked alright! Thanks a thousand :)
Answer: Interesting question...here's a Stata-based solution (that doesnt require OS utilities like awk). My example uses the data example contributed by chl, except that I added in the data problems described by Fr. (missing years, multiple siblings, etc).
Run the code below from your do-file editor.  Note that there are some comments explaining alternatives for handling multiple siblings by reshaping the data wide.
**********************! Begin example
clear

**input dataset:
input str20(v1)
""
"N: toto"
"Y: 2000"
"S: tata"
""
"N: titi"
"Y: 2004"
"S: tutu"
""
"N: toto"
"Y: 2000"
"S: tata2"
""
"N: toto"
"Y: 2000"
"S: tata3"
""
"N: tete"
"Y: 2002"
"S: tyty"
""
"N: tete"
"Y: 2002"
"S: tyty2"
"S: tyty99"
""
"N: tete2"
"S: tyty22"
""
"N: tete3"
"Y: 2004"
"S: tytya"
"S: tytyb"
"S: tytyc"
end

**parse data/v1
split v1, parse(": ")
l in 1/7
drop v1

**create panel id
g id = _n if mi(v12)
replace id = id[_n-1] ///
     if mi(id) & !mi(v12)
drop if mi(v12)
//get max value for later//
bys id: g i = _n
qui sum i
loc max `r(max)'
rename v12 attribute
l in 1/6

**reshape data
foreach x in N Y S {
g `x' = attribute if v11=="`x'" ///
    & !mi(attribute)
    forval n = 1/`=`max'-1' {
    foreach s in + - {
bys id: replace `x' = `x'[_n`s'`n'] if !mi(`x'[_n`s'`n']) ///
    & mi(`x')
    } //end x.loop
  } //end n.loop
} //end s.loop

drop v11 attribute i
duplicates drop

**if you want multiple siblings on one line, reshape wide:
bys id N Y: g j = _n
reshape wide S, i(id) j(j)
order id N Y
li

**********************! End example


Function to copy char pointer content crashes when printing second index of copy

Question: I am having problems copying the content pointed by a char pointer to another, even though I am allocating memory to it before using strcpy. I've seen somy suggestions with strdup, but I would like to know what to do without the need of it. Here is my main code
int main (void)
{
    char word[20];
    leaftype destiny;
    while(1)
    {
        printf("\nType in a word: ");
        scanf("%s",word);
        copy_leaf(&destiny,palavra);
        if (palavra[0] == '0') break;
    }

    system("pause");

    return 0;
}

The problem I have is with the function copy_leaf:
void copy_leaf(leaftype* destiny, leaftype source)
{
    printf("\n====start of copy_leaf======\n");
    int i;
    printf("strlen of source: %d",strlen(source));
    printf("\nsource: ");
    for(i = 0; i <= strlen(source); i++)
    {
        if(i == strlen(source))
        {
            printf("\\0");
        }
        else printf("%c-",source[i]);
    }
    *destiny = malloc((strlen(source)+1)*sizeof(char));
    strcpy(*destiny,source);
    printf("\nstrlen of destiny: %d",strlen(*destiny));
    printf("\ndestiny: ");
    for(i = 0; i <= strlen(*destiny); i++)
    {
        if(i == strlen(*destiny))
        {
        printf("\\0");
        }
        else printf("%c-",*destiny[i]);
    }
    printf("\n===end of copy_leaf======\n");
}

leaftype is defined as:
typedef char* leaftype;

When I run the code having the word "example" as input, I get on the console:
Type in a word:
====start of copy_leaf======
strlen of source: 7
source: e-x-a-m-p-l-e-\0
strlen of destiny: 7
destiny: e-

and it crashes ("program.exe has stopped working etc" on Windows 7). I am using devcpp, but my file is named with C extension. Can anyone help me in fixing this char* to char* content copy? I need a function to make that because I need to copy content of one string to another many times in my C file. Thanks in advance!
p.s.: what I have already tried in copy_leaf function (desperate solutions):

changing leaftype source to const leaftype source (that'd be a const char* source)
making *destiny = strcpy(*destiny,source), as strcpy returns a pointer to the destination string
Answer: you should not use *destiny[i], but you need to use (*destiny)[i] like in this line,
    else printf("%c-",(*destiny)[i]);

BTW, destiny is a double pointer, i don't think you really need a double pointer anyway.
Comment: I'll +1 this if you explain what the difference is in a way that a novice can understand ;)
Comment: A double pointer is necessary as stated [here](http://c-faq.com/ptrs/passptrinit.html)
Answer: printf("%c-",*destiny[i]);

destiny is a char**, and [] has precedence over *.
Therefore this is interpreted as:
printf("%c-",*(destiny[i]));

when you actually want:
printf("%c-", (*destiny)[i]);

i.e. you were reading the first element of the ith pointer, when you actually wanted the ith element of the first (and only) pointer.
Answer: Why I like that?
These are the following corrections to be done.
 void copy_leaf(leaftype* destiny, leaftype source)

change to
void copy_leaf(leaftype destiny, leaftype source)

destiny = malloc((strlen(source)+1)*sizeof(char));

strcpy(destiny,source);

for(i = 0; i < strlen(destiny); i++)
    {
        printf("%c-",destiny[i]);

    }

By the way, the right prototype for strcpy should be that the source data should be always- const char *.
Comment: That changes the behavior. In the OP's version destiny is modified in the caller. You're now only modifying a local copy.
Comment: Also, the second argument to strcpy is const char*, but that means that strcpy doesn't modify the data. There's no requirement that the caller use a const char*; a char* is compatible.


Is measure theory only for integrals?

Question: I am trying to self-study probabilistic measure theory after completing my undergrad degree, and I am curious if there are more interesting applications of measure theory aside from Lebesgue integration ? It seems like (correct me if I am wrong here) measure on its own is a rich field before delving in integration of measurable functions.
Comment: One immediate example that comes to mind are Hausdorff measures which can be used to measure the (non-integer) dimension of fractals.
Comment: What do you consider "not integration"? The measure of a set is the integral of the corresponding indicator function.
Comment: A measure is how we can measure a set in general case, not only for real numbers, but the integral gives the flexibility to imagine that there is a certain "density" on the set - this is the integrand. If the integrand function, i.e. density, is unit, then the integral is just a measure.
Comment: So basically integral and measure are the same(or equivalent) concept(s) ?
@zkutch
Comment: "basically" is very subjective word,
@Pat - in mathematics I prefer to say, that integral is based on measure. It will be funny theory, if someone created reverse - it will be same as to create volume from mass. Now we based mass (integral) on volume (measure).
Comment: Ergodic Theory is based on measure theory.  See, for instance, https://en.wikipedia.org/wiki/Ergodic_theory
Answer: I would propose that the construction of measures itself can be a highly non-trivial task in measure theory, yet it is the very foundation of it.
Think of what a measure is: It is a non-negative set-function $\mu$ from some $\sigma$-algebra $\mathcal F$. This means, to define a measure we need to assign to every set $A\in\mathcal F$ a value $\mu(A)\in[0,\infty]$. But often times the $\sigma$-algebra $\mathcal F$ will be very large and involve very complicated sets (for example Cantor set in the real line). Are we really going to find some nice "formula" to define $\mu(A)$ for every possible $A\in\mathcal F$? Probably not...
This is why extension Theorems like Caratheodory's Extension Theorem are so vital: They allow us to uniquely define measures on a "complicated" $\sigma$-algebra $\mathcal F$ by only defining it on some "simpler" generating set $\mathcal C\subset \mathcal F$. This would be one example of an important piece of measure theory that is "independent" of integration.
To give another interesting example from Probability Theory, where we are not so much concerned about integration with respect to a probability measure, but rather constructing a probability measure in the first place: Consider the theory of Stochastic Processes. Often times we want the paths of such a process to be continuous (or at least cádlág), which means we are trying to construct some probability measure on the set of continuous functions $C$ (or the set of cádlág functions $D$). But how would one even try to do this? Note that now our $\sigma$-algebra consists of "function sets", i.e. sets $A\subseteq C$.
The most intuitive way to understand a stochastic process is to not look at its law over $C$, but rather at the laws of the finite-dimensional projections of it. This means, one may try to construct a stochastic process $(X_t)_{t\geq 0}\in C$ by considering the finite-dimensional projections  $(X_{t_1},\dots,X_{t_k})$ for various $t_1<\dots<t_k\in[0,\infty)$ and hope to "extend" the collection of their distributions on $\mathbb R^k$ to a distribution on $C$. Here, extension Theorems like Kolmogorov's Extension Theorem together with Kolmogorov's Continuity Theorem provide a way to do this.
Again, in the theory of stochastic processes we may not even be interested in integrating against a measure $\mu$ on $C$ (though there are certainly areas of Stochastic Analysis where this is done) but rather constructing such measures and analyzing them in some way, e.g. studying Weak Convergence on $C$. While weak convergence can be understood via integrationg w.r.t. bounded continuous function (à la Portmanteau), this approach is completely intractable for stochastic processes, hence one looks for other criterions of weak convergence, see e.g. here for an overview for continuous processes and here for an overview for cádlág processes.
Comment: *But often times the* $\sigma$-algebra $\mathcal F$ *will be very large and involve very complicated sets (for example Cantor set in the real line).* -- Since the Cantor set is closed (complement of an open set; countable intersection of open sets), it's VERY LOW for complexity in the transfinite hierarchy of elements in a $\sigma$-algebra -- level $0$ or $1,$ depending on how one begins enumerating the levels, out of $\omega_1$-many levels. More complicated are sets at various [large number](https://en.wikipedia.org/wiki/Large_numbers) levels, **(continued)**
Comment: and even more complicated sets are at various large countable ordinal levels (see [1](https://johncarlosbaez.wordpress.com/2016/06/29/large-countable-ordinals-part-1/) and [2](https://johncarlosbaez.wordpress.com/2016/07/04/large-countable-ordinals-part-2/) and [3](https://johncarlosbaez.wordpress.com/2016/07/07/large-countable-ordinals-part-3/)). That said, there are different ways of measuring complicated'ness, and so while both the Cantor set and the Mandelbrot set are closed sets, each can certainly be considered to be fairly complicated sets.

Is measure theory only for integrals?