Determine the domain of the inverse of $f(x) = 2x^2 + 8x - 7$, which is a function.

Question: Determine the domain where the inverse of $f(x) = 2x^2 + 8x - 7$ is a function.

So, I started off switching the $y$- (the $f(x)$) and $x$-value, like so:
$x = 2y^2 + 8y - 7$
Then, I plugged these values into the quadratic formula, getting:
$f^{-1}(x) = (-8 \pm \sqrt{120})/4$

First off, is the inverse written correctly (this problem is different from the others I worked on)? And second, since I have a ($\pm$) sign, does that mean there will be two different domains?
Comment: The inverse should be a function of $y$, which you've lost somewhere.
Comment: The function $f(x) = 2x^2 + 8x - 7$ is not injective (one-to-one), so it does not have an inverse function unless you restrict its domain to an interval in which it is injective.
Answer: First of all, this is an excellent example of an OP providing enough details of their attempt at solving a problem so that it's possible to give answers tailored to the OP's error or confusion. Kudos to Bibliophile for doing so.
The first step is perfectly correct. It's the second step where things go awry. It's always tempting to plug the coefficients of a quadratic polynomial, which $2y^2+8y-7$ certainly is, into the quadratic formula $-b\pm\sqrt{b^2-4ac})\over2a$.  The thing to remember is that the quadratic formula gives the solution to a quadratic equation in which the polynomial is being set equal to $0$.  That's not what we have here. Instead, we have $2y^2+8y-7$ set equal to $x$. So we first need to move the $x$ over, and only then apply the quadratic formula:
$$2y^2+8y-7=x\implies2y^2+8y-(7+x)=0\implies y={-8\pm\sqrt{64+8(7+x)}\over4}={-8\pm\sqrt{120+8x}\over4}$$
Finally, note that the problem only asks for the domain of the inverse function.  In this case, that amounts to asking where $\sqrt{120+8x}$ is a real number.  It's easy to see that the domain is $x\in[-15,\infty)$.
Remark:  The function $f(x)=2x^2+8x-7$ has an inverse only in the sense that $f(f^{-1}(x))=x$ for all $x$ in the domain of $f^{-1}$ (i.e., for all $x\in[-15,\infty)$).  Indeed, there really is no such thing as "the" inverse here: because of the $\pm$ sign in the quadratic formula, there are two natural possibilities:
$$f_+^{-1}(x)={-8+\sqrt{120+8x}\over4}\quad\text{and}\quad f_-^{-1}(x)={-8-\sqrt{120+8x}\over4}$$
Additional remark: Another way to get at the domain for the inverse here is to rewrite the quadratic $2x^2+8x-7=2(x^2+4x)-7=2(x^2+4x+4)-8-7$ to get
$$f(x)=2(x+2)^2-15$$
from which it's clear that $f(x)$ takes all values greater than or equal to $-15$, so that the domain of its inverse is $[-15,\infty)$.
Answer: So that a function admits an inverse it should be monotone in the range. Let's find where your function is monotone:
$$f'(x) = 4x + 8 = 0$$
then at $x = -2$, you have a local extrema. So, at $]-\infty,-2]$ we have an inverse. And at $]-2,\infty[$ we also have an inverse. It happens to be that the range of $f(x)$ (consequently the domain of the inverse) is the same in both domains of $f(x)$, which is $$[f(-2),f(+\infty)[=[-15,+\infty[$$
Answer: First, your calculations are incorrect. We have
$$
f(x) = 2x^2 + 8x -7
$$
set $y = f(x)$ and solve for $x$.
$$
y = 2x^2 + 8x - 7 \Leftrightarrow
2(x+2)^2 = y + 15 \Leftrightarrow
x = -2 \pm \sqrt{\frac{y+15}{2}}
$$
So the inverse is $f^{-1}(x) = -2 \pm \sqrt{\frac{x+15}{2}}$
In order for this to be a function, we must have that:
for every $x$ we can only obtain one $y$. With the $\pm$ this is not the case.
It turns out that the $-2 + \sqrt{\frac{x+15}{2}}$ corresponds to those $x$ which are to the right of the extrem point in the range of $f(x)$ and $-2 - \sqrt{\frac{x+15}{2}}$ corresponds to those $x$ which are to the left of the extrem point in the range of $f(x)$. I think the easiest way to see this is by looking at the mirror image of $f(x)$ in the line $y=x$ graphically.
Comment: I think instead of $$2(x+2)=y+15$$ you should have $$2(x+2)^2=y+15$$
Comment: Correct, I've edited. @Crosby
Answer: Let $a>0$ and $f(x)=ax^2+bx+c$. There is
$$
\varphi:  \left[\frac{-\Delta}{4a},+\infty)\right) \to\left(-\infty, -\frac{b}{2a}\right]
\qquad \mbox{and} \qquad
\psi:\left[ \frac{-\Delta}{4a},+\infty)\right) \to \left[ -\frac{b}{2a}, +\infty,\right)
$$
such that
$$
\begin{matrix}
\varphi ( f(x))=x \qquad f(\varphi(y))=y\\
\psi(f(x))=x      \qquad f(\psi(y))=y
\end{matrix}
$$
Here $\Delta=b^2-4ac$. Let $y=ax^2+bx+c$. Check for yourself
$$
y=\left[a\left(x+\frac{b}{2a}\right)^2-\frac{\Delta}{4a} \right]
$$
Then
$$
\left( x+\frac{b}{2a}\right)^2=\frac{1}{a}\left( y+\frac{\Delta}{4a}\right)
$$
and
$$
x=-\frac{b}{2a} \pm\sqrt{\frac{1}{a}\left(y+\frac{\Delta}{4a}\right)}
$$
Finally we have
$$
\varphi(y)=-\frac{b}{2a}-\sqrt{\frac{1}{a}\left(y+\frac{\Delta}{4a}\right)}
$$
and
$$
\psi(y)=-\frac{b}{2a}+\sqrt{\frac{1}{a}\left(y+\frac{\Delta}{4a}\right)}
$$


First quick glance at a dataset

Question: Please pardon my ignorance, but...
I keep finding myself in a situation, where I'm faced with a bunch of new data I managed to find. This data usually looks something like this:
Date     Number1  Number2  Category1  Category2
20120125      11      101        Dog      Brown
20120126      21       90        Cat      Black
20120126      31      134        Cat      Brown
(...)

Usually at first glance I can't really tell if there are any trends here. The correlations between the various columns may not be very significant, but I would be delighted if I didn't have to manually create a plot for every possible combination of columns/categories.
Is there a tool out there which would accept a table of data along with information which columns should be treated as numbers, dates and categories and then proceed to plot:

correlations between each two numerical columns
correlations between each two numerical columns, with separate trend lines for each category
each number column as a time series,
each number column as a time series, separated by category,
etc.

In the end this would generate a large number of plots, most of which would show only noise. Ideally, the tool could score the plots by correlation and in the end display a slideshow starting with the highest scoring plots. This would be a very imperfect, but useful first glance at the dataset.
So? Is there a tool everyone uses for this and I just don't know about it, or is this something we need to make?
Comment: Thank you all very much for your answers. I'm taking my time to test each of the tools you mention on my data. I will pick an answer after my tests. I guess it's too bad I can't pick more then one :)
Answer: @Ondrej and @Michelle have provided some good information here.  I wonder if I can contribute by addressing some points not mentioned elsewhere.  I wouldn't beat yourself up about not being able to glean much from the data in tabular form, tables are generally not a very good way to present information (cf., Gelman et al., Turning Tables into Graphs).  On the other hand, asking for a tool that will automatically generate all of the right graphs to help you explore a new data set is almost like asking for a tool that will do your thinking for you.  (Don't take that the wrong way, I recognize your question makes clear that you aren't going that far; I just mean that there will never really be such a tool.)  A nice discussion that is related to this can be found here.
These things having been said, I wanted to talk a little about the kinds of plots that you might want to use to explore your data.  The plots listed in the question would be a good start, but we might be able to optimize that a little.  To start with, making "a large number of plots" correlating pairs of variables might not be ideal.  A scatterplot only displays the marginal relationship between two variables.  Important relationships can often be hidden in some combination of multiple variables.  So the first way to beef up this approach is to make a scatterplot matrix that displays all pairwise scatterplots simultaneously.  Scatterplot matrices can be enhanced in various ways:  E.g., they can be combined with univariate kernel density plots of each variable's distribution, different markers / colors can be used to plot different groups, and possible nonlinear relationships can be assessed by overlaying a loess fit.  The scatterplot.matrix function in the car package in R can do all of these things nicely (an example can be seen halfway down the page linked above).
However, while scatterplot matrices are a good start, they are still only displaying the marginal projections.  There are a few ways to try to move beyond this.  One is to explore 3-dimensional plots using the rgl package in R.  Another approach is to use conditional plots; coplots can help with relationships amongst 3 or 4 variables simultaneously.  An especially useful approach is to use a scatterplot matrix interactively (albeit, this will require more effort to learn), e.g. by 'brushing'.  Brushing allows you to highlight a point or points in one frame of a matrix and those points will simultaneously be highlighted in all of the other frames.  By moving the brush around, you can see how all of the variables change together.  UPDATE: Another possibility that I had forgotten to mention is to use a parallel coordinates plot.  This has a disadvantage in not making your response variable distinct, but could be useful, for example, in examining inter-correlations amongst your X variables.
I also want to commend you for examining your data sorted by date collected.  Although data are always gathered over time, people don't always do this.  Plotting a line graph is nice, but I would suggest you supplement that with graphs of autocorrelations and partial autocorrelations.  In R, the functions for these are acf and pacf respectively.
I recognize that all of this doesn't quite answer your question in the sense of giving you a tool that will make all the plots for you automatically, but one implication is that you wouldn't actually have to make as many plots as you fear, e.g., a scatterplot matrix is just one line of code.  In addition, in R, it should be possible to write a function / some reusable code for yourself that would partly automate some of this (e.g., I can imagine a function that takes in a list of variables and a date-ordering, sorts them, pops up a new window for each with line, acf, and pacf plots).
Comment: (+1) Don't miss [ggobi](http://www.ggobi.org/) and `marginal.plot` from the [latticeExtra](http://latticeextra.r-forge.r-project.org/) package.
Comment: As always, excellent points. :)
Answer: Correlations between each pair of numerical columns can be shown in a correlation matrix. It need not be purely numerical, it can be color coded, to allow for a quick-glance evaluation. Check out corrplot package for R.
For further analysis, Rattle is quite a useful GUI tool.
If you search Stack Exchange using the keywords "corrplot" or rather "Rattle", you will find several topics where these tools and their alternatives are covered. Like this one.
Good luck!
Answer: @Ondrej has given some good advice, so I will focus on your question around how software treats imported data. With character data, "Category 1" and "Category 2", the software automatically treats these as groups or factors because mathematical operations cannot be conducted on these pieces of data. This means that you will be prevented from entering anything from those categories (alternatively, you'll get an error if you try if you're using syntax or a command line instead of a menu-driven system) into an analysis that requires numbers.
For data like your "Number 1" and "Number 2", the software reads these as numeric. If you have any groups/factors that contain purely numeric data, you will need to instruct your software that these are groups/factors.
Sometimes dates can be imported badly into statistical software. Once you import your data, you should see that the data type in your statistical software is showing some form of "date" type for "Date". If you see the data type as anything other than date, you have an issue. Even if it is showing as date, check the import of some rows where you have dates like days like the 13th or 25th of the month - depending on how the software is set up, sometimes the American/British date formatting causes screwy data from import, because of the reversal of the day/month.

First quick glance at a dataset


High-accuracy RNG

Question: I need to simulate a sample of size 100x3 of white noise (normal with null mean and unitary variance)
I'm actually using Mersenne-Twister but discussing with my Professor seems is not "very stable" for the size we need.
Since I'm going to perform it via a programming language, do you have any suggestion for other RNG? I also found this.
Thanks for the help :)
UPDATE
With "not very stable" I mean how pretty different the values are each run. rnorm should give me pretty independent elements with are not since covariance is not equal to Identity Matrix. I would need to have a sample that result pretty close to identity matrix, even if rounded. So, is there any way to discard samples until it's very close to Identity Matrix? What condition should I use?
Comment: Why isn't typing ```rnorm(100)``` in R a valid solution?
Comment: What exactly do you mean by "not very stable"? Also the link you provided points to a function for simulation from a [stable distribution](https://en.wikipedia.org/wiki/Stable_distribution) of which the normal distribution is a special case. For simulating purely from a normal distribution, `rnorm` is sufficient.
Comment: @David sorry, I forgot it's 100x3 size, but I will provide an aswer in some secs.
Comment: @JackLametta What about ```rnorm(300)``` then?
Comment: @David updated question :)
Comment: @COOLSerdash I've updated my question.
Answer: The fact that the variances are not exactly 1 and the covariances not exactly 0 is totally expected, especially with these sample sizes and does by no means indicate that the RNG is not working properly. (Hint: Try running cov(matrix(rnorm(1e6*3), 1e6))). Remember that the values specified in the RNG are population parameters of the distribution and not the empirical values of samples drawn from this population.
Although it is unclear from the question why such exact numbers are needed, they can be generated using the function mvrnorm from the MASS package specifying the argument empirical = TRUE. In contrast to rnorm which is used to sample from univariate normal distributions, mvrnorm is used to generate samples from multivariate normal distributions. Here is an example:
library(MASS)

set.seed(142857)
mu_vec <- c(0, 0, 0)  # The means
cov_mat <- diag(1, 3) # The covariance matrix
n <- 100

x <- mvrnorm(n = n, mu = mu_vec, Sigma = cov_mat, empirical = TRUE)

cov(x)
              [,1]          [,2]          [,3]
[1,]  1.000000e+00 -2.250771e-16 -2.604286e-16
[2,] -2.250771e-16  1.000000e+00  6.497218e-17
[3,] -2.604286e-16  6.497218e-17  1.000000e+00

The variances and covariances of the simulated samples are now exactly 1 and 0, respectively, as desired.
Comment: @JackLametta `mvrnorm` is used to sample from multivariate normal distributions. I have updated my answer and included this information.
Comment: May I ask what's the difference between mvrnorm and rnorm?
Comment: I guess for moving on with the next problem, I should open another question.
Comment: Thanks, so far.
Answer: All right, so it looks to me that your problem has nothing to do with the random number generator but rather with choosing a distribution that does not generate a lot of outliers (low kurtosis)
If there are no constraints preventing us from doing so, I would go for the uniform distribution:
matrix(runif(300, min=0, max=1), 100)

ADDED AFTER QUESTION EDIT: Since you can't change your distribution. I think your best chance is to save the output of first execution (setting variance to $x$) and add some random noise (normal with variance $1-x$ This way you get the desired mean and variance while getting some stability between executions. Choose the value of $x$ that better fits your needs
Comment: The term "white noise" means a sequence of independent identically distributed random variables
Comment: Actually I need a Normal distribution with the parameters cited.
Comment: I just added them now, since I omitted white noise is Normal (0,1).
Actually, professor sugegsted me to change the RNG since that one is not so stable in termns of values...
That's why I'm asking the question.
Comment: Oh well, thanks. I'm pretty new in the topic. Sorry if I was wrong.

High-accuracy RNG


Apache mod_deflate doesn't compress javascript/css

Question: I'm trying to make Gzip compression work on xampp, right now this is in my .htaccess
<code><IfModule mod_deflate.c>

    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype

</IfModule>
</code>
The HTML file gets compressed, but nothing happens to the JavaScript and CSS files. Anyone know why? How to fix this? (if it's even possible)
Comment: Does the mime-types for javascript and css files that apache reports match up with the types you're adding?
Comment: `mod_deflate` installed and enabled?
Comment: Jup, as I said, compression works on html files, but on nothing else
Comment: @Crinsane You can try going to [here](http://web-sniffer.net/) and doing a HEAD request for a css and js file, or you can try looking for `AddType` for js and css in server config
Comment: Found out the browser still used a cached version of the js and css files
Answer: Okay... stupid fault... browser still used cached versions...


A general theorem concerning arithmetic functions

Question: I am self-learning An Introduction to Sieve Methods and their Applications by Alina Carmen Cojocaru & M. Ram Murty.
The authors left the proof of Proposition 9.1.1 as an exercise and I try to prove it. Here is the proposition:
$$\mathcal D=\left\{D\,:\,\mathbb N\longrightarrow\mathbb C\ \left|\ \sum_{n\leq x}|D(n)|^2=O(x(\log x)^\alpha)\ \text{for some}\ \alpha>0\right\}\right..$$

If $D\in\mathcal D$ and $\theta>0$, then

$$\sum_{n\leq x}\frac{|D(n)|}{n^\theta}\ll x^{1-\theta}(\log x)^\alpha\ \ \ \ \text{for some}\ \alpha>0.$$

If $D_1,D_2\in\mathcal D$, then

$$\sum_{ef\leq x}|D_1(e)D_2(f)|d(ef)\ll x(\log x)^\beta\ \ \ \ \text{for some}\ \beta>0,$$
and
$$\sum_{ef\leq x}|D_1(e)D_2(f)|^2d(ef)\ll x(\log x)^\gamma\ \ \ \ \text{for some}\ \gamma>0,$$
where $d(n)$ is the number of positive divisors function.

I have proved part 1 but stuck in part 2. Here is my proof for part 1:
By Cauchy-Schwarz inequality,
$$\sum_{n\leq x}|D(n)|\leq\sqrt{\left(\sum_{n\leq x}|D(n)|^2\right)\cdot\lfloor x\rfloor}\ll x(\log x)^{\alpha/2}.$$
Therefore, by partial summation,
$$\begin{aligned}
\sum_{n\leq x}\frac{|D(n)|}{n^\theta}&=\frac{1}{x^\theta}\sum_{n\leq x}|D(n)|+\theta\int_1^x\left(\sum_{n\leq t}|D(n)|\right)\frac{dt}{t^{\theta+1}}\\
&\ll x^{1-\theta}(\log x)^{\alpha/2}+\theta\int_1^x\frac{(\log t)^{\alpha/2}}{t^\theta}dt\\
&\ll x^{1-\theta}(\log x)^{\alpha/2}.
\end{aligned}
$$

For part 2, the best bound I got is $x^{1+\epsilon}(\log x)^\beta,\ \forall\epsilon>0$, using Dirichlet's hyperbola method. I don't have any idea dealing with the function $d(n)$.
Any comment and answer is appreciated.
Comment: @FShrike it's another way to write big O notation. $$f(x) << g(x) \ <=>\ f(x) = O(g(x)).$$
Comment: @LucaArmstrong (it's `\ll` btw to render $\ll$) I've seen it mean different things in different contexts
Comment: What's the *precise* meaning of $\ll$, here?
Answer: Notation) We put $\mathcal{L}=\log(x+1)$ and write $\mathcal{L}^M$ for any fixed power of $\mathcal{L}$. There may be multiple appearances of $M$ but they do not mean the same constants everytime. Let $\epsilon$ be a fixed positive number smaller than $\log 2$.
For the first estimate of $2.$, we use the following for all $D\in\mathcal{D}$:
$$
\sum_{n\leq x} |D(n)|d(n) \ll x \mathcal{L}^M.
$$
This follows by Cauchy-Schwarz, the left hand side of the above is
$$
\ll \sqrt{ \sum_{n\leq x}|D(n)|^2 \cdot \sum_{n\leq x} d(n)^2 }
$$
Then the result follows.
Now, the proof of the first estimate: By partial summation for the sum over $f$,
$$
\begin{align}
\sum_{ef\leq x} |D_1(e)D_2(f)|d(ef)&\leq \sum_{ef\leq x} \frac{|D_1(e)D_2(f)|d(e)d(f)x}{ef}\\
&=\sum_{e\leq x} |D_1(e)|d(e) \sum_{f\leq x/e} \frac{|D_2(f)|d(f)x}{fe}\\
&\ll \sum_{e\leq x} \frac{|D_1(e)|d(e)x}e \mathcal{L}^M.
\end{align}
$$
By partial summation, we have
$$
\sum_{e\leq x}\frac{|D_1(e)|d(e)}e \ll \mathcal{L}^M.
$$
Then by combining these estimates, we have
$$
\sum_{ef\leq x} |D_1(e)D_2(f)|d(ef)\ll x\mathcal{L}^{2M}
$$
as desired.
We will show that the second estimate of $2.$, does not hold, by showing a counterexample.
We say that a number is a primorial if it is of the form $\prod_{p\leq y} p$. Let $D_1=D_2=D$ be the arithmetic function defined as follows:
$$
D(n)=\begin{cases}1 &\mbox{ if }n=1,\\
0 &\mbox{ if }n \text{ is not a primorial and not }1,\\
\sqrt n &\mbox{ if }n=\prod_{p\leq y} p \text{ is a primorial and }y \text{ is a prime number}.\end{cases}
$$
Then $D\in\mathcal{D}$ by $\sum_{n\leq x} D(n)^2\ll x$.
However, if $x$ is a primorial, then by the case $e=x$ and $f=1$, we have
$$
\sum_{ef\leq x}|D_1(e)D_2(f)|^2d(ef) \geq D_1(x)^2D_2(1)^2d(x)
$$
When $x$ is a primorial, we have $D_1(x)^2=x$ and
$$
d(x)\geq x^{\frac{\log 2 -\epsilon}{\log\log x}}.
$$
Thus, together with $D_2(1)=1$, the above lower bound for the sum is
$$
x^{1+\frac{\log 2 -\epsilon}{\log\log x}}.
$$
This lower bound is not $\ll x(\log x)^{\gamma}$ for any fixed $\gamma>0$.
Comment: Ah, the key here is that the second part of the second case is false! I sat down and tried to work through this problem and failed, but I didn't think to see if it was true.
Comment: From the first part of 2, we see that $$\sum_{e\leq x} |D_i(e)|^4\ll x(\log x)^{\alpha}$$ for some $\alpha>0$ implies the result of the second part. Then we also see this does not follow from $$\sum_{e\leq x} |D_i(e)|^2\ll x(\log x)^{\alpha}$$ This was the starting point where I started to think that the second part is false and looked for a counterexample.


how do you troubleshoot network performance of a web application

Question: This is a pretty naive question, I guess. I frequently need to figure out what if the problem with a web app or is it simply a networking issue - lost packets or a slow connection in any point between, say, your boss on a crappy wifi connection at the airport and the web server, or the CDN and the web server or MySQL and the webserver, or memcached box... You get the idea. Also, how do you tell if it's the DNS server?
Some of you are missing the point. This is not a question about measuring web application performance. This is a question about measuring network performance as a component of web application performance.
Answer: Set up tracing (perhaps togglable by a querystring), showing the amount of time spent in heavy sections of the code, and overall server time.  If it server creates the page in .2 seconds and it takes 10 seconds to load, you know it's either the network, or the user's browser.
You can also use the Net tab in Firebug, or timeline view in Fiddler to see individual components coming down and how long they take.
Answer: To see if it's the DNS server, you can try to bypass the DNS server.  You can do that by adding the relevant host names to your hosts file.  If, when you have the addresses in the hosts file, the web server seems to be responding much faster, then investigate the DNS further.  If site performance still sucks, the problem is most likely elsewhere.
More advanced; You can also query the DNS directly with nslookup or dig.  Make sure you query your web site domain's authoritative DNS servers directly to see their response time, as opposed to the response time of the local DNS server, which may have a cached copy of the entries.
Answer: The best approach is to baseline your web performance from sites with known good connectivity.  Once you have that established, you can then begin the fairly straightforward process of establishing the cause of latency for your particular client <--> web application issue from the client in question.
My recommendations for baselining latency would be pingdom.com - $10/month gets you rock solid (I've been using them for the last six months - every issue they've reported has been real) latency analysis from multiple locations on the Internet as well as monitoring/notification for website down issues.
Of particular importance to your requirements, is that they establish an audit log of your web sites performance from multiple locations in the United States, as well as internationally.  This can prove useful if you have a transient issue and you wish to look back historically.
Being able to provide your boss (who is your target audience in the question) a graph of average latency from twelve different locations provides a strong foundation for identifying the client-side issues (WiFi, DNS, laptop problems) versus an issue with the website's base performance AND connection to the Internet.
DNS server issues, of course, can be immediately remedied by having the client place the appropriate hostname->IP mappings in the local /etc/hosts (or, in the case of Windows, C:\windows\system32\drivers\etc\hosts) file - If the issue disappears when you have the appropriate /etc/hosts file configured, it's a very strong indicator that there is an issue in your resolver chain (local resolver, first DNS server in the chain, or canonical)
Answer: Can't hurt to perform actual load testing from multiple locations as well. Run a local load test, and then run one from various locations outside of your data center. The local tests should give you a good baseline of what to expect at LAN/local conditions. Then you can compare that to what you get externally, and you can see what sort of loss you're getting on the networking end. Obviously, the external tests are going to have higher load times, but you have to determine what's acceptable in that realm.
Answer: In addition to the other recomendations I like to use Fiddler to see exactly how long individual requests are taking and how much badwidth is used.  It runs from the client so it shows me how long each request takes from that persepctive.
Answer: Also, try YSlow, a great add-in for Firebug:
http://developer.yahoo.com/yslow/
Answer: Seems to me you need to know network connections for each process, the amount of traffic for each socket connection, the response time for each socket and a way to visualize the data.
appfirst.com has worked for us.


Determine the density of sum of three normal variables.

Question: Setting
$\pmb{X} = (X_1,X_2,X_3)$ is a properly center normal with covariance matrix
$$\begin{pmatrix}
a & b & 0\\ b  & d & 0\\ 0 & 0 & e
\end{pmatrix}$$
Determine the density of $Y = X_1 + 2 X_2 - X_3$
So I see $X_1 \overset{d}{\sim} \mathcal{N}(0,a)$, $X_2 \overset{d}{\sim} \mathcal{N}(0,d)$, and $X_3 \overset{d}{\sim} \mathcal{N}(0,e)$.
But the non-zero covariance between $X_1$ and $X_2$ is really throwing me off, please explain?
Comment: Are you _sure_ you have transcribed all the numbers properly? The covariance matrix that you have written down says that cov$(X_1,X_2)= 4$ while var$(X_1)=3$, var$(X_2)=5$ which makes the _correlation coefficient_ $$\rho_{1,2}=\frac{\operatorname{cov}(X_1,X_2)}{\sqrt{\operatorname{var}(X_1) \operatorname{var}(X_2)}} = \frac{4}{\sqrt{3\times 5}} > 1.$$
Comment: Alternatively, $$\operatorname{var}(X_1-X_2)=\operatorname{var}(X_1) + \operatorname{var}(X_2) - 2\cdot \operatorname{cov}(X_1,X_2) = 3+5-2\cdot 4 = 0$$ showing that _something_ is awry.
Comment: You're right the numbers are not correct, I made an edit for a generic covariance matrix
Answer: Hint:  $$\begin{align*} \operatorname{Var}[Y] &= \operatorname{Var}[X_1 + 2X_2 - X_3] \\ &= \operatorname{Var}[X_1] + 4\operatorname{Var}[X_2] + \operatorname{Var}[X_3]  + 4 \operatorname{Cov}[X_1, X_2] - 2 \operatorname{Cov}[X_1, X_3] - 4 \operatorname{Cov}[X_2, X_3] \end{align*}$$


Fiz um leitor de pdf em python com um contador pra ler página a página desse pdf mas estou errando em algo e meu "leitor" só lê a ultima página:

Question: <code># o contador começa em -1 pq o para ler a primeira página tenho que começar do indice 0
    contador = -1

def acessarPDF( c = contador):

    import PyPDF2

    arq = r"C:\Users\Neto\Desktop\Springer Ebooks.pdf"

    lerPdf = PyPDF2.PdfFileReader(arq)

    pagina = lerPdf.getPage(c)

    conteudo = pagina.extractText()

    return conteudo

while contador < 21:

    contador += 1

    acessarPDF()

pdf = acessarPDF()

print(pdf)
</code>
Comment: Você não deveria passar a variável `contador` para a função `acesaPDF`?
Comment: o erro esta nessa forma de contar, veja que esta invocando pagina -1, que é o final do array
Answer: Veja se dá certo assim:
<code>    import PyPDF2
    contador = 0

    def acessarPDF(c):
        arq = r"C:\Users\Neto\Desktop\Springer Ebooks.pdf"
        lerPdf = PyPDF2.PdfFileReader(arq)
        pagina = lerPdf.getPage(c)
        conteudo = pagina.extractText()
        return conteudo

    while contador <= 21:
        """
        Troquei a posição da incrementação do contador,
        para que ele possa começar com zero.
        """

        print(acessarPDF(contador)) # Aqui vai printar e executar a função ao mesmo tempo.
        contador += 1
</code>
Comment: Valeu, cara. tmj!


AlertDialog.Builder not dismissing android

Question: I have a AlertDiaog.Builder instance which I want to dismiss on NegativeButton click. then I want to execute a AyncTask. All this happens upon shaking my device.
currently, The AlertDialog.builder does not dismiss even after the AyncTask executes.
The showDialog() is executed from another button click where everything works perfect. This problem occurs only on device shake.
Here is my code:
@Override
    public void onShake(float force)
    {
        // TODO Auto-generated method stub

        hour = cal.get(Calendar.HOUR);
        hour = hour+1;
        mins = cal.get(Calendar.MINUTE);
        timeString = hour+":"+mins+":"+today.second;
        showDialog(timeString, "");
        }
    public void showDialog(String timeString, String title)
    {

        builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(title);
        builder.setMessage("Reaching at:"+" "+ timeString+"?");

        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();
                dialog.cancel();
            }
        });

        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which)
            {
                // Do nothing but close the dialog
                dialog.cancel();;
                new AddStatusTask().execute();

            }

        });

        alert = builder.create();
        alert.show();
    }

any help is appreciated
Comment: did i keep global referance of ur dialog to dissm on postexceute of asynctask?
Comment: @mtetno no I didnt. I am executing the same piece of code on another button click where it works fine. its only when the device is shaken this problem occrs
Comment: and this is in same activity right? u just wanna dismiss it on asynctask complete?
Comment: That is strange as the dialog will close on positive or negative even is there is no dismiss() or cancel(); Try with `builder.show();` instead of `alert = builder.create(); alert.show();`
Comment: Maybe it is a context issue? You use getActivity().
Comment: did u sloved the issue?
Comment: @greenapps your solution worked. Please post an answer so that I can accept it.
Answer: That is strange as the dialog will close on positive or negative even if there is no dismiss() or cancel(); Try with builder.show(); instead of alert = builder.create(); alert.show();.


Criar nova matriz com conteúdos de outra matriz

Question: Matriz principal:
public static String [][] matrizPrincipal(){
     String [] [] matriz = new String [2] [6];
     matriz[0][0] = "Robin Arryn";
     matriz[0][1] = "Lino Facioli";
     matriz[0][2] = "145";
     matriz[0][3] = "Vivo";
     matriz[0][4] = "Arryn";
     matriz[0][5] = "Feminino";

     matriz[1][0] = "Yohn Royce";
     matriz[1][1] = "Rupert Vansittart";
     matriz[1][2] = "45";
     matriz[1][3] = "Vivo";
     matriz[1][4] = "Arryn";
     matriz[1][5] = "Feminino";
     return matriz;
}

Método que caso o personagem (coluna 0 da matriz principal) for uma mulher (coluna 5) e pertencer a família Arryn (coluna 4) adiciona o nome desse personagem a uma nova matriz:
public static void imprimeMatrizFeminina(String [] [] mat){
     int cont = 0;
     //Método para Mulheres da família Arryn
     for(int i=0; i<mat.length; i++){
        if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")) cont ++;
     }
     String[] matrizFemininaArryn = new String [cont];

     for(int i=0; i<mat.length; i++){
        for(int j=0; j<matrizFemininaArryn.length; j++){
           if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")){
               matrizFemininaArryn[j] = mat[i][0];
           }
        }
     }
     System.out.println("Mulheres da família Arryn em ordem alfabética crescente:" + Arrays.toString(matrizFemininaArryn));
}

Porém ao testar, ele retorna somente o primeiro personagem (Robin Arryn) e a segunda posição retorna nulo ao invés do nome Yohn Royce.
Imagem:
Answer: Esse problema acontece porque no método imprimeMatrizFeminina você itera n vezes sobre a array matrizFemininaArryn, o que é desnecessário, retire o terceiro for e use a variável j como índice:
public static void imprimeMatrizFeminina(String [] [] mat){
    int cont = 0, j = 0;
    for(int i = 0; i < mat.length; i++)
       if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")) cont ++;

    String[] matrizFemininaArryn = new String [ cont ];

    for(int i = 0; i < mat.length; i++){
        if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")){
            matrizFemininaArryn[j] = mat[i][0];
            j ++;
        }
    }
    System.out.println("Mulheres da família Arryn em ordem alfabética crescente:" + Arrays.toString(matrizFemininaArryn));
}

Ver demonstração
Alternativamente, você pode utilizar uma lista:
public static void imprimeMatrizFeminina(String [] [] mat){
    List<String> matrizFemininaArryn = new ArrayList<String>();

    for(int i = 0; i < mat.length; i++){
        if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")){
            matrizFemininaArryn.add(mat[i][0]);
        }
    }
    System.out.println("Mulheres da família Arryn em ordem alfabética crescente: " + matrizFemininaArryn);
}

Ver demonstração
Comment: Excelente! Era isso mesmo ! Muito obrigado xD


Defining an EXTRACT range from a SELECT statement

Question: I intend to process a dataset from EventHub stored in ADLA, in batches. It seems logical to me to process intervals, where my date is between my last execution datetime and the current execution datetime.
I thought about saving the execution timestamps in a table so I can keep track of it, and do the following:
DECLARE @my_file string = @"/data/raw/my-ns/my-eh/{date:yyyy}/{date:MM}/{date:dd}/{date:HH}/{date:mm}/{date:ss}/{*}.avro";

DECLARE @max_datetime DateTime =  DateTime.Now;

@min_datetime =
    SELECT (DateTime) MAX(execution_datetime) AS min_datetime
    FROM my_adldb.dbo.watermark;

@my_json_bytes =
    EXTRACT Body byte[],
            date DateTime
    FROM @my_file
    USING new Microsoft.Analytics.Samples.Formats.ApacheAvro.AvroExtractor(@"{""type"":""record"",""name"":""EventData"",""namespace"":""Microsoft.ServiceBus.Messaging"",""fields"":[{""name"":""SequenceNumber"",""type"":""long""},{""name"":""Offset"",""type"":""string""},{""name"":""EnqueuedTimeUtc"",""type"":""string""},{""name"":""SystemProperties"",""type"":{""type"":""map"",""values"":[""long"",""double"",""string"",""bytes""]}},{""name"":""Properties"",""type"":{""type"":""map"",""values"":[""long"",""double"",""string"",""bytes"",""null""]}},{""name"":""Body"",""type"":[""null"",""bytes""]}]}");

How do I properly add this interval to my EXTRACT query? I tested it using a common WHERE clause with interval defined by hand and it worked, but when I attempt to use @min_datetime it doesn't work, since its result is a rowset.
I thought about applying some filtering in a subsequent query, but I am afraid this means @my_json_bytes will extract my whole dataset and filter it aftewards, resulting in a suboptimized query.
Thanks in advance.
Comment: Try applying the filter in a subsequent with a `CROSS JOIN` to `@min_datetime`.
Answer: You should be able to apply the filter as part of a later SELECT.  U-SQL can push up predicates in certain conditions but I haven't been able to test this yet.  Try something like this:
@min_datetime =
    SELECT (DateTime) MAX(execution_datetime) AS min_datetime
    FROM my_adldb.dbo.watermark;

@my_json_bytes =
    EXTRACT Body byte[],
            date DateTime
    FROM @my_file
    USING new Microsoft.Analytics.Samples.Formats.ApacheAvro.AvroExtractor(@"{""type"":""record"",""name"":""EventData"",""namespace"":""Microsoft.ServiceBus.Messaging"",""fields"":[{""name"":""SequenceNumber"",""type"":""long""},{""name"":""Offset"",""type"":""string""},{""name"":""EnqueuedTimeUtc"",""type"":""string""},{""name"":""SystemProperties"",""type"":{""type"":""map"",""values"":[""long"",""double"",""string"",""bytes""]}},{""name"":""Properties"",""type"":{""type"":""map"",""values"":[""long"",""double"",""string"",""bytes"",""null""]}},{""name"":""Body"",""type"":[""null"",""bytes""]}]}");

@working =
    SELECT *
    FROM @my_json_bytes AS j
         CROSS JOIN
             @min_datetime AS t
    WHERE j.date > t.min_datetime;

Comment: Thank you! This will do the trick. I just hope it is optimized. I will benchmark it later if I get the time to do so.


Erro ao iniciar servidor Tomcat

Question: Estou inserindo duas dependências hibernate no meu pom.xml

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

Quando inicio o servidor Tomcat dá erro

Log no console:

INFORMAÇÕES: At least one JAR was scanned for TLDs yet contained
  no TLDs. Enable debug logging for this logger for a complete list of
  JARs that were scanned but no TLDs were found in them. Skipping
  unneeded JARs during scanning can improve startup time and JSP
  compilation time. fev 16, 2018 11:34:20 AM
  org.apache.catalina.core.ContainerBase startInternal GRAVE: A child
  container failed during start java.util.concurrent.ExecutionException:
  org.apache.catalina.LifecycleException: Failed to initialize component
  [org.apache.catalina.webresources.JarResourceSet@5fd5d6d1]    at
  java.util.concurrent.FutureTask.report(Unknown Source)    at
  java.util.concurrent.FutureTask.get(Unknown Source)
  .....................
fev 16, 2018 11:34:20 AM org.apache.coyote.AbstractProtocol pause
  INFORMAÇÕES: Pausing ProtocolHandler ["http-nio-8080"] fev 16, 2018
  11:34:20 AM org.apache.coyote.AbstractProtocol pause INFORMAÇÕES:
  Pausing ProtocolHandler ["ajp-nio-8009"] fev 16, 2018 11:34:20 AM
  org.apache.catalina.core.StandardService stopInternal INFORMAÇÕES:
  Stopping service [Catalina] fev 16, 2018 11:34:20 AM
  org.apache.coyote.AbstractProtocol destroy INFORMAÇÕES: Destroying
  ProtocolHandler ["http-nio-8080"] fev 16, 2018 11:34:20 AM
  org.apache.coyote.AbstractProtocol destroy INFORMAÇÕES: Destroying
  ProtocolHandler ["ajp-nio-8009"]
Answer: Tomcat 8.5 . Dentro de catalina.properties, localizado no conjunto de diretórios / conf:
tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\*.jar
Ou vá para context.xml, localizado no diretório / conf da Tomcat e adicione:
<JarScanner scanClassPath="false"/>
Comment: tentei os dois modos, porém o erro persiste.

Erro ao iniciar servidor Tomcat


how to debug drupal_http_request

Question: I'm working on a module that takes a form submission and posts it to a rest api, using the webform validator module's hooks.  I'm trying to debug what's going wrong, and I have the following code, which correctly displays $data and $url but nothing for $result (I'm assuming it's null?).
I'm new to drupal and I wonder what I'm doing wrong, with the http_request that it comes back null, or what else I can do to debug.
      $options = array( data => $data,
                        method => 'POST');
      //verify $data
      $errors['item_2'] = $data;
      $errors['item_3'] = $url

      $result = drupal_http_request($url, $options);

      // display the returned JSON result as a form error
      $errors['item_1'] = json_decode($result);

Comment: This function always returns an array (PHP), that you can access the status code, redirects, and the response contents. If you install Devel module, you can call dpm($result) to make it print the variable in a nice interactive display. When using API functions, API docs can be very helpful: https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request/7
Answer: drupal_http_request doesn't just return the response data, it returns an object.
Return value
object An object that can have one or more of the following components:
request: A string containing the request body that was sent.
code: An integer containing the response status code, or the error code if an error occurred.
protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
status_message: The status message from the response, if a response was received.
redirect_code: If redirected, an integer containing the initial response status code.
redirect_url: If redirected, a string containing the URL of the redirect target.
error: If an error occurred, the error message. Otherwise not set.
headers: An array containing the response headers as name/value pairs. HTTP header names are case-insensitive (RFC 2616, section 4.2), so for easy access the array keys are returned in lower case.
data: A string containing the response body that was received.
For example, you can check
// This is the actual response data.
drupal_set_message($result->data);
// if there's an error, it'll  be in here
drupal_set_message($result->error);

or, if using the devel module
dpm($result);

In your case, you might just need:
if (empty($result->error) {
  $errors['item_1'] = json_decode($result->data);
}else{
  // An error occurred, log, show msg etc...
}

how to debug drupal_http_request


mean of sample vs the sample mean

Question: Say I have a sample population A it has mean $\mu_A$.  I sample A and obtain another sample population $\hat A$, it has a mean of $\mu_\hat A$.
If a hypothesis test indicates that I should be 95% confident that the two means $\mu_A$ and $\mu_\hat A$ are not equal.
What can I infer about $\hat A$ ?
How might it be different from A.
Comment: You might want to rethink how you describe the hypothesis test.  You probably mean "There is a 0.05 or less probability that if the two means were equal we would see the data we did", which is not the same?
Comment: @PeterEllis I am saying that 95% of the time I expect the difference in the means not be equal to 0. Is that not what I wrote?
Answer: You seem to be describing the procedure of the bootstrap which allows you to estimate the standard deviation of a measured statistics (in your case the mean of the series) by sampling the series many times with replacements.
By performing bootstraping you will be able to infer the distribution of μA (it's standard deviation, or any of it's relevant CI).
Comment: Ok this'll give a framework to think about it, but I'm still having trouble fleshing out the implications. Care to speculate?
Comment: Can you explain what you are looking for? What would you like to learn about population A? and it's  μA?

mean of sample vs the sample mean


Are there any good design practices or standards for JavaScript development?

Question: When developing with object-oriented languages like Java or C#, it's not uncommon for developers to use design tools like UML to make class diagrams, create interfaces, define major components and interactions, outline an API, etc., before beginning the implementation.
I know for most small JavaScript applications, these software engineering principles may be overkill, but if you're developing a library (jQuery, YUI) or creating a large application (Gmail, Google Docs), it's a good idea to create a design and plan ahead before you start writing any code.
Are there any similar practices used in JavaScript development or web development in general?
Edit:
Just to clarify, I'm not interested in creating classes/interfaces or making UML for JavaScript. JavaScript is a different paradigm from the likes of Java/C# and therefore needs different design tools. I'm interested in knowing what those JavaScript design tools/practices are, if any.
Maybe this question better asks what I'd like to know: If a company like Google created a large web application and had several dozen team members create it, what processes, documents, and practices would such a team use to successfully create, collaborate, and solidify a design? What tools (e.g., UML, flow charts, scribbled notes on a piece of paper) would they use to work on and share the design of the application (without writing a single line of code)?
Comment: You can apply any language agnostic design methodology to JavaScript. I tend to define my module's interfaces and develop to unit tests. you can also use libraries like underscore.js to apply high level functional abstractions.
Answer: I'm a fan of the Google Javascript Style Guide:
https://google.github.io/styleguide/javascriptguide.xml
Comment: +1 for that. It's nice to read some of that advice. Didn't know about the memory leaks.
Answer: I think the answer depends largely on which libraries, if any, you are using client side.
Jquery code looks very different from Sencha or Sproutcore code, for example.  In Sencha and Sproutcore, the framework provides you with a 'class' system for developing components, so these frameworks lend themselves to the canonical forms of design patterns.
Also note that javascript is very different then Java or C#.  You can impose an interface type system on your code, but many would argue that you are killing the javascript dynamic-language awesomeness if you do.
That said, its always good to have a plan.  If you can stay DRY by extending JS objects, then I think you should.  And it always makes sense to put some high level design in place.
Comment: @zarjay, right.  If it is a true RIA, then I believe you should design it.  Check out my answer here to see how I designed a part of one of my apps: http://stackoverflow.com/questions/5018391/finite-state-machine-pattern-the-one-true-pattern/5018499#5018499
Comment: Thanks for commenting. I know that JavaScript is a different paradigm from Java/C#, which is why I don't want to use design tools that were built for object-oriented languages. However, I also don't want to scribble design notes in Notepad or a Word document. It'd be nice if there were a standard or best practice way of saying "This is the design/API that we agree on for our web application."


Linear probability model

Question: Is there any advantage or any situation when the Linear probability model is superior than Logit model and Probit model, apart from its simplicity.
Comment: Superior in what sense? If you think in terms of generalization, then according to Free Lunch theorem no model is the best or superior to all others considering all possible datasets.
Comment: Thank you for your response. Actually i want to know that in what circumstances linear probability  model can be preferred over Logit and probit model?
Comment: This is about link functions. The probit link function enables to deal with probability units, while the logit link function with log odds. It is computationally simpler to work with the latter. The logit link function is also useful when working with multinomial dependent variables. All in all it seems that the difference is about how the predicted value is used.
Answer: I can think of a special case where no link function is superior to any other link function. In that case a linear probability model (identify link function) is as good as a logit, probit, cloglog, or any other link function you can imagine, and the simplicitly of interpreting a linear probability model could in that special case decisively tip the balance.
That special case is a fully saturated model, i.e. a model that includes only categorical explanatory/predictor/independent/right-hand-side/$x$-variables and includes all possible (higher order) interactions. In that case the predicted probabilities will be exactly the same regardless which link function you use and correspond to the means of the dependent variable within each combination of predictor variables. Since the predicted probabilities are guaranteed to be exactly the same regardless which link function is used, the fit of these different models is also exactly the same.

Linear probability model


Why doesn't g++ see boost::regex_search() function?

Question: I am trying to compile against the boost::regex library, but as soon as I try and use the regex_search() function, it barfs:
$ g++ -Wall -L/cygdrive/c/Users/Adrian/Downloads/boost_1_53_0/stage/lib  -std=c++0x exec.cpp -lboost_regex -o exec
exec.cpp: In function 'int main(int, char**, char**)':
exec.cpp:32:3: error: 'regex_serach' is not a member of 'boost'
makefile:3: recipe for target `exec' failed
make: *** [exec] Error 1

Here is the some sample code that brings up this error:
#include <boost/regex.hpp>

int main(int argc, char* argv[], char* env[])
{
  typedef boost::match_results<string::const_iterator> matches_t;
  typedef matches_t::const_reference match_t;
  boost::regex x("");
  string str;
  matches_t what;
  boost::match_flag_type flags = boost::match_default;
  boost::regex_serach(str.begin(), str.end(), what, x, flags);
  return 0;
}

Line 32 is the line where regex_search is on.  The g++ version is 4.5.3 under cygwin.  Boost version is 1.53.  If I comment out the regex_search line, it compiles fine.  Ideas?
Answer: #include <boost/regex.hpp>

int main(int argc, char* argv[], char* env[])
{
  typedef boost::match_results<std::string::const_iterator> matches_t;
  typedef matches_t::const_reference match_t;
  boost::regex x("");
  const std::string str;
  matches_t what;
  boost::match_flag_type flags = boost::match_default;
  regex_search(str.begin(), str.end(), what, x, flags);
  return 0;
}

Three issues - string is in std namespace, requires to be called out accordingly. Second the regex_search template defines an iterator for a const string so declare it that way. Lastly regex_search is not part of boost namespace and
 there was a typo in the regex_seRAch. The above compiles and executes fine against boost 1.53.
Comment: The 1st is a non-issues as I forgot to include the `#include` and `using namespace std;`.  I didn't realise that the iterator didn't get const promoted.  Hrm.  And thanks for catching my typeo. Doh!
Comment: Ah, I understand.  [This example](http://stackoverflow.com/a/14571400/1366368) shows why.


Assigning retained object to __unsafe_unretained variable , but why don't it crash?

Question: As far as I know str1 is released after assignment. I just receive warning but why don't it crash?
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController * vc = [[UIViewController alloc] init] ;
    self.window.rootViewController = vc ;
    [self.window makeKeyAndVisible];

    NSString * __unsafe_unretained str1 = [[NSString alloc] initWithFormat:@"First Name: %@", @"cc"] ;
    // I think it should crash here !
    NSLog(@"string: %u", [str1 length]) ;

    NSString * __weak str2 = [[NSString alloc] initWithFormat:@"First Name: %@", @"cc"] ;
    // nil for str2
    NSLog(@"string: %@", str2) ;

    return YES;
}
</code>
It may be clear if I modify the code like this.
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController * vc = [[UIViewController alloc] init] ;
    self.window.rootViewController = vc ;
    [self.window makeKeyAndVisible];

    NSString * __unsafe_unretained str1 = [[NSString alloc] initWithFormat:@"First Name: %@", @"cc"] ;
    // I think it should crash here !
    NSLog(@"string: %u", [str1 length]) ;

    TestObject * __unsafe_unretained obj1 = [[TestObject alloc] init] ;
    NSLog(@"obj1:%@", obj1) ;

    return YES;
}
</code>
TestObject.m:
<code>@implementation TestObject

- (void)dealloc
{
    NSLog(@"%@, %@", NSStringFromSelector(_cmd), self) ;
}

@end
</code>
The log is
<code>2013-12-09 15:49:08.625 xxx[23950:a0b] string: 14
2013-12-09 15:49:08.627 xxx[23950:a0b] dealloc, <TestObject: 0x8970ff0>
2013-12-09 15:49:08.627 xxx[23950:a0b] obj1:<TestObject: 0x8970ff0>
</code>
Comment: are you using `str1` outside the local pool / method?
Comment: @AnoopVaidya No, I just use it to test arc and study about it.
Comment: It is considered an error to use, but the memory will not be deallocated until the end of the run loop, when the autorelease pool drains. (This behavior may be different with code optimization enabled.)
Comment: It will crash if use that string afterwords...like `NSString *str2=[NSString stringWithFormat:@"%@",str1];`
Comment: @preetam Yes, you are right, but why?
Comment: @AaronBrager You mean str1 is marked autoreleased? As @preetam said, it will carsh if use it like `NSString *str2=[NSString stringWithFormat:@"%@",str1];`, so I don't think so.
Answer: There are two possible things happening there.
Aaron Brager covered one of them - if an object is in an autorelease pool, the pool doesn't drain until the next cycle of the run loop so the object will be granted a temporary reprieve. However ARC is able to elide many instances of autorelease and is doing so in this case.
So the answer is that the memory has not yet been overwritten so your calls appear to work fine. But that's just an accident. If we reorder things a bit we get a very different result:
<code>    NSString * __unsafe_unretained str1 = [[NSString alloc] initWithFormat:@"First Name: %@", @"cc"];

    // I think it should crash here !

    TestObject * __unsafe_unretained obj1 = [[TestObject alloc] init];
    NSLog(@"obj1:%@", obj1);

    //oops, crash!
    NSLog(@"string: %u", [str1 length]);
</code>
In this case, the memory pointed to by str1 was overwritten by the allocated TestObject, so the first pointer-sized byte was changed from pointing at NSString's isa to TestClass' isa. That means asking for length will fail. But obj1 is just as invalid as str1... That memory is in the free list now, just waiting to be re-used. In actual fact it contains random junk, it just so happens that the junk "appears" to be a valid Objective-C object until it is reused.
If you add a length method to TestClass, my example will appear to work again! Don't be deceived... The C standard says that accessing an invalid pointer is undefined behavior, meaning the compiler is free to format your hard drive, delete all your contacts, or do anything at all. It can even do this before the first instruction in your program is executed because a program that contains undefined operations is entirely undefined. (It is not defined right up until the moment it does something crazy, it is undefined in its entirety).
So the short version is: You performed an undefined operation (accessing a free'd pointer), and rather than formatting your hard drive, the compiler decided to pretend your program made sense. That is merely an artifact of the compiler's optimizations and how memory happened to be used, but the outcome is just as meaningless as printing "Hippo" and exiting. (Or more practically, run with the Zombies instrument and/or guard malloc enabled and you will find your original code example crashes immediately).


I see an additional SSHD connection established from an IP that I don't recognise. Should I be worried? (output included)

Question: Here's the output (I've changed my IP to 22.214.171.124)
    [root@web01 centos]#  lsof -i tcp:22
    COMMAND   PID   USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
    sshd     3705   root    3u  IPv4   43164      0t0  TCP *:ssh (LISTEN)
    sshd     3705   root    4u  IPv6   43166      0t0  TCP *:ssh (LISTEN)
    sshd    32064   root    3u  IPv4 8676370      0t0  TCP web01.internal:ssh->22.214.171.124:33976 (ESTABLISHED)
    sshd    32160   root    3u  IPv4 8673203      0t0  TCP web01.internal:ssh->23-23-23-23.static.isp.com:filesphere (ESTABLISHED)
    sshd    32168 centos    3u  IPv4 8673203      0t0  TCP web01.internal:ssh->23-23-23-23.static.isp.com:filesphere (ESTABLISHED)

The unknown IP: 22.214.171.124 - on a quick Google search I found out it's from China and has been reported for abuse a few times.
How bad is this? What should I do from here?
Answer: You probably get a lot of those any day. Some bots try common user names/passwords on every internet facing sshd they can find.
You can do a last to see if there is an actual login (not just a connection) from an unknown address and check /var/log/auth. Note though that if the system was compromised you'll probably find nothing there.
And consider using fail2ban to automatically ban ip addresses that try to connect too many times.


How to detect API call from Zapier?

Question: Is there any way to detect API call from Zapier to my app?
I've created two zaps on Zapier. Creating tasks from Wrike to MyApp and vice versa.
I got infinite loop, because when I create task on Wrike it is automatically created on MyApp. But than Zapier detects new task on MyApp and creates new one (same task) in Wrike and so on.
I was thinking to add new field in task object (createdFromZapier) and filter by that field, but is there any other way to handle this?
Answer: Here is answer from Zapier team:
There isn't a great way to do this — at best, you could set the User Agent header within your developer integration and then inspect the header on your API server side to detect when a request is coming from Zapier.
We have a help guide on avoiding Zap loops at https://zapier.com/help/troubleshoot/behavior/zap-is-stuck-in-a-loop which might help.

How to detect API call from Zapier?


When trying to create lists of CA atoms, I get the following error "key error 'CA' when executing the following code

Question: For the following code, when I execute the code I get an error, which I've listed below. I was wondering if anyone could give me any insights into how to append the CA atoms into tag_atoms/tagged_atoms lists, which I will use for alignment. And highlight any potential flaws in the way the code is written which I would be overlooking. I'm new to python, so any insight would be great and very helpful.
def loadPDB(pdb_name):

    folder = pdb_name[1:3]
    pdbl = PDB.PDBList()
    pdbl.retrieve_pdb_file(pdb_name)
    parser = PDB.PDBParser(PERMISSIVE=1)
    structure = parser.get_structure(
        pdb_name, folder + "/pdb" + pdb_name + ".ent")

    return structure

def alignCoordinates(taggedProtein, potentialTag):
    for model in taggedProtein:
        firstModel = model
        break
    for chain in firstModel:
        firstChain = chain
        break

    for firstChain in firstModel:
        tagged_atoms = []
        tag_atoms    = []

        for residue in firstChain:
            tagged_res = residue

        for tagged_res in firstChain:
            tagged_atoms.append(firstChain['CA'])

    for model in potentialTag:
        firstTagModel = model
        break

    for chain in firstTagModel:
        firstTagChain = chain
        break

    for residue in firstTagChain:
        tag_res = residue

        for tag_res in firstTagChain:
            tag_atoms.append(firstTagChain['CA'])

    super_imposer = Bio.PDB.Superimposer()
    print repr(tagged_atoms)
    print repr(tag_atoms)
    super_imposer.set_atoms(tagged_atoms, tag_atoms)
    super_imposer.apply(tag_model.get_atoms())

    print super_imposer.rms

    io = Bio.PDB.PDBIO()
    io.set_structure(tag_model)
    io.save("Aligned.PDB")

def main():

    pdb1 = "2lyz"
    pdb2 = "4abn"

    potentialTag  = loadPDB(pdb1)
    taggedProtein = loadPDB(pdb2)

    alignCoordinates(taggedProtein, potentialTag)

main()

This is the error message below:
Structure exists: '/Users/Azi_Ts/Desktop/ly/pdb2lyz.ent'
Structure exists: '/Users/Azi_Ts/Desktop/ab/pdb4abn.ent'
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:87:          PDBConstructionWarning: WARNING: Chain A is discontinuous at line 13957.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:87:   PDBConstructionWarning: WARNING: Chain B is discontinuous at line 14185.
  PDBConstructionWarning)

Traceback (most recent call last):
  File "alignPDB.py", line 76, in <module>
    main()
  File "alignPDB.py", line 74, in main
    alignCoordinates(taggedProtein, potentialTag)
  File "alignPDB.py", line 39, in alignCoordinates
    tagged_atoms.append(firstChain['CA'])
  File "/Library/Python/2.7/site-packages/Bio/PDB/Chain.py", line 70, in    __getitem__
    return Entity.__getitem__(self, id)
  File "/Library/Python/2.7/site-packages/Bio/PDB/Entity.py", line 38, in   __getitem__
    return self.child_dict[id]
KeyError: 'CA'

Answer: To get all the CA atoms you only have to do:
ca_atoms = [atom for atom in taggedProtein.get_atoms() if atom.name=="CA"]

Remember that the structures loaded, taggedProtein and  potentialTag, have three methods that might be useful here: get_chains(), get_residues() and get_atoms(). Using those three you could get rid of every for loop you have in def alignCoordinates().


How to customize collection rendering when using active_model_serializers?

Question: I am using active_model_serializers to render a collection as JSON for ember-data consumption.
All is ok when rendering a single item, but collection rendering consists as an array of items.
render json: @scenarios, status: :ok

gives:
[{"scenario":{"id":4,"name":"My sample scenario"}},{"scenario":{"id":5,"name":"Yet another sample scenario"}}]

but I would like to obtain:
{"scenarios": [{"id":4,"name":"My sample scenario"},{"id":5,"name":"Yet another sample scenario"}]}

What is the state of the art way to get a root key with all collection items, side-data, and so on? (the documentation is not that clear about this)
EDIT
The scenario serializer is currently as follow:
class ScenarioSerializer < ActiveModel::Serializer
  attributes :id, :name
end

Comment: http://railscasts.com/episodes/322-rabl
Comment: @jdoe Thanks for your suggestion, but I would like to keep using active_model_serializers as I don't want to have code myself all the serialization concerns.
Comment: What does your scenario_serializer.rb (or equivalent) look like?
Comment: @pansapien Just updated the question...
Comment: Does 'embed :ids' make any difference? I'm getting the JSON formatted as you desire yours to be, but that's the only difference I have with my code. It's not clear to me that it should make a difference, but would be something to try.
Comment: @pansapien Thks again for your time, but it does not work for me. :-(
Certainly something somewhere has to be different...
Answer: Try the latest version. AMS uses the controller name as the key for an array. By default it should render like you showed above.
If your controller is not named ScenariosController, you can force the root element of the array like this:
render json: @scenarios, root: "scenarios", status: :ok

Comment: That's right. In fact, I had a mistake elsewhere... some of my model classes had a custom `to_json` implementation which I missed... :-(
Comment: Cool. In general, there is better handling of arrays in AMS now.


Dimensionality not matching for differential of matrix with orthogonality constraints

Question: I was reading through the following answer out of curiosity about calculating the differential of a matrix with orthogonality constraints. Briefly the mathematics works out as follows:
$
\text{Let } X \in \mathbb{R}^{m\times n}, \text{ so that } X^TX=I_{n\times n}, \text{ } m > n
$
$
\text{Then }, d(X^TX)= dX^T X + X^T dX = 0
$
I originally saw no problem with that except then I noticed that: $dX^T X\in \mathbb{R}^{n\times n}$ and $dX X^T\in \mathbb{R}^{m\times m}$.
If these two matrices have different dimensions ... how is the addition over the matrices even defined? Or how should one interpret this at all?
Comment: There is no $dX X^T$ involved, only $dX^T X$ and $X^T dX$.
Matrix multiplication is not commutative.
Comment: oh! it must have been a silly transcription on my part. I've just been looking at too many symbols today it seems ..
Answer: $\newcommand{\R}{\mathbb{R}}$
$dX\in \R^{m\times n}$, and it will be clearer if you use brackets:
$$d(X^TX) = (dX)^TX + X^T(dX) = 0,$$
both terms are in $R^{n\times n}$. Equivalently, if $\Delta_X$ is tangent to the Stiefel manifold at $X$, differentiate the relation $X^TX=I$ in direction $\Delta_X$ shows $(\Delta_X)^TX + X^T(\Delta_X) = 0$, or $X^T\Delta_X$ is antisymmetric.
Comment: Thank you the bracketing idea is actually quite helpful.


Preciso de obter a lista de musicas

Question: Eu queria imprimir a lista de músicas guardadas num array listaMusica:
   System.out.println(p.listarMusicas());

Este é o método para guardar os dados:
  Musica v = new Musica(t, a, d, ano, g);
                         p.addMusica(v);

 public void addMusica(Musica música) {
    if (_musicas < _capacidade) {
        _listaMusica[_musicas] = música;
        _musicas++;
    }
}

E este é o método listarMusicas():
   public String listarMusicas() {
    String res = "";
    for (int i = 0; i < _musicas; i++)
        res += i + ": " + _listaMusica[i].getTítulo();
    return res;
}

Vou disponibilizar todo o código agora neste link:
http://pastebin.com/4rY6dtab
Aceito sugestões.
Comment: Não entendi. O que você quer fazer? O método listarMusicas() já responde a tua pergunta. Talvez se adicionar um \n depois de getTitulo() fique melhor de ler, mas não sei se é isso o que você quer.
Comment: Por que você não usa `List`?
Comment: Quando eu faço isso ele nao mostra realmente a lista de musicas
Comment: Algum pode ajudar-me?
Answer: O código está extremamente difícil de manter, e por isso possui alguns bugs que você deverá resolver (vide abaixo).
Mas para imprimir a lista, sugiro criar um método toString() na classe Música:
@Override
public String toString() {
    return "Musica [_titulo=" + _titulo + ", _autor=" + _autor
            + ", _duracao=" + _duracao + ", _ano=" + _ano + ", _genero="
            + _genero + "]";
}

Assim fica mais fácil de iterar sobre o array.
No método listarMusicas() chame esta lista e use um StringBuilder (que é mais eficiente) para concatenação de Strings:
public String listarMusicas() {
    StringBuilder sb = new StringBuilder();
    for(Musica m: _listaMusica) {
        if(m!=null) {
            sb.append(m);
        }
    }
    return sb.toString();
}

Feito isso, o seu código ainda possui alguns problemas que precisam ser corrigidos. Vou listá-los aqui:

Não use um Array para a lista de músicas. Use uma List<Musica>. Esta é a estrutura correta para o seu caso, em que a lista pode crescer e diminuir. Outro motivo é não precisar checar se o elemento é nulo. A List tem o tamanho exato que você precisa, e poderá usar o forEach para iterar sobre ela facilmente.
Não use a variável _musicas para controlar o tamanho do Array (ou da Lista). O Array possui a propriedade length e a List possui um size().
Ao remover uma música da lista, ele faz _musicas--. Só que se remover várias vezes, a variável fica negativa! Isso gera um ArrayOutOfBoundsException. Mais um motivo para não controlar isso por fora.
Não use variáveis com underscore (_), pois diminui a legibilidade.
Não use variáveis com acentos e caracteres fora do padrão (getTítulo, getDuração). Isso vai te facilitar quando abrir o código por outros editores (ou outras pessoas usarem).

Boa sorte no seu trabalho.

Preciso de obter a lista de musicas


Multilinear transformations being determined by their values on basis elements

Question: The following is stated in the book Analysis on Manifolds by James Munkres

Just as is the case with linear transformations, a multilinear transformation
  is entirely determined once one knows its values on basis elements. That
  we now prove.

And then he gives the following lemma.

Lemma 26.2 Let $a_1, \dots, a_n$ be a basis for $V$. If $f, g : V^k \to \mathbb{R}$ are $k$-tensors on $V$ and if $$f\left(a_{i_1}, \dots, a_{i_k}\right) = g\left(a_{i_1}, \dots, a_{i_k}\right) $$ for every $k$-tuple $I = (i_1, \dots, i_k)$ of integers from the set $\{1, \dots, n\}$ then $f=g$.

Now what I don't understand is why to we even need the following in the above lemma

"for every $k$-tuple $I = (i_1, \dots, i_k)$ of integers from the set $\{1, \dots, n\}$"

Because $V^k$ has dimension $k \cdot n$ since $V$ has dimension $n$, and has as basis elements \begin{align*}&(a_1, 0,  \dots, 0), \dots, &(a_n,0, \dots, 0), \\
&(0, a_1, \dots, 0), \dots, &(0, a_n, \dots, 0), \\
 \ \ \ &. &. \\
 \ \ \ &. &. \\
 \ \ \ &. &. \\
&(0, 0, \dots, a_1), \dots, &(0, 0, \dots, a_n)
\end{align*}
So if $\mathcal{B}$ was the set of basis elements of $V^k$ above then I'd say that the following proposed lemma would make more sense

Proposed Lemma: Let $V$ be a vector space of dimension $n$. If $f, g : V^k \to \mathbb{R}$ are $k$-tensors on $V$ and if $$f(\alpha) = g(\alpha)$$ for every $\alpha \in \mathcal{B}$ where $\mathcal{B}$ is a basis for $V^k$, then $f= g$

Furthermore the same part of Lemma 26.2

"for every $k$-tuple $I = (i_1, \dots, i_k)$ of integers from the set $\{1, \dots, n\}$"

Taken literally gives $n^k$ possible $k$-tuples, which would correspond to checking to see if the values of $f$ and $g$ agree on $n^k$ basis elements, which confuses me since $\dim(V^k) = kn$
I'm sure that Lemma 26.2 must be correct and I'm just making some error somewhere, if so could someone please point out what that error is.
Comment: take a look at how this construction looks for $V=\Bbb R^1$ or  $V=\Bbb R^2$ or $V=\Bbb R^3$ with $k=1$ or $=2$ or $k=3$
Comment: @janmarqz Okay so take the case $V = \mathbb{R}^2$ and $k=2$, suppose $f, g : V^2 = \mathbb{R}^4 \to \mathbb{R}$ are two $2$-tensors, by the above theorem we need to show $$f(e_1, e_1) = g(e_1, e_1);\\ f(e_1, e_2) = g(e_1, e_2);\\ f(e_2, e_1) = g(e_2, e_1); \\  f(e_2, e_2) = g(e_2, e_2);$$ for basis elements $e_1 = (1, 0)$ and $e_2 = (0, 1)$ of $\mathbb{R}^2$. But for example $(e_1, e_1) = (1, 0, 1, 0)$ is not a basis element of $\mathbb{R}^4$
Comment: So I take it that Munkres is referring to basis elements of $V$ as opposed to $V^k$
Comment: for bilinear maps $\Bbb R^2\times\Bbb R^2\to\Bbb R$ (which is a vector space) you only need the 4 basic "vectors":
$$\left(\begin{array}{cc}1&0\\0&0\end{array}\right)$$
$$\left(\begin{array}{cc}0&1\\0&0\end{array}\right)$$
$$\left(\begin{array}{cc}0&0\\1&0\end{array}\right)$$
$$\left(\begin{array}{cc}0&0\\0&1\end{array}\right)$$
Comment: @janmarqz But that's not what the theorem above asserts..
Answer: The dimension of $\underbrace{V\otimes\dots\otimes V}_{k \text{ times}} = \bigotimes^k V$ is $n^k$, even though the dimension of $V^k$ is $kn$. We're talking about multilinear maps on $V^k$, not linear maps. (Note that $n=k=2$ is a bad example to pick, since then $kn = n^k$. :))
EDIT: I should comment that the vector space of multilinear maps on $V^k$ is isomorphic to $\big({}\bigotimes^k V\big)^*$, but dimensions are the same.
Comment: Right. That's why we're considering the $n^k$ $k$-tuples $(a_{i_1},\dots,a_{i_k})$.
Comment: Thanks for your answer Ted! Just one follow up question, you're saying then that Munkres is talking about basis elements from $\bigotimes^k V$ and not $V^k$, correct?
Comment: Okay thanks again Ted! :)


Do I need a second RAID controller for fault-tolerance?

Question: I have a server with 3 hard drives installed, and a total capacity of 6. We're planning to max it out, but our consultant also suggested getting a second RAID controller "for redundancy" to support the new drives. To me, this doesn't make much sense. Even with a second RAID controller running half of the disks, we're still stuck with only half of our disks/programs/data if one of the controllers dies (which isn't much better than running with none). We're putting vmware on the server and he vaguely mentioned some advanced fault tolerance/failover features, but if the disks are inaccessable due to a failed controller, how is it supposed to work?
Counting only reasons for redundancy, not performance, why would I want to have a second RAID controller in my server?
Comment: I have seen a history when the only RAID controller failed, making the multi-disk high RAID storage it has been servicing alone not just unusable but even all data there unrecoverable. It was a heavy blow to the company. Ultimately most of data has been reconstructed from the files found in workstations. Total shame. Always mirror data on the independent disk cluster with obviously another controller. Never assume RAID 6 will save your life in all cases if you rely on a single small card that gets 80° C hot while operating for many years 7/24.
Answer: In a 'single box high availability' design then yes, you'd want a second controller, ideally on a second bus too. But this kind of approach has given way to a cheaper design based around clustering where one box failure doesn't stop service. So it depends on if you plan to use a clustered environment or rely on a single box. Even if your answer is the latter having dual controllers may be seen as adding extra complexity and maybe being overkill.
edit - based on your comment about using ESXi on your other question I'd have to say that its clustering is fabulous, we have many 32-way clusters that work brilliantly.
Comment: Not in an ESX/ESXi world no - a single one would be fine, make sure you get a controller that will make one big R10 array of all 6 disks but allow you to create these 2TB (or less) logical disks ok. HP's Pxxx-series let you do that btw.
Comment: AFAIK, we're not going to use clustering. How would a second controller in a single box benefit me? Is there such a thing as controller failover?
Answer: A second RAID controller which is actively used is not for redundancy. Only if it is a cold-stand-by controller where you switch all your disks to when the first one dies. Then you have redundancy (for the controller). But beware of doing so, as posted here.
So the RAID is for redundancy of disks leading to a single point of failure at the controller. Having a second (unused) controller may solve this as you could switch all the disk to the new one. If this works depends on other factors...
I'm no native speaker, but for me "fault-tolerance" is something different than "redundancy". Can some English speaker help me out here?
Comment: Redundancy is a way of achieving fault-tolerance :). I was looking for something along the lines of a cold-standby or a failover controller. Is this a feature that's supported, or would I have to manually swap out the cards?
Comment: I have never seen a controller where the switching of disks is done automatically. This is either because I didn't looked for it or because I can't imagine how you should circuit the cables between one disk and two controllers.
Comment: Dual-ported drives are quite common in enterprise environments (think SAN shelves) - but the prices go up by a factor of 2 or 3, obviously.
Answer: On a single box, you actually need two RAID controllers, connected to two different PCI-E root complexes, to have complete I/O subsystem redundancy. This can be achieved by two different configuration:

use costly dual ported SAS disks, with each SAS link connected to a different controller. In this manner, each controller is connected to each disk. Obviously, the two controller can't operate on disks at the same time; some form of locking/fence is necessary to coordinate access to disks. SCSI has some special provision to provide the necessary fencing mechanism, but these must be coordinated by appropriate software. In other words, you can not simply connect a disk to two controller and call it a day; rather, you need appropriate software configuration to let it works without problems;
use normal and cheaper single link SAS/SATA disks, connecting one half of them to each controller. For example with 6 disks, you need to connect 3 disks to a controller and 3 disks to another controller. On each controller, configure a RAID array as needed (eg: RAID 5 or RAID1). Then, at the OS level, you can configure a software RAID between the two disk arrays, achieving full array redundancy. While cheaper, this solution has the added drawback to effectively halve your storage capacity (due the the software RAID1 level).

A key problem with both approach is that you do not have full system redundancy: a motherboard/CPU problem can bring down the entire system, independently from how much controllers/disks you have.
For this reason, this kind of redundancy-in-a-box is seldom used lately (apart that in mid/high-end SAN deployments); rather, clustering/network mirroring is gaining wide traction. With clustering (or network mirroring) you have full system redundancy, as a single failed system can not negate data access. Obviously clustering has its own pitfalls so its not a silver/easy bullet, but in some situation its advantages can not be negated. Moreover, you can also use asynchronous network mirroring to have an almost-realtime data redundacy on geographically different location, so that a single catastrophic event will not wreak havoc on your data.
Comment: It depends on the underlying replication mechanism. DRBD, for example, enable the use of a full (protocol C) or near-full (protocol B) synchronized replication. This means that when a write is acknowledge on the source host, it is actually commited on the remote host also In other words, write barriers are honored on both hosts). With such guarantee, any robust filesystem/database should recover without problems.
Comment: Yes,  some databases support the replication, and some other applications also. These are obviously much easier to work with.
Comment: With some kinds of data the copy that is only half updated (because the synchronization failed in the midway) may be unusable. A database is the typical example, but also various source code and data sets with lots of small files that are closely depent on each other.
Answer: You'd need dual-ported SAS drives to provide actual failover on multiple controllers.
While these do exist, it is decidedly uncheap - not in the price range of a single server that only has internal storage.
These are technologies often employed in SAN systems, where controller death is a real issue.
For a single server with no other failover capabilities, a second controller will not gain anything - it will just cost more money and provide the consultant with more profit.


Como impedir que links do AdSense abram em nova aba

Question: Existe algum método de impedir que meu site abra links em nova aba e fazê-los abrir na mesma? E o contrário? Obrigado.
Edit: Uso o Google Adsense. Alguns anúncios abrem na mesma aba, outros abrem uma nova aba. Queria bloquear que abrissem em nova aba.
Answer: Sim, para abrir sempre na mesma aba, utilize o atributo _self, e para abrir sempre outra aba, o atributo _blank.
Por exemplo:
Abre em outra página

Abre na mesma página

Edit: Dá uma olhada nesta página, principalmente nos comentários, onde tem inclusive o link para uma possível solução. Mas já adianto que, segundo consta ali, modificar o comportamento do google ad sense pode ferir os termos de serviço, e você pode inclusive ser expulso do sistema.
Comment: Editei a resposta, mas acho que não tenho boas notícias. :)
Comment: Mas onde a pessoa clica no meu site está em flash, e já está programado para abrir em nova aba.
Comment: Não existe nenhum outro método sem ser atributo? Algo que afete o site inteiro?
Comment: Ah, neste caso eu não sei, acho que vc tem que configurar isso no próprio flash, mas pode ser que exista mesmo algo em js... Sugiro que edite a pergunta pra incluir mais detalhes, principalmente informando que o site está em flash...
Comment: O site não está em flash. É porque tem anúncios do Google Adsense. Alguns abrem em nova aba, outros não.
Comment: Se ainda nao conhece as regras, leia antes de fazer kaka


Hanon and Self-Taught Bad Technique

Question: I was looking at the question about the benefits of working from Hanon to improve on piano and there was a lot of talk about the dangers of Hanon reinforcing bad technique.
If I am a self-teaching pianist wishing to work exercises like Hanon to improve my chops but don't want to reinforce or worsen bad technique (I''m assuming my technique isn't great) and can't really afford dedicated piano lessons, how can I learn good technique?
Answer: You have almost answered this in the question - you really do need lessons from an experienced instructor to make sure you learn good technique.
I'm not saying you need a full course necessarily, but especially at the start there is no alternative, and you'll want to have a check at regular points through your learning.
Comment: I would agree about lessons being the only real way to get "proper" technique. Tim has a point that this can be rather subjective but there are definitely objective things about it. Such as poor technique causing physical ailments, such as tendinitis. A piano teacher I once had told a story of how he had been playing using almost entirely his fingers to control dynamics. Proper technique instructs a player to use the motion of the arms and/or wrist to facilitate the louder dynamics. He was already an accomplished player at the time and he said this change greatly helped his playing and health.
Comment: +1 for the 2nd para. Don't think 'good technique' can be learned  in a couple of lessons, and after those, bad habits will creep in at various stages. However, I feel that 'good' or 'bad' techniques are rather subjective. Maybe the basis for a future question...
Answer: The cheapest way to learn good technique is also the slowest and most risky - trial and error. Why are all techniques not created equal? Two big reasons: First, poor technique will limit your ability and quality of your playing. Second, poor technique can lead to repetitive motion injury and limit or halt your ability to play at all.
Since you write that you are trying to improve, you will probably be trying to improve for as long as you are playing, and that means you will be pushing yourself a little. Limits on playing ability will frustrate you and pushing yourself to practice more with poor technique increases your chances of injury. You can attempt more and more difficult pieces on your own and constantly try alternative techniques as you experience trouble with the pieces or discomfort after playing, but it's a bit risky and a long tedious process. I speak from experience.
You could try searching YouTube for technique videos but the best thing is to save your pennies and try to get a good teacher to meet with you at least once a month. Tell them that you are motivated to put in the practice and you really want help with technique and they should be able to address your particular hands and any existing bad habits in a way that any other resource can't.
I've never regretted saving and spending the majority of my disposable income on music.

Hanon and Self-Taught Bad Technique


Generalizing / Refactoring the code

Question: My code is something like this :
if(country == china)
{
getCNData();

}

else {
getDefaultDataForallCountries();

}

Now I need to add similar logic as CN for some other country say  US . The option available to me is to  add one more country check in if condition and make it like
if(country ==china && country==US){
getCNandUSData();

}

else {
getDefaultDataForallCountries();

}.

1) I am somehow not comfortable to go for this solution as this is not generic . What if tomorrow I need to have same CN logic applied to another country say france . Can you please suggest me how can I make my code better and more generic.
2) Also I am not comfortable with the naming conventions. If say I go with my approach of adding US in If condition , Should I refactor the class name and function name to getCNAndUSData () ?
I am not sure here of what is the correct way to deal with such existing code.
Appreciate your comments.
Comment: I doubt (country==china && country==US) could ever possibly evaluate to true... unless US and china are equal of course :P
Answer: This type of issue (overuse of "if" and "switch" statements) is neatly handled by implementing a strategy pattern with a abstract factory.  Basically you want to change the algorithm without changing your implementation and duplicating the code over and over and over.
Enjoy!
Answer: use enums.
enum Country
{
    China,
    USA
};

your code will be refactored to this:
switch(country)
{
        case China:
        case USA:
           getCNAndUSData () ;
           break;
        ... //Here can be another countries
        default:
           getDefaultDataForallCountries()
}

Answer: You most likely would be better off using a "switch" statement..
switch (  ) {
case this-value:
  Code to execute if  == this-value
  break;
case that-value:
  Code to execute if  == that-value
  break;
...
default:
  Code to execute if  does not equal the value following any of the cases
  break;
}
Read more: http://discuss.itacumens.com/index.php?topic=22753.0#ixzz11OXV6caP
Answer: You could bitwise comparison. This means assigning each country a bit:
#define China 1
#define US 2
#define France 4

Then you can compare like this:
if (country&(US|China)) {
  // ...
}

And about your naming problem, you could just use a generic name like getSpecificData(). Though I don't really understand your context.
Comment: Please don't EVER consider using `#define` for constants in C++ code. Be thankful that I am not sitting in the same room you are, I would have bashed you on the head.
Answer: Here is a very very broad skeletal outline based on LSP/Strategy Design Pattern which should give you the idea.
struct country{
    void getdata(){return dogetdata();}
    virtual ~country() = 0;
private:
    virtual void dogetdata() = 0;
};

country::~country(){}

void country::dogetdata(){
    // logic for default data for all countries
}

struct china : country{
private:
    void dogetdata(){return ;}
public:
    ~china(){}
};

struct xyz : country{
private:
    void dogetdata(){return ;}
public:
    ~xyz(){}
};

void get(country *p){
    p->getdata();
}

int main(){
}

Comment: dogetdata() needs to be protected in the base class (public would technically work as well but I'm sure that's not what you want).
Comment: @gregg: Yes, it could be protected if I wanted my derived classes to call it. That would basically depend on other design considerations e.g.
Answer: As suggested the case structure can be used here for better. In you case the code will be

switch (country)
      case China:
            GetCNData();
            Break;
      case US:
            GetUSData();
            Break;
      default:
            GetGenericData();

In case you think the GetUSData and GetCNData are same, then you can simply call GetCNData() from GetUSData().

GetUSData()
  {
  GetCNData();
  }

If you want to have compile time independence, then use virtual inheritance. Create a base class named Country and have the method GetData() in it. Now Create other country classes by inheriting this and by changing the GetData() method appropriately.
This can also be done using the templates, not sure how.

Generalizing / Refactoring the code


Decide if series convergent or divergent, and if convergent finding sum.

Question: I need to decide if this series is convergent or not, and if it is to find its sum.
$$\sum_{n=1}^\infty \frac{1}{(n+3)(n+4)}$$
I think it is convergent as $$\lim_{n \to \infty}\frac{1}{(n+3)(n+4)}=0$$
From this point though I do not know how to obtain its sum.
Comment: See https://en.m.wikipedia.org/wiki/Telescoping_series
Comment: In general it's dangerous to assume that a series converges if the individual terms of a series approaches 0. For instance, the harmonic series famously diverges, despite the fact that $1/n\rightarrow 0$.
Comment: $\displaystyle \lim_{n\to\infty} \frac 1 n = 0 \text{ but } \sum_{n=1}^\infty \frac 1 n \text{ diverges.}$ So your reason for thinking it converges is not good enough by itself.
Answer: Hints:

For convergence use comparison test.
To obtain its sum use the identity $\displaystyle \frac{1}{(n+3)(n+4)} = \frac{1}{n+3}-\frac{1}{n+4}$

Note: If $\lim_{n\to\infty} a_{n}=0$ then it need not imply that $\sum a_{n}$ converges. Example $a_{n}=\frac{1}{n}$.


Find $\int \frac{x^2}{2x-1}\mathrm{d}x$

Question: Use the substitution $2x-1$ to find $\int  \frac{x^2}{2x-1}\mathrm{d}x.$
I started out by using the substitution to find $\mathrm{d}x$ in terms of $\mathrm{d}u$.
$$
\frac {\mathrm{d}u}{\mathrm{d}x} = 2
$$
$$
\mathrm{d}x = \frac {1}{2}\mathrm{d}u
$$
Now the question looks like this:
$$
\int \! \frac{x^2}{u} \, \cdot \frac {1}{2}\mathrm{d}u
$$
I then found $x^2$ in terms of $u$:
$$
2x-1 = u
$$
$$
x = \frac {u+1}{2}
$$
$$
x^2 = \left(\frac {u+1}{2}\right)^2
$$
I then substituted this back into the equation.
$$
\int \! \frac {(\frac {u+1}{2})^2}{u} \cdot \frac {1}{2}\, \mathrm{d}u
$$
$$
\int \! \frac {(\frac {u+1}{2})^2}{2u}\, \mathrm{d}u
$$
From here I have tried expanding out the brackets, and using a substitution to put $2u$ on the top of the fraction, but neither method got the correct answer, and I have spent a long time on the question. Am I on the right track here, or should I be approaching this any differently? Thanks
Comment: You should get $\frac{1}{8}\int(u+2+\frac{1}{u})du$ if you multiply out and simplify. (Using long division instead of substitution is another method that will work on this problem.)
Answer: $$\int\, \frac {\left(\dfrac {u+1}{2}\right)^2}{2u}\, \mathrm{d}u =\int\frac{u^2 + 2u + 1}{8u} = \frac 18 \int\left(u + 2 +\frac 1u\right)\,du $$ $$=  \frac 18 \left(\int u\,du + 2\int du + \int \frac 1u\,du\right)$$
Can you take it from here?
Comment: Yep, got it now, thanks very much!
Comment: You're welcome, Ed.
Answer: HINT
Here it is another way to solve it: consider the following algebraic manipulation
\begin{align*}
\frac{x^{2}}{2x-1} & = \frac{1}{4}\times\frac{4x^{2}}{2x-1} = \frac{1}{4}\times\frac{(4x^{2}-1) + 1}{2x-1} = \frac{1}{4}\times\left[\frac{4x^{2}-1}{2x-1} + \frac{1}{2x-1}\right]\\\\
& = \frac{1}{4}\times\left[2x+1 + \frac{1}{2x-1}\right]
\end{align*}
Can you take it from here?

Find $\int \frac{x^2}{2x-1}\mathrm{d}x$