Is this an appropriate method to test for seasonal effects in suicide count data?

Question: I have 17 years (1995 to 2011) of death certificate data related to suicide deaths for a state in the U.S. There is a lot of mythology out there about suicides and the months/seasons, much of it contradictory, and of the literature I've reviewed, I do not get a clear sense of methods used or confidence in results.
So I've set out to see if I can determine whether suicides are more or less likely to occur in any given month within my data set. All of my analyses are done in R.
The total number of suicides in the data is 13,909.
If you look at the year with the fewest suicides, they occur on 309/365 days (85%). If you look at the year with the most suicides, they occur on 339/365 days (93%).
So there are a fair number of days each year without suicides. However, when aggregated across all 17 years, there are suicides on every day of the year, including February 29 (although only 5 when the average is 38).

Simply adding up the number of suicides on each day of the year doesn't indicate a clear seasonality (to my eye).
Aggregated at the monthly level, average suicides per month range from:
(m=65, sd=7.4, to m=72, sd=11.1)
My first approach was to aggregate the data set by month for all years and do a chi-square test after computing the expected probabilities for the null hypothesis, that there was no systematic variance in suicide counts by month. I computed the probabilities for each month taking into account the number of days (and adjusting February for leap years).
The chi-square results indicated no significant variation by month:
# So does the sample match  expected values?
chisq.test(monthDat$suicideCounts, p=monthlyProb)
# Yes, X-squared = 12.7048, df = 11, p-value = 0.3131

The image below indicates total counts per month. The horizontal red lines are positioned at the expected values for February, 30 day months, and 31 day months respectively. Consistent with the chi-square test, no month is outside the 95% confidence interval for expected counts.

I thought I was done until I started to investigate time series data. As I imagine many people do, I started with the non-parametric seasonal decomposition method using the stl function in the stats package.
To create the time series data, I started with the aggregated monthly data:
suicideByMonthTs <- ts(suicideByMonth$monthlySuicideCount, start=c(1995, 1), end=c(2011, 12), frequency=12)

# Plot the monthly suicide count, note the trend, but seasonality?
plot(suicideByMonthTs, xlab="Year",
  ylab="Annual  monthly  suicides")

     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1995  62  47  55  74  71  70  67  69  61  76  68  68
1996  64  69  68  53  72  73  62  63  64  72  55  61
1997  71  61  64  63  60  64  67  50  48  49  59  72
1998  67  54  72  69  78  45  59  53  48  65  64  44
1999  69  64  65  58  73  83  70  73  58  75  71  58
2000  60  54  67  59  54  69  62  60  58  61  68  56
2001  67  60  54  57  51  61  67  63  55  70  54  55
2002  65  68  65  72  79  72  64  70  59  66  63  66
2003  69  50  59  67  73  77  64  66  71  68  59  69
2004  68  61  66  62  69  84  73  62  71  64  59  70
2005  67  53  76  65  77  68  65  60  68  71  60  79
2006  65  54  65  68  69  68  81  64  69  71  67  67
2007  77  63  61  78  73  69  92  68  72  61  65  77
2008  67  73  81  73  66  63  96  71  75  74  81  63
2009  80  68  76  65  82  69  74  88  80  86  78  76
2010  80  77  82  80  77  70  81  89  91  82  71  73
2011  93  64  87  75 101  89  87  78 106  84  64  71

And then performed the stl() decomposition
# Seasonal decomposition
suicideByMonthFit <- stl(suicideByMonthTs, s.window="periodic")
plot(suicideByMonthFit)

At this point I became concerned because it appears to me that there is both a seasonal component and a trend. After much internet research I decided to follow the instructions of Rob Hyndman and George Athanasopoulos as laid out in their on-line text "Forecasting: principles and practice", specifically to apply a seasonal ARIMA model.
I used adf.test() and kpss.test() to assess for stationarity and got conflicting results. They both rejected the null hypothesis (noting that they test the opposite hypothesis).
adfResults <- adf.test(suicideByMonthTs, alternative = "stationary") # The p < .05 value
adfResults

    Augmented Dickey-Fuller Test

data:  suicideByMonthTs
Dickey-Fuller = -4.5033, Lag order = 5, p-value = 0.01
alternative hypothesis: stationary

kpssResults <- kpss.test(suicideByMonthTs)
kpssResults

    KPSS Test for Level Stationarity

data:  suicideByMonthTs
KPSS Level = 2.9954, Truncation lag parameter = 3, p-value = 0.01

I then used the algorithm in the book to see if I could determine the amount of differencing that needed to be done for both the trend and season. I ended  with
nd = 1, ns = 0.
I then ran auto.arima, which chose a model that had both a trend and a seasonal component along with a "drift" type constant.
# Extract the best model, it takes time as I've turned off the shortcuts (results differ with it on)
bestFit <- auto.arima(suicideByMonthTs, stepwise=FALSE, approximation=FALSE)
plot(theForecast <- forecast(bestFit, h=12))
theForecast

> summary(bestFit)
Series: suicideByMonthFromMonthTs
ARIMA(0,1,1)(1,0,1)[12] with drift

Coefficients:
          ma1    sar1     sma1   drift
      -0.9299  0.8930  -0.7728  0.0921
s.e.   0.0278  0.1123   0.1621  0.0700

sigma^2 estimated as 64.95:  log likelihood=-709.55
AIC=1429.1   AICc=1429.4   BIC=1445.67

Training set error measures:
                    ME    RMSE     MAE       MPE     MAPE     MASE       ACF1
Training set 0.2753657 8.01942 6.32144 -1.045278 9.512259 0.707026 0.03813434

Finally, I looked at the residuals from the fit and if I understand this correctly, since all values are within the threshold limits, they are behaving like white noise and thus the model is fairly reasonable. I ran a portmanteau test as described in the text, which had a p value well above 0.05, but I'm not sure that I have the parameters correct.
Acf(residuals(bestFit))

Box.test(residuals(bestFit), lag=12, fitdf=4, type="Ljung")

    Box-Ljung test

data:  residuals(bestFit)
X-squared = 7.5201, df = 8, p-value = 0.4817

Having gone back and read the chapter on arima modeling again, I realize now that auto.arima did choose to model trend and season. And I'm also realizing that forecasting is not specifically the analysis I should probably be doing. I want to know if a specific month (or more generally time of year) should be flagged as a high risk month. It seems that the tools in the forecasting literature are highly pertinent, but perhaps not the best for my question. Any and all input is much appreciated.
I'm posting a link to a csv file that contains the daily counts. The file looks like this:
head(suicideByDay)

        date year month day_of_month t count
1 1995-01-01 1995    01           01 1     2
2 1995-01-03 1995    01           03 2     1
3 1995-01-04 1995    01           04 3     3
4 1995-01-05 1995    01           05 4     2
5 1995-01-06 1995    01           06 5     3
6 1995-01-07 1995    01           07 6     2

daily_suicide_data.csv
Count is the number of suicides that happened on that day. "t" is a numeric sequence from 1 to the total number of days in the table (5533).
I've taken note of comments below and thought about two things related to modeling suicide and seasons. First, with respect to my question, months are simply proxies for marking change of season, I am not interested in wether or not a particular month is different from others (that of course is an interesting question, but it's not what I set out to investigate). Hence, I think it makes sense to equalize the months by simply using the first 28 days of all months. When you do this, you get a slightly worse fit, which I am interpreting as more evidence towards a lack of seasonality. In the output below, the first fit is a reproduction from an answer below using months with their true number of days, followed by a data set suicideByShortMonth in which suicide counts were computed from the first 28 days of all months. I'm interested in what people think about wether or not this adjustment is a good idea, not necessary, or harmful?
> summary(seasonFit)

Call:
glm(formula = count ~ t + days_in_month + cos(2 * pi * t/12) +
    sin(2 * pi * t/12), family = "poisson", data = suicideByMonth)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.4782  -0.7095  -0.0544   0.6471   3.2236

Coefficients:
                     Estimate Std. Error z value Pr(>|z|)
(Intercept)         2.8662459  0.3382020   8.475  < 2e-16 ***
t                   0.0013711  0.0001444   9.493  < 2e-16 ***
days_in_month       0.0397990  0.0110877   3.589 0.000331 ***
cos(2 * pi * t/12) -0.0299170  0.0120295  -2.487 0.012884 *
sin(2 * pi * t/12)  0.0026999  0.0123930   0.218 0.827541
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 302.67  on 203  degrees of freedom
Residual deviance: 190.37  on 199  degrees of freedom
AIC: 1434.9

Number of Fisher Scoring iterations: 4

> summary(shortSeasonFit)

Call:
glm(formula = shortMonthCount ~ t + cos(2 * pi * t/12) + sin(2 *
    pi * t/12), family = "poisson", data = suicideByShortMonth)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-3.2414  -0.7588  -0.0710   0.7170   3.3074

Coefficients:
                     Estimate Std. Error z value Pr(>|z|)
(Intercept)         4.0022084  0.0182211 219.647   <2e-16 ***
t                   0.0013738  0.0001501   9.153   <2e-16 ***
cos(2 * pi * t/12) -0.0281767  0.0124693  -2.260   0.0238 *
sin(2 * pi * t/12)  0.0143912  0.0124712   1.154   0.2485
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 295.41  on 203  degrees of freedom
Residual deviance: 205.30  on 200  degrees of freedom
AIC: 1432

Number of Fisher Scoring iterations: 4

The second thing I've looked into more is the issue of using month as a proxy for season. Perhaps a better indicator of season is the number of daylight hours an area receives. This data comes from a northern state that has substantial variation in daylight. Below is a graph of the daylight from the year 2002.

When I use this data rather than month of the year, the effect is still significant, but the effect is very, very small. The residual deviance is much larger than the models above. If daylight hours is a better model for seasons, and the fit is not as good, is this more evidence of very small seasonal effect?
> summary(daylightFit)

Call:
glm(formula = aggregatedDailyCount ~ t + daylightMinutes, family = "poisson",
    data = aggregatedDailyNoLeap)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-3.0003  -0.6684  -0.0407   0.5930   3.8269

Coefficients:
                  Estimate Std. Error z value Pr(>|z|)
(Intercept)      3.545e+00  4.759e-02  74.493   <2e-16 ***
t               -5.230e-05  8.216e-05  -0.637   0.5244
daylightMinutes  1.418e-04  5.720e-05   2.479   0.0132 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 380.22  on 364  degrees of freedom
Residual deviance: 373.01  on 362  degrees of freedom
AIC: 2375

Number of Fisher Scoring iterations: 4

I'm posting the daylight hours in case anyone wants to play around with this. Note, this is not a leap year, so if you want to put in the minutes for the leap years, either extrapolate or retrieve the data.
state.daylight.2002.csv
[Edit to add plot from deleted answer (hopefully rnso doesn't mind me moving the plot in the deleted answer up here to the question. svannoy, if you don't want this added after all, you can revert it)]
Comment: The wording "one of our 50 states" implies that all readers belong to the United States. Manifestly many aliens lurk here too.
Comment: Is that from a public dataset? Could you make the week-by-week or even day-by-day data available?
Comment: @Elvis - I've posted a link to the daily count data. The data comes from death certificates which are 'public record' but require a process to obtain; however, the aggregated count data does not. PS - I tried the link myself and it worked, but I've not posted to a public dropbox folder in this way before so please let me know if the link does not work.
Comment: Since your data are counts, I'd expect variance to be related to the mean. The usual time series models don't account for that (however, you might try say a [transformation](https://en.wikipedia.org/wiki/Anscombe_transform), perhaps a [Freeman-Tukey](https://en.wikipedia.org/wiki/Anscombe_transform#Alternatives), say), or you could look at a time series model that's designed for count data. (If you don't do this it may not be a huge problem since the number only ranges over a factor of two or so.)
Comment: forecaster -- because in count data spread is related to mean. e.g. consider a Poisson count $y_t$, with mean $\mu_t$. In that case, $\text{Var}(y_t)=\mu_t$, so as the mean increases, the variance (and so also the spread) increases. [Indeed, often you find spread to be related to mean in some way for almost any data that has an upper or lower bound; there are clear reasons why this might be expected in those cases.]
Comment: Very interesting problem Can you please post the data and also please share the source for this data set?
Comment: There seem to be a trend peaking at May-July but whether it is statistically significant is the question. It may be better if you plot by day of the year (1-366) rather than plotting monthly values. It may help if you post here 366 numbers indicating number of deaths on each day of the year for entire data.
Comment: In the SARIMA model there are the seasonal `sar1` and `sma1` terms, so your statement *based on the model selected, there is a trend* ***but not a seasonal component*** does not seem right. The `sar1` and `sma1` make up the seasonal component.
Comment: Thanks Richard, I was basing my conclusion more on the fact that nsdiffs() returned zero rather than actually interpreting the model. I need to go back and more fully understand the model that was selected by auto.arima()
Comment: @forecaster - the data come from death certificate data at the (a) state level. I've "dumped" the time series, the data itself I believe is too large to go into the post.
Comment: Thanks @NickCox for cleaning up the grammar and putting in the links.
Comment: Wow, thanks. I'll try to rerun the Poisson regression with the daily data!
Comment: @Glen_b, yes! the data requires transformations as it can be seen as the level shifts in 2009, there is more fluctuations/variability. Can you please let me know how and why this happens in count data vis-a-vis time series ?
Comment: svannoy -- I took the liberty of moving rnso's plot to your Q. @rnso -- I hope you don't mind. If you have some strong objection, let me know.
Comment: I always thought this plot was useful but @Tim did not like it. I have undeleted my answer.
Comment: I like the plot, I think I should have included something like it initially anyhow. I was looking at histograms to get a sense of trend/season, but this I think is better.
Answer: What about a Poisson regression?
I created a data frame containing your data, plus an index t for the time (in months) and a variable monthdays for the number of days in each month.
T <- read.table("suicide.txt", header=TRUE)
U <- data.frame( year = as.numeric(rep(rownames(T),each=12)),
         month = rep(colnames(T),nrow(T)),
         t = seq(0, length = nrow(T)*ncol(T)),
         suicides = as.vector(t(T)))
U$monthdays <- c(31,28,31,30,31,30,31,31,30,31,30,31)
U$monthdays[ !(U$year %% 4) & U$month == "Feb" ] <- 29

So it looks like this:
> head(U,14)
   year month  t suicides monthdays
1  1995   Jan  0       62        31
2  1995   Feb  1       47        28
3  1995   Mar  2       55        31
4  1995   Apr  3       74        30
5  1995   May  4       71        31
6  1995   Jun  5       70        30
7  1995   Jul  6       67        31
8  1995   Aug  7       69        31
9  1995   Sep  8       61        30
10 1995   Oct  9       76        31
11 1995   Nov 10       68        30
12 1995   Dec 11       68        31
13 1996   Jan 12       64        31
14 1996   Feb 13       69        29

Now let's compare a model with a time effect and a number of days effect with a model in which we add a month effect:
> a0 <- glm( suicides ~ t + monthdays, family="poisson", data = U )
> a1 <- glm( suicides ~ t + monthdays + month, family="poisson", data = U )

Here is the summary of the "small" model:
> summary(a0)

Call:
glm(formula = suicides ~ t + monthdays, family = "poisson", data = U)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.7163  -0.6865  -0.1161   0.6363   3.2104

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept) 2.8060135  0.3259116   8.610  < 2e-16 ***
t           0.0013650  0.0001443   9.461  < 2e-16 ***
monthdays   0.0418509  0.0106874   3.916 9.01e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 302.67  on 203  degrees of freedom
Residual deviance: 196.64  on 201  degrees of freedom
AIC: 1437.2

Number of Fisher Scoring iterations: 4

You can see that the two variables have largely significant marginal effects. Now look at the larger model:
> summary(a1)

Call:
glm(formula = suicides ~ t + monthdays + month, family = "poisson",
    data = U)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2.56164  -0.72363  -0.05581   0.58897   3.09423

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.4559200  2.1586699   0.674    0.500
t            0.0013810  0.0001446   9.550   <2e-16 ***
monthdays    0.0869293  0.0719304   1.209    0.227
monthAug    -0.0845759  0.0832327  -1.016    0.310
monthDec    -0.1094669  0.0833577  -1.313    0.189
monthFeb     0.0657800  0.1331944   0.494    0.621
monthJan    -0.0372652  0.0830087  -0.449    0.653
monthJul    -0.0125179  0.0828694  -0.151    0.880
monthJun     0.0452746  0.0414287   1.093    0.274
monthMar    -0.0638177  0.0831378  -0.768    0.443
monthMay    -0.0146418  0.0828840  -0.177    0.860
monthNov    -0.0381897  0.0422365  -0.904    0.366
monthOct    -0.0463416  0.0830329  -0.558    0.577
monthSep     0.0070567  0.0417829   0.169    0.866
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 302.67  on 203  degrees of freedom
Residual deviance: 182.72  on 190  degrees of freedom
AIC: 1445.3

Number of Fisher Scoring iterations: 4

Well, of course the monthdays effect vanishes; it can be estimated only thanks to leap years!! Keeping it in the model (and taking into account leap years) allows to use the residual deviances to compare the two models.
> anova(a0, a1, test="Chisq")
Analysis of Deviance Table

Model 1: suicides ~ t + monthdays
Model 2: suicides ~ t + monthdays + month
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       201     196.65
2       190     182.72 11   13.928    0.237

So, no (significant) month effect? But what about a seasonal effect? We can try to capture seasonality using two variables $\cos\left( {2\pi t \over 12}\right)$ and $\sin\left( {2\pi t \over 12}\right)$:
> a2 <- glm( suicides ~ t + monthdays + cos(2*pi*t/12) + sin(2*pi*t/12),
             family="poisson", data = U )
> summary(a2)

Call:
glm(formula = suicides ~ t + monthdays + cos(2 * pi * t/12) +
    sin(2 * pi * t/12), family = "poisson", data = U)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.4782  -0.7095  -0.0544   0.6471   3.2236

Coefficients:
                     Estimate Std. Error z value Pr(>|z|)
(Intercept)         2.8676170  0.3381954   8.479  < 2e-16 ***
t                   0.0013711  0.0001444   9.493  < 2e-16 ***
monthdays           0.0397990  0.0110877   3.589 0.000331 ***
cos(2 * pi * t/12) -0.0245589  0.0122658  -2.002 0.045261 *
sin(2 * pi * t/12)  0.0172967  0.0121591   1.423 0.154874
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 302.67  on 203  degrees of freedom
Residual deviance: 190.37  on 199  degrees of freedom
AIC: 1434.9

Number of Fisher Scoring iterations: 4

Now compare it with the null model:
> anova(a0, a2, test="Chisq")
Analysis of Deviance Table

Model 1: suicides ~ t + monthdays
Model 2: suicides ~ t + monthdays + cos(2 * pi * t/12) + sin(2 * pi *
    t/12)
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       201     196.65
2       199     190.38  2   6.2698   0.0435 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So, one can surely say that this suggests a seasonal effect...
Comment: I like the idea of Poisson regression a lot (+1), I think it is a much more educated modelling assumption but "*surely say*" based on a value of 0.044? I would probably bootstrap things if anything first if I had such a $p$-value...
Comment: I totally agree, that's what I implied :) "One can surely say that this suggests an effect"; and not "There is an effect"! What I think interesting is this trigonometric transform, it is very natural and I don't understand why it's not seen more often. But this is only a starting point... bootstrapping, assessing the model... lots to do.
Comment: +1. Poisson meets Fourier.... I think economists and some others emphasise indicator variables because seasonality can be spikey, but the trigonometric approach often helps.
Comment: Indeed. A tutorial review I wrote is accessible at http://www.stata-journal.com/article.html?article=st0116
Comment: No probs! My bad then, I was unable to detect the joke. :)
Comment: @forecaster you're right, it would be interesting to check for autocorrelation of the residues. I won't have much time in the next weeks though...
Comment: @forecaster Thanks for careful replies; our views seem pretty much identical once we have clarified and discussed them!
Comment: I will try to look at the residuals and post them as well. I agree with the comments @NickCox that significance testing isn't the highest priority given the nature of the data (and probably not regardless of the data), but I am interested in effect size. I don't care about a significant small effect in this data; the only thing that would make a difference is the evidence for/against a large effect. This discussion has been very helpful and I appreciate the time/energy/generosity.
Comment: Yes @NickCox it is true, in particular here one could imagine, for example, the presence of some "Christmas effect"... Note that it is also possible to consider a series of nested models: start with a model without seasonality; add first $\cos$ and $\sin$ of $2 \pi t \over 12$, then of $2 \times {2 \pi t \over 12}$, etc, allowing for increasingly complicated periodic shape.
Comment: @NickCox That's great, something I had no familiarity with. I read your paper which was also very helpful. Is there a way to characterize the _effect size_ of the periodicity? One can say _marginally_ significant at p = 0.0435, but how do you interpret the magnitude of the coefficient? Perhaps I should go to the Bliss reference?
Comment: A single sine and cosine curve has an amplitude which can be calculated and interpreted. If you were fitting something more complicated, you would need to think about what made sense.
Comment: @NickCox this is a nice tutorial, thanks for the reference. Are the birth data you use available anywhere?
Comment: @Elvis I copied the data from Bliss's text as referenced in my paper. I don't know a public location for a file. If you email me privately I can send you a copy.
Comment: @NickCox Very nice of you Nick, I'll e-mail you! Cheers.
Comment: @Elvis May be a naive comment, since this is a time series data therefore the errors will be auto correlated and you cannot use standard errors and p values in Glm as you will be violating assumptions of Glm and cannot use the p values to draw any conclusion on seasonality via significance testing.
Comment: Why would the error be auto-correlated?
Comment: @forecaster It's correct that sine and cosine terms might not capture all the structure in the data, so there may be correlation in the errors. But any implication that only pure time series methods are appropriate for time series would just rule out useful methods as a matter of prejudice. In many fields for example, checking for trend is based on simple regressions against time. People can do many useful analyses without worrying too much whether P-values are exactly right; it's the usual situation that assumptions are at best roughly satisfied.
Comment: @Elvis, since it is a time series data and dependent nature of the data, errors will be auto-correlated if you dont account for this structure. You could check for acutocorrelation by ploting residuals, ACF and PACF of residuals. See this [answer](http://stats.stackexchange.com/questions/32285/assumptions-of-generalised-linear-model) by gung on the assumptions of a GLM model in this site.
Comment: @NickCox, I agree completely, that in practice we don't look at satisfying all assumtion otherwise it would analysis by paralysis. I rarely look at significance testing p values on non experimental data. I was trying to add a caveat on this analysis since auto-correlations, dependence, normality of residuals are some of the important assumptions of a time series analysis AND significant testing is used in the above analysis.
Comment: @NickCox, Also I have used trignometry functions in a time series regression framework in my response below. Thanks for the nice article in the stat journal.
Comment: @svannoy we all appreciate a nice problem and this exchange of ideas!
Answer: A chi-square test is a good approach as a preliminary view to your question.
The stl decomposition can be misleading as a tool to test for the presence of seasonality. This procedure manages to return a stable seasonal pattern even if
a white noise (random signal with no structure) is passed as input. Try for example:
plot(stl(ts(rnorm(144), frequency=12), s.window="periodic"))

Looking at the orders chosen by an automatic ARIMA model selection procedure is also a bit risky since a seasonal ARIMA model does not always involve seasonality (for details see this discussion). In this case, the chosen model generates seasonal cycles and the comment by @RichardHardy is reasonable, however, a further insight is required in order to conclude that suicides are driven by a seasonal pattern.
Below, I summarize some results based on the analysis of the monthly series that you posted. This is the seasonal component estimated upon the basic structural time series model:
require(stsm)
m <- stsm.model(model = "llm+seas", y = x)
fit <- stsmFit(m, stsm.method = "maxlik.td.scoring")
plot(tsSmooth(fit)$states[,2], ylab = "")
mtext(text = "seasonal component", side = 3, adj = 0, font = 2)

A similar component was extracted using the software TRAMO-SEATS with default options. We can see that the estimated seasonal pattern is not stable across time and, hence, does not support the hypothesis of a recurrent pattern in the number of suicides across months during the sample period. Running the software X-13ARIMA-SEATS with default options, the combined test for seasonality
concluded that identifiable seasonality is not present.
Edit (see
this answer and my comment below for a definition of identifiable seasonality).
Given the nature of your data, it would be worth complementing this analysis based on time series methods with a model for count data (e.g. Poisson model) and test for the significance of seasonality in that model. Adding the tag count-data to your
question may result in more views and potential answers in this direction.
Comment: In addition to the monthly seasonality one could ask about the day-of-week seasonality. Actually I wouldn't be surprised if some days of the week are more or less prone to suicide. A $\chi2$ test should give you an answer in seconds.
Comment: Thanks @javiacalle, I'll be investigating the methods you suggest. Can I ask about your conclusion of the graph you posted, is it the fact that the amplitude increases as years progress that is the basis of your comment, "we can see that the estimated seasonal pattern is not stable across time", or does that include the more subtle observation that the shape of each peak is slightly different? I'm a assumming the former, but we know where assumptions lead us.
Comment: @svannoy The main conclusion based on the time series methods used in my answer is that there isn't a clear seasonal pattern in the sample data. Despite seasonal cycles explain part of the variability of the data,
a seasonal pattern cannot be identified reliably since it is obscured by a high degree of irregular fluctuations (this could also be checked displaying the gain function of the chosen ARIMA model shown in the question).
Comment: @oDDsKooL I also have done the chi-square test on day of the week, Saturday/Sunday are a bit below expectations and Monday/Tuesday are just above....
Answer: As noted in my comment, this is a very interesting problem. Detecting seasonality is not a statistical exercise alone. A reasonable approach would be to consult theory and experts such as:

Psychologist
Psychiatrist
Sociologist

on this problem to understand "why" there would be seasonality to supplement data analysis. Coming to the data, I used an excellent decomposition method called unobserved components model (UCM) which is a form of state space method. See also this very accessible article by Koopman. My approach is similar to @Javlacalle. It not only provides a tool to decompose time series data but also objectively assesses the presence or absence of seasonality via significance testing. I'm not a big fan of significance testing on
non-experimental data but I don't know of any other procedure that you would be able to test your hypothesis on presence/absence of seasonality on a time series data.
Many ignore but a very important feature that one would want to understand is the type of seasonality:

Stochastic - changes randomly and tough to predict
Deterministic - does not change, perfectly predictable. You could use dummy  or trigonometry (sin/cos etc.,) to model

For a lengthy time series data such as yours, it is possible that seasonality might have changed over time. Again UCM is the only approach that I know that can detect these stochastic/deterministic seasonality. UCM can decompose your problem into following "components":
Time Series Data = level + Slope + Seasonality + Cycle + Causal + Error(Noise).

You could also test if level, slope, cycle is deterministic or stochastic. Please note that level + slope = trend. Below I present some analysis on your data using UCM. I used SAS to do the analysis.

data input;
format date mmddyy10.;
date = intnx( 'month', '1jan1995'd, _n_-1 );
      input deaths@@;
datalines;
62    47  55  74  71  70  67  69  61  76  68  68
64    69  68  53  72  73  62  63  64  72  55  61
71    61  64  63  60  64  67  50  48  49  59  72
67    54  72  69  78  45  59  53  48  65  64  44
69    64  65  58  73  83  70  73  58  75  71  58
60    54  67  59  54  69  62  60  58  61  68  56
67    60  54  57  51  61  67  63  55  70  54  55
65    68  65  72  79  72  64  70  59  66  63  66
69    50  59  67  73  77  64  66  71  68  59  69
68    61  66  62  69  84  73  62  71  64  59  70
67    53  76  65  77  68  65  60  68  71  60  79
65    54  65  68  69  68  81  64  69  71  67  67
77    63  61  78  73  69  92  68  72  61  65  77
67    73  81  73  66  63  96  71  75  74  81  63
80    68  76  65  82  69  74  88  80  86  78  76
80    77  82  80  77  70  81  89  91  82  71  73
93    64  87  75  101 89  87  78  106 84  64  71
;
run;

ods graphics on;
 proc ucm data = input plots=all;
      id date interval = month;
      model deaths ;
      irregular ;
      level checkbreak;
      season length = 12 type=trig var = 0 noest; * Note I have used trigonometry to model seasonality;
   run;

   ods graphics off;

After several iterations considering different components and combinations, I ended with a parsimonious model of the following form:
There is a stochastic level + deterministic seasonality + some outliers and the data does not have any other detectable features.

Below is significance analysis of various components. Notice that I used trigonometry (that is sin/cos in the seasonality statement in PROC UCM) similar to @Elvis and @Nick Cox.  You could also use dummy coding in UCM and when I tested both gave similar results. See this documentation for differences between the two ways to model seasonality in SAS.

As shown above you have outliers: two pulses and one level shift in 2009 (Did economy/housing bubble play a role after 2009 ??) which could be explained by further deep dive analysis. A good feature of using Proc UCM is that it provides excellent graphical output.
Below is seasonality and a combined trend and seasonality plot. Whatever is left over is noise.

A more important diagnostic test if you want to use p values and significance testing is to check if your residuals are pattern-less and normally distributed which is satisfied in the above model using UCM and as shown below in the residual diagnostic plots like acf/pacf and others.

Conclusion: Based on data analysis using UCM and significance testing the data appears to have seasonality and we see high number of deaths in summer months of May/June/July and lowest in winter months of December and February.
Additional Considerations: Please also consider the practical significance of the magnitude of seasonal variation. To negate counterfactual arguments please consult domain experts to further complement and validate your hypothesis.
I'm by no means saying that this is the only approach to solve this problem. The feature that I like about UCM is that it allows you to explicitly model all the time series features and is highly visual as well.
Comment: +1. Many interesting and helpful comments. To your list of psychologist, psychiatrist, sociologist could be added meteorologist/climatologist. Such a person would want to add that no two years are identical in rainfall and temperature cycles. I would have guessed crudely at more depression in winter (shorter day lengths, etc.), but so much for a guess given some data.
Comment: Thanks for this answer and for interesting comments. I don't know UCM, it seems very interesting, I'll try to keep that in mind...
Comment: (+1) Interesting analysis. I would still be cautious about concluding the presence of a significant deterministic seasonal pattern but your results call for a closer look into this possibility. The Canova and Hansen test for seasonal stability could be helpful, it is described for example [here](http://jalobe.com/blog/testing-for-seasonal-stability-canova-and-hansen-test-statistic/).
Comment: Using the implementation available in the software `gretl` (default options in a model with seasonal dummies and a first order lag), the null of stability
is rejected at the 5% significance level for September and October. Using the seasonal trigonometric cycles, stability of the fundamental seasonal cycle of frequency $\pi/6$ is not rejected at the 5% level, which agrees with the conclusions by @Elvis.
Comment: Thanks @forecaster, this adds a lot to my learning. I am a psychologist, with a public health degree. I'd add epidemiologist to your list. As I mention in the beginning, there is a lot of mythology (aka theorizing) about seasonal trends and suicide. One can make strong arguments for seasonal trends, in any direction so we need quantitative analyses to (dis)confirm. From a public health perspective, if we found sharp discontinuities we could target interventions. I'm not seeing that in this data. From a theory-of-suicide perspective, confirming even small trends could inform theory development.
Answer: For initial visual estimation, following graph can be used. Plotting the monthly data with loess curve and its 95% confidence interval, it appears that there is a mid-year rise peaking at June. Other factors may be causing the data to have wide distribution, hence the seasonal trend may be getting masked in this raw data loess plot. The data points have been jittered.

Edit: Following plot shows loess curve and confidence interval for change in number of cases from the number in the previous month:

This also shows that during the months in first half of the year, the number of cases keep rising, while they are falling in the second half of the year. This also suggest a peak in mid-year. However, the confidence intervals are wide and goes across 0, i.e. no change, throughout the year, indicating a lack of statistical significance.
The difference of a month's number can be compared with average of previous 3 months' values:

This shows a clear increase in numbers in May and a fall in October.
Comment: (-1) There are already three high-quality answers to this question. Your answer also does **not** answer the posted question - you could post it as a *comment*. You do not provide answer how this data could be analyzed.
Comment: I had earlier posted comment here (see below the question), but I cannot post figure in comments.
Comment: Although I understand the editorial here, I will say that @rnso has provided a nice graph that illustrates the potential seasonal component nicely and should have been a part of my original post.
Comment: I understand that and agree, but still this is not an answer but rather a *comment* or improvement. @rnso could have suggested to you via comment that you could look on or include such plot.
Comment: @Glen_b , @ Tim :  I have added another plot that might be useful and that I cannot put in a comment.


The fibre functor on the category of unipotent flat vector bundles of a scheme

Question: Suppose we have a scheme $X$ over a field $L$ of characteristic $0$, and suppose that $S$ is an $L$-scheme. Then let $X_S:=X \times _L S$ denote the base change.
As in Le group fondamentale de la droite projective moins trois pointes (Deligne) we let $Un(X)$ be the category of unipotent vector bundles $\mathcal{V}$ on $X$ with flat connection $\nabla$, where by unipotent we mean that $X$ has a filtration (of finite length) by sub-bundles stabilised by the connection $\nabla$. The morphisms are morphisms of $O_X$-modules preserving the connection. Let $Vect_S$ be the category of vector bundles on $S$.
Given an $L$-points $b,x$ of $X$, there are $S$-points $b(S),x(S)$ of $X_S$. We fix $b$ as our base point and consider the following functor:
$$ e_b(S): Un(X_S) \rightarrow Vect_S;\;\; \mathcal{V} \mapsto b(S)^* \mathcal{V}$$
In particular, if $S=L$ then we are just taking the fibre of $\mathcal{V}$ at the point $b$.
I'm trying to understand how the above construction gives us a neutral Tannakian category by which we construct the de Rham fundamental group. So we require that $Un(X)$ be a rigid abelian tensor category with $e_b$ a fibre functor. The bit that's confusing me is the following: showing $e_b$ is a fibre functor.
I have looked at the paper referenced above, and it simply says that $e_b$ is a fibre functor. I have tried to show that $e_b$ is a fibre functor based on the definitions of everything presented. That is, I've tried to show that $e_b$ is an exact, $L$-linear and faithful tensor functor. My ideas we're as follows:

Tensor functor: this follows from the definition of $b^*$ and the definition of tensor product of sheaves of modules
Exact: We want to show that if we have an exact sequence $$ 0 \rightarrow \mathcal{U} \rightarrow \mathcal{V} \rightarrow \mathcal{W} \rightarrow 0$$ then we have an exact sequence $$ 0 \rightarrow b^*\mathcal{U} \rightarrow b^*\mathcal{V} \rightarrow b^*\mathcal{W} \rightarrow 0$$ We know that $b^*$ is right exact, so we just need to check that it is also left exact for these vector bundles. Now if we are working over $S=L$, then this is very easy by checking exactness on the stalks since $O_L(L)=L$. If $S \neq L$ I'm a bit more confused - $S$ will be covered by the spectra of some $L$-algebras $R$. At the level of stalks , if we pick a point $s$ we'll have something like $$ 0 \rightarrow \mathcal{U}_{b(S)(s)} \otimes_{O_{X_S,b(S)(s)}} O_{S,s} \rightarrow b^*\mathcal{V}_{b(S)(s)} \otimes_{O_{X_S,b(S)(s)}} O_{S,s} \rightarrow b^*\mathcal{W}_{b(S)(s)} \otimes_{O_{X_S,b(S)(s)}} O_{S,s} \rightarrow 0$$ So then my thinking is that since any $L$-algebra is a flat, we find that $O_{S,s}$ is flat and hence the sequence is exact at the level of stalks and hence exact. Is this correct?
Faithful: here's where I'm really confused about things. We want to show that the morphism $$ Hom_{Un(X_S)}(\mathcal{V}, \mathcal{W}) \rightarrow Hom_{Vect_S}(b(S)^*\mathcal{V}, b(S)^*\mathcal{W})$$ is an injection. Now, if we let $S=L$, then already this is confusing to me. Suppose that the $L$-point $b$ corresponds to a point $P \in X$. Then to my mind, the above is saying that if $f,g: \mathcal{V} \rightarrow \mathcal{W}$ are such that $f_P=g_P$ then $f=g$. Now, obviously this must have something to do with the connections on the bundles $\mathcal{V}, \mathcal{W}$ but I'm not sure how to go forward here.

Any help would be greatly appreciated!
Answer: The exactness of $e_b$ follows from the fact that a short exact sequence of vector bundles is locally split, so pull-back of short exact sequences of vector bundles is exact.  Another way to think about it is that $\mathcal W$ is flat over $X_S$, and pull-back is a tensor product, so the Tor that could cause left exactness to fail actually vanishes.
The faithfulness uses the connection: certainly a map of vector bundles (with no extra structure) is not characterized by its value on a fibre.  For example, suppose that a morphism of bundles with connection, that is compatible with the connection, vanishes on the fibre at $b$.  Then uniqueness of solutions of first order linear ODE's with fixed initial conditions shows that this morphism has to be identically zero.
Comment: @Aaron: Yes, uniqueness of formal solutions, together with the fact that sections of a vector bundle over an irreducible variety embed into the formal completion at any chosen point, so that it's enough to check formal vanishing to deduce actual vanishing.
Comment: So, the first part makes sense to me but I need to work through the details to be sure.
Comment: As for the second part, do we mean uniqueness of formal solutions here, since we have algebraic connections?


Extracting a name from a String

Question: I'm quite new to NSString manipulation and don't have much experience at all of manipulating strings in any language really.
My problem is that I have a string that contains a lot of data, within this data is a name that I need to extract into a new NSString. EG:
NSString* dataString =@"randomdata12359123888585/name_john_randomdatawadapoawdk"

"/name_" always precede the data I need and "_" always follows it.
I have looked into things such as NSScanner but I'm not quite sure what the correct approach is or how to implement NSScanner.
Comment: So u used NSScanner. where is the code of that approach?
Comment: So basically you just want to throw the whole thing for help without saying where you have difficulty?  There are so many topics about separating a string into smaller ones.  Have you run a search?
Comment: So, try something.  The task is easily accomplished simply using NSString methods -- you don't need to use NSScanner.
Comment: So the two words seperated by underscore after name is what you want to extract ?
Comment: It will helps you: http://stackoverflow.com/questions/594797/how-to-use-nsscanner
Comment: Or even regular expressions.
Answer: Your string format is very well-defined (as you say, the name you are after is always preceded by "/name_" and always followed by "_"), and I suppose that the name ("john") hence cannot contain an underscore.
I'd therefore consider a simple regular expression, which is perfectly suited for this sort of problem:
NSString *regexPattern = @"^.*/name_(.*?)_.*$";

NSString *name = [dataString stringByReplacingOccurrencesOfString: regexPattern
                                                       withString: @"$1"
                                                          options: NSRegularExpressionSearch
                                                            range: NSMakeRange(0, dataString.length)];

In case you are not familiar with regular expressions, what is going on here is:

Begin at the beginning of the string (the "^")
Allow anything (".*") followed by "/name_"
Capture what follows (the parenthesis means "capture this")
In the parenthesis, allow anything (".*"), but make it as short as possible (the "?" after the "*")
It must be followed by an underscore and then allow anything that happens to be there up to the end of the string (the "$")

This will match the whole string, and when substituting the match (i.e., all of the string) with "$1", it will substitute the match with the substring included in the first (and only) parenthesis.
Result: It will produce a string that contains only the name. If the string does not have the correct format (i.e., no name between two underscores), then it will not change anything and return the full, original string.
It is a matter of coding style whether you prefer one approach over the other, but if you like regular expressions, then this approach is both clean, easy to understand and simple to maintain.
As I see it, any fragility in this is due to the data format, which looks suspiciously like something that depends on other "random" pieces of data, so whichever method you choose to parse that string, make sure you add some defensive tests to check the data format and alert you if unexpected strings begin to enter your data. This could be years from now, when you have forgotten everything about underscores, regexes and NSScanner.
Answer: I managed to do this with NSScanner, however the array answer would work too so I've upvoted it.
The NSScanner code I used for anyone else facing a similar problem is:
-(void)formatName{
NSString *stringToSearch = _URLString; //url string is the long string we wish to search.

NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:@"name_" intoString:nil]; // Scan all characters before name_
while(![scanner isAtEnd]) {
    NSString *substring = nil;
    [scanner scanString:@"name_" intoString:nil]; // Scan the # character
    if([scanner scanUpToString:@"_" intoString:&substring]) {
        // If the space immediately followed the _, this will be skipped

        _nameIwant = substring; //nameIwant is a property to store the name I scanned for
        return;
    }

}

}
Answer:
-(void)separateString{
NSString* dataString =@"randomdata12359123888585/name_john_randomdatawadapoawdk";
NSArray *arr1 = [dataString componentsSeparatedByString:@"/"];
NSArray *arr2 = [[arr1 objectAtIndex:1] componentsSeparatedByString:@"_"];
NSLog(@"%@ %@",arr1,arr2);
}

The output you get is

arr1=  (
randomdata12359123888585,
"name_john_randomdatawadapoawdk"
)
arr2 = (
name,
john,
randomdatawadapoawdk
)

now you can access the name or whatever from the array index.

Extracting a name from a String


rails react browserify TypeError: Object function has no method 'extend'

Question: I'm trying to make a web app using rails, react, and browserify. I've been following this tutorial, and since I want server-side rendering, I've used this repo as a starting point, and followed the tutorial mentioned in the README file.
Although I think I've done things as the mentioned articles suggest, I cant figure out how to solve the following error:

TypeError: Object function ( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            } has no method 'extend'

If you want to reproduce the error, clone my repo, which is opensource and its on github, and go to the feature branch auth, instal the gems and npm packages and lift the server:

$ cd path_to_project
$ git checkout -b feature/auth
$ bundle
$ npm install
$ bundle exec rails server

I would really appreciate any help, since i'm currently stuck here. Also, I'm new to react, so I don't know pretty much where to look for the problem.
EDIT: By request in the comments, I've removed the stacktrace in order to make the question more readable. If you need any extra information, please let me know.
Comment: Can you edit your post, please? It is not easy to legible.
Comment: @MateuszCzerwiński : done, could you figure something out?
Comment: @Throoze Unrelated but if you have a moment, would you mind trying browserify-rails 2.0.2 and see if it works well for you? There were some performance improvements but I'd like to confirm it is working correctly for everyone.
Answer: I happened to be using the j-toker CommonJS package which internally uses jQuery's ajax API. jQuery is incompatible with server side rendering since it needs a document element to load itself, and it only exists in the browser, not in the server. The solution is not yet at hand, but as J-Toker's author has indicated, he's about to release a new library that covers the case of server side rendering.
So, to anyone encountering a similar error, check if you are using jquery or any other package that in turns depends on jquery, or requires having a document DOM element, and try using a server-side-rendering-safe alternative.


Root Certificate for all computers in a LAN for Azure's Point to Site VPN connection

Question: In case of Point to Site VPN connection between one to one i.e. Windows Server on Azure and one Windows 10 laptop at premises, it's okay to create a root certificate of one computer but in case of more than one computer in a LAN in the premise, do I need to create the root certificate of all computers of the LAN and do I need to configure P2S for all computers at Virtual Gateway Network separately?
I don't think so. Pls clarify.
Comment: Are you using a VPN appliance at both sites to route traffic between sites? If so, then you don't need to touch root CAs on _any_ computer.
Comment: No, I am not using any application. I read some references for P2S VPN connection. In all references, Root certificate of one computer has been created. I just shared a scenario. Pls resolve the scenario.
Answer: You understanding is right. You just create a root certificate and a client certificate. The root certificate should be upload to Azure. The client certificate can be shared with you pcs. For more details, please refer to https://learn.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-point-to-site-rm-ps
Comment: The link https://learn.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-point-to-site-rm-ps says, root certificate generated with an enterprise solution (recommended) or generate a self-signed certificate. What about root certificate using an enterprise solution?
Comment: The link https://learn.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-point-to-site-rm-ps says, each client computer that you connect to a VNet with a Point-to-Site connection must have a client certificate installed. You generate it from the root certificate and install it on each client computer.  You can either generate a unique certificate for each client, or you can use the same certificate for multiple clients. It is confusing. Please clarify it.
Comment: As per the link, "each client computer that you connect to a VNet with a Point-to-Site connection must have a client certificate installed." If a client certificate is generated from a client computer A, does it mean, the client certificate generated from the client computer A is to be installed in the same client computer A?
Comment: As per the link, "You generate it from the root certificate and install it on each client computer." If more than one client computers to be connected from the Azure VM using P2S connection, does it mean a client certificate generated from one client computer is to be installed in all client computers?
Comment: @user741975 Your understanding is right . All clients use the same certificate.
Comment: Pls let me know, what about root certificate using an enterprise solution?
Comment: As per my understanding, if Windows Server Domain Controller is setup at Azure and there are some computers in a LAN at site. And if all computers need to join Windows Server Domain Controller, it comes under P2S connection. Am I right?
Comment: If I am right, in such case, do I need to create root certificate in all computers individually and need to update all certificates on Virtual Gateway Network?
Comment: If you use same client certificate, you just need a root certificate. The root certificate is used to ensure if your computer has installed the right client certificate

Root Certificate for all computers in a LAN for Azure’s Point to Site VPN connection


Given a differentiable function $f$, prove that $\lim_{h\to 0}\frac{f\left(x + \frac{h}{2}\right)-f\left(x - \frac{h}{2}\right)}{h} = f'(x)$.

Question: I'm trying to prove the following statement

Given a differentiable function $f:\mathbb{R}\to \mathbb{R}$, prove that $$\lim_{h \to 0} \frac{f\left(x + \frac{h}{2}\right)-f\left(x - \frac{h}{2}\right) }{h} = f'(x)$$

I know $2$ definitions for the derivative of a function $f$:
$$
\lim_{h \to 0} \frac{f\left(x +h\right)-f\left(x\right) }{h} \qquad \text{and} \qquad \lim_{a \to x} \frac{f\left(x \right)-f\left(a\right) }{x-a}
$$
so my idea was to try to arrange the limit in question into one of these $2$ forms.

I proceeded to take $x^* = x - \frac{h}{2} $ to do a change of variable, in which case my limit would end up looking like
$$\lim_{h \to 0} \frac{f\left(x^* +h\right)-f\left(x^*\right) }{h} = f'(x^*) $$
which would seem to imply that this is equal to $f'\left(x - \frac{h}{2}\right)\neq f'(x)$ using the first definition of the derivative. I know that since $h \to 0$, then $f'\left(x - \frac{h}{2}\right)$ and $f'(x)$ are the same thing, but since the paramater $h$ is included in the substitution I'm making I don't know how to account for this after I took the limit.
I think my problem is just a basic concept misconception, but I can't seem to find a way to rigorously justify the steps I need to take to transform the limit into one of the definitions that I know. Could anyone tell me what I'm doing wrong or how I could correctly structure this argument to make it rigorous? Thank you!
Comment: $\lim_{h \to 0} f'(x-\frac h2) = f'(x)$ only if $f'$ is continuous at $x.$
Answer: $$\lim_{h \to 0} \frac{f\left(x + \dfrac{h}{2}\right)-f\left(x - \dfrac{h}{2}\right) }{h}=\lim_{h \to 0} \dfrac{f\left(x + \dfrac{h}{2}\right)-f(x)+f(x)-f\left(x - \dfrac{h}{2}\right) }{h}
\\=\lim_{h \to 0} \dfrac{f\left(x + \dfrac{h}{2}\right)-f(x)}{2\dfrac h2}
+\lim_{h \to 0} \dfrac{f\left(x - \dfrac{h}{2}\right)-f(x) }{-2\dfrac h2}=2\frac{f'(x)}2.$$
Note that the reciprocal is not true, because $f(x)$ does not appear in the symmetric formula. So the equivalence is one-way.
Comment: @RobertLee: not at all. It needs to be continuous at $x$.
Comment: For a classic example, the limit exists for $f(x) = |x|$ at $x = 0$, but clearly $f'(0)$ does not exist.
Comment: Thank you so much for your answer! I have a question about the last remark. To make the reciprocal true, would it then suffice to ask that $f(x)$ be _defined_ for all $x \in \mathbb{R}$?
Comment: Does the hypothesis that $f$ is differentiable on $\mathbb{R}$ not imply that it's also continous over the reals?
Comment: @RobertLee: yes it does.
Answer: \begin{align}
& \frac{f\left(x + \frac{h}{2}\right)-f\left(x - \frac{h}{2}\right) }{h} \\[12pt]
= {} & \frac 1 2\left( \frac{f\left(x + \frac{h}{2}\right) - f(x)}{h/2} + \frac{f(x) -f\left(x - \frac{h}{2}\right)}{h/2} \right) \\[8pt]
\to {} & \frac 1 2\Big( f'(x) + f'(x)\Big) \quad \text{as } h\to0.
\end{align}


How to append values to hidden field?

Question: I have a one field which is hidden and that gets added dynamically to track the another select box's selected items.
for e.g:
    hidden_field_name= count_select;

    select_box_name = select1;

both gets added dynamically when user click "add" button. Now I want to store the select1's selected item count in count_select for every instance.
But when I use the val() method it write the total click's in count_select value.
Here is code:
Html code :

function getCount() {
  top.count = $("select.container_countable option:selected[value!='']").length;
  $('.countable').val(top.count);
}

<input type='hidden' class='countable' id='count_containerfilter' name='countable_cont' value=0>
<select onclick='getCount()' class='container_countable' multiple='multiple' name='new_containerfilter'>

Any idea why is this happening?
Comment: Please provide your code.
Comment: It would be better if you post your markup as well as js codes.
Comment: Can you plz show some of your code?
Comment: There is no JavaScript function `val()`, I guess you are using jQuery.
Comment: @NabilKadimi Yes right I am using Jquery !!! And Sorry I have no experience with this.
Comment: what I want to achieve is : select_box = 2 item selected ,newly added select box = 3 item selected , so finally count_select should contain count_select = [2, 3] instead of that it contains [5, 5]
Comment: your SELECT box HTML ?
Answer: Based on your this comment above:

what I want to achieve is : select_box = 2 item selected ,newly added
  select box = 3 item selected , so finally count_select should contain
  count_select = [2, 3]....

You could use an array to track the selections. Once done, either assign that array directly to the hidden input or stringify it and assign the string.
See this snippet:

var tmp = [];
$("select.countable").on("change", function() {
    tmp = [];
    $("select.countable").each(function() {
        var ctr = $(this).find("option:selected").length;
        tmp.push(ctr);
    });
    $("#ctr").val(JSON.stringify(tmp));
    $("#result").text($("#ctr").val());
});

<input type='hidden' id='ctr' />

<select class="countable" multiple>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>
<select class="countable" multiple>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

Here is a fiddle for you to play with: http://jsfiddle.net/abhitalks/f6o3ped8/1/
Try adding more selects and see the result.
.
Comment: This is what I wanted. But I tried to embed this code in my code and it is not working. As I am adding the table content through the script code. but it is not listening to the on change event.
Comment: In that case use event delegation. i.e. bind an event on parent and check `target`. e.g. `$(parent).on("change", ".countable", func...`. Something like this: http://jsfiddle.net/abhitalks/n1238LLo/1/
Comment: @Sagar: BTW, it would make your life easier if you do not `stringify` the array. Just assign it as is. This way on the server-side you will get a comma-separated string which you can split easily.
Answer: This code is from jQuery docs for :selected (with slight modification):

$("select")
  .change(function() {
    var count = $("select option:selected").length; // Count selected
    $("input").val(count);                          // Update field
  })
  .trigger("change");                               // Trigger at least once
select{
  height:100px;
  width:100px;
}

<select name="garden" multiple="multiple">
  <option>Flowers</option>
  <option>Shrubs</option>
  <option>Trees</option>
  <option selected="selected">Bushes</option>
  <option>Grass</option>
  <option selected="selected">Dirt</option>
</select>
<input />
Comment: I don't think so this will work out for me. This is the same situation in which I am right now . When I submit the form querydict contains the input as a dict key and values will be [first+second selected items, first+second selected items]

How to append values to hidden field?


Parsing a URL to find a varying length string

Question: I have a string in multiple URLs starting with two characters followed by between 1-6 numbers e.g. 'SO123456' This string is rarely in the same position within the URL. Following the string is either .html or whitespace.
SELECT SUBSTRING(URL,PATINDEX('%SO[0-9]%',URL),8)

FROM Table

WHERE URL LIKE '%SO[0-9]%'

This code returns 'SO12.htm' if the string is shorter than 8 characters.
Not all of the URLs have this string, and if that's the case then I still need the query to produce 'Null'.
I'm trying to return the exact length of the string. Can anyone help me with a way to solve this please? Can you find the length of a wildcard string to use within the substring so that only the exact string length is returned?
Many Thanks.
Comment: Possible duplicate of: http://stackoverflow.com/questions/9772566/using-patindex-to-find-varying-length-patterns-in-t-sql
Comment: Not sure how to relate this to my problem
Comment: [This answer](http://stackoverflow.com/a/9778647/1015327) shows how to extract a substring matching a pattern from a string. The same should work for you. Then take the length of that string.
Comment: This works for the URLs where my string is the first numeric character. Do you have any idea how to apply this to exactly the string I need? Thanks
Comment: Of course, you must use *your own* pattern, but apart from that it should work for you.
Answer: I think you should check the length of the column first dude.
Here's the code
SELECT CASE LEN(URL) -- Check the length of URL column
WHEN > 8 THEN SUBSTRING(URL,PATINDEX('%SO[0-9]%',URL),8)
ELSE -- do your stuff
END as 'example'
FROM Table

Comment: Every URL is greater than 8 characters, the 8 is the maximum number of characters the string I'm interested can be.
Answer: Not quite elaborated, but as a hint to get you started:
patindex = PATINDEX('%SO[0-9]%',URL) -> Index of the start of the pattern
charindex = CHARINDEX('.html', URL, patindex ) -> Index of the first '.html' after the start of the pattern.
patternLen = charindex - patindex

So something like the following may work:
SELECT
  CHARINDEX('.html', URL,
    PATINDEX('%SO[0-9]%',URL)
  ) -
  PATINDEX('%SO[0-9]%',URL)
FROM ...

Not all of the URLs have this string, and if that's the case then I
  still need the query to produce 'Null'.

-> Outer (self) join:
SELECT
  allUrls.URL,
  CHARINDEX('.html', u.URL, PATINDEX('%SO[0-9]%',u.URL) ) - PATINDEX('%SO[0-9]%', u.URL) -- Same as above
FROM MyTable allUrls
LEFT OUTER JOIN MyTable u
  ON allUrls.URL = u.URL
  AND u.URL LIKE '%SO[0-9]%'

Answer: Try this:
Select case when patindex('%SO[0-9]&',URL) = 0 then null else substring(URL, patindex('%SO[0-9]&',URL),8)
From Table


Como forçar o download de um arquivo, que esta armazenado no banco de dados

Question: Tenho um sistema onde, são listados documentos do banco de dados, onde o usuário tem a opção de visualizar ou baixar o arquivo. Quero saber como faço para resgatar este arquivo do banco e forçar o download dele. Este arquivo está em .pdf
Este é o codigo que eu tenho
header("Content-type: application/pdf");

//pega o arquivo
$sql_select_file = "SELECT * FROM malote_arq_2014 WHERE reg=" . $reg . "";
$query_select_file = mysqli_query($conn, $sql_select_file);
$result = mysqli_fetch_array($query_select_file);

header("Content-Disposition: attachment; filename=".$arquivo);

Só que ele me retorna a seguinte mensagem:
Header may not contain more than a single header, new line detected in
Comment: @Mathdesigner47 já que você conseguiu resolver e era um erro bem específico, eu sugeriria deletar a pergunta neste caso.
Comment: Já viu esse artigo? http://blog.thiagobelem.net/forcando-o-download-de-arquivos-com-php/
Comment: Sim, e já testei aquele script, mas ele continua me retornando mesma mensagem que citei acima
Comment: @Bacco, eu realmente estava confundindo o nome do arquivo com o conteúdo. No 'header' eu estava passando o conteúdo do arquivo, experimentei colocar um nome qualquer, e funcionou. Problema resolvido!
Comment: @Mathdesigner47 ótimo. Ainda acho que seria o caso de deletar a pergunta, mas veja o que acha melhor! O importante é que resolveu.
Answer: Provavelmente $arquivo está vindo com caracteres especiais ao final.
Experimente usando a função trim para limpar estes caracteres:
header("Content-Disposition: attachment; filename=".trim( $arquivo) );

Esta solução é melhor como meio apenas de identificar o problema, pois o ideal seria o nome do arquivo já ser originariamente capturado sem nenhum caractere desnecessário.
Experimente também comentar estas linhas:
// header("Content-type: application/pdf");
...
// header("Content-Disposition: attachment; filename=".$arquivo);

e colocar no final um print_r( $arquivo ); para identificar outros enganos.

Certifique-se também de não estar colocando o conteúdo do arquivo no lugar do nome do arquivo.
Comment: consegui, foi exatamente isso o que você disse, estava passando para o header o conteudo do arquivo. Experimentei colocar o nome, e funcionou
Comment: continua dando a mesma mensagem de erro
Comment: será que pelo fato de eu omitir o tamanho do arquivo, seja o motivo deste erro?
Comment: @Mathdesigner47 experimente a sugestao que eu pus para vermos o que se encontra em $arquivo. Desconfio que tenha algo errado lá. Se não for isso, pode ter problemas em outra parte do código. Seria bom você por o código completo, ou ao menos a parte que cria a variável `$arquivo`.
Comment: Utilizei o sua sugestão, ele me mostra uma porção de caracteres, que são ilegíveis. E creio que não seja erro no código, pois utilizo este mesmo código para exibir o arquivo, no browser


Removing C6054 error with scanf functions

Question: I am using Code Analysis (aka FxCop) on VS2012 and I have a few functions of the form
void ReadTable(FILE *fd)
{
    char label[32];
    /* ... */
    fscanf(fd, "%s", label);
    /* ... */
    if (strcmp(label, "TEST") == 0)
    {
        /* ... */
    }
}

These always throw warning C6054: String 'label' might not be zero-terminated. I understand why this happens, since they can't use SAL annotations to indicate the output from fscanf will be null-terminated, but the fact remains.
Is there a way to get rid of this warning (without disabling the relevant Code Analysis check wholesale)? Or is it something I just have to live with when using scanf?
Comment: @user3121023 I'm compiling now with that test (it takes a while), but even if that works, it isn't a really extensible solution, especially if there's a case where `label` is dynamically allocated.
Answer: If scanf fails the buffer remains uninitialized. User may enter more than 32 characters writing out-of-bounds. In either case the buffer will not be null terminated.
First initialize the buffer correctly:
char label[32] = { 0 };

then make sure you read at most 31 characters and check the return value of the call:
const int read = fscanf( fd , "%31s" , label );
if( read <= 0 )
{
    //didn't read anything, check feof and ferror
}


Listener for new file created in workspace in vscode extension api

Question: I was looking through the vscode api, and I was wondering if there exists a type of listener event that sees that a file was created in the current workspace folder.
Thank you!
Answer: You can use a FileSystemWatcher for this, for instance if you wanted to know about the creation of .txt files in the current workspace:
let folders = vscode.workspace.workspaceFolders;
if (folders) {
    let watcher = vscode.workspace.createFileSystemWatcher(
        new vscode.RelativePattern(folders[0], "*.txt"));
    watcher.onDidCreate(uri => console.log(`created ${uri}`));
}


How to find a CDF of a composite random variable

Question: I am given a composite random variable $X$, "composite" meaning that $X$ is the random variable that has both discrete and continuous components, with the probability distributions:
$$\begin{cases}P(a<X<b) = \frac{b-a}{2} & \text{if $0<a<b<1$ } \\ P(X=i) = \left(\frac{1}{2}\right)^{i+1} & \text{if $i=1,2,\dotsc$} & \end{cases}$$
How can one write CDF of $X$?

EDIT 1.
Given the hints in the comment section I have found $F_1(x)$ and $F_2(x)$ as below:
$F_1(x) = \begin{cases} 0 & \text{if $x<0$} \\ x & \text{if $0<x<1$} \\1 & \text{if $x>1$}\end{cases}$
$F_2(x) = 1 - \left(\frac{1}{2}\right)^i \;\; \text{for $i=1,2,\dotsc$}$
Hence, the cdf will be given by $F_X(x) = \frac{1}{2} F_1(x) + \frac{1}{2} F_2(x)$.
The reason why I wanted to obtain the cdf in the first place was to then generate random variables using inverse method. Would the following algorithm work?
Following @Henry's answer about the coin tossing:

generate uniform random variable $U_1 \sim U(0,1)$
if $U_1<\frac{1}{2}$ then output $X=U_1$
if $U_1\geq \frac{1}{2}$ then output $X=F_2^{-1}(U)$

Not sure about the last step though. Can I even inverse it when its discrete?
Comment: @gt6989b The first gives $\mathbb P(0<X<1)=\frac12$ and the second gives $\mathbb P(X \in \{1,2,3,\ldots\})=\frac12$, which add up to $1$
Comment: not sure this would add up to $1$ though?
Answer: Hints:
Consider the two independent random variables $X_1$ and $X_2$, and find the cumulative distribution functions $F_1(x)=\mathbb P(X_1 \le x)$ and $F_2(x)=\mathbb P(X_2 \le x)$ when
$$\begin{cases}\mathbb P(a<X_1<b) = b-a & \text{if $0<a<b<1$ } \\ \mathbb  P(X_2=i) = \left(\frac{1}{2}\right)^{i} & \text{if $i=1,2,\dotsc$} & \end{cases}$$
i.e. double the probabilities in the original question.
Then independently toss a fair coin to decide whether $X=X_1$ or $X=X_2$, so mutually exclusively each with probability $\frac12$.  You can then say, using the law of total probability,  $$F(x)=\mathbb P(X \le x) = \frac12 \mathbb P(X_1 \le x)+ \frac12\mathbb P(X_2 \le x)= \frac12 F_1(x) + \frac12 F_2(x)$$
Comment: @bajun65537: $X_1$ has a uniform distribution on $(0,1)$ while $X_2$ has a geometric distribution
Comment: I still have a bit of a problem. I follow your logic for the first part as well as for the final part. However, I still find the $F_1(x)$ quite difficult. In previous examples I had a pdf function given quite explicitly - and all I had to do was integrate. Here I'm not sure what to do with the probabilities $\mathbb P(a<X_1<b)$ and $\mathbb  P(X_2=i)$. Could you help me with that as well?


Tomcat on virtual server: JVM cannot start because 44 GB Ram is not enough ?

Question: I'm renting a virtual machine, running Ubuntu 9.04. I installed the SUN JDK 6.0 (via apt-get) and Tomcat 6.0.18 (via unzipping).
General problem with Java (partly solved)
At first, it was impossible to run a JVM because of memory problems. Even something simple as java -version failed with
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

I figured out that even though free reported 44 GB of free memory, I was only allowed to use a small fraction of it, something like 284 MB per allocation. Running java -Xms10m -Xmx256m -version works fine, but I don't want to change every script that invokes java.
Also I read about the JAVA_OPTS environment variable, which is honored by many apps. I've set this to "-Xms10m -Xmx256m"
Problem with Tomcat
The tomcat startup script catalina.sh also uses JAVA_OPTS. But event though, I still get the three error lines mentioned above, readable in logs/catalina.out. I know that JAVA_OPTS is used, because when I put nonsense into that variable, I see the consequences in logs/catalina.out.
It seems like Tomcat also wants to start javac, which needs the options prefixed with -J like -J-Xms10m -J-Xmx256m instead. But I'm not sure if this is related to the problem, because there is no more output than those three lines.
I'm starting Tomcat via bin/startup.sh which in turn calls bin/catalina.sh. I know there is also the possibilty to start it via jsrv, but I cannot do this, because the make / configure process for jsrv also wants to call javac which fails with the well known three line error message mentioned above.
Now I'd be interested in two possible kinds of solution:

how can I make Java just work on my virtual host, no matter who calls java or javac and no matter how he calls it?
if this is impossible, how can I adjust Tomcat to just run?

PS: Please note that I only have control over the virtual machine, but no control and only limited knowledge over/about the surrounding physical machine.
PPS: Sorry for the noobish title of this question, but I felt that the original, well written title did not attract enough readers, so I thought this might help ;) It actually helped, as I got 0 views in the first hour, but 8 views in the hour after the change. Strange world.
Edit: this is the output of ulimit -a:
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 20
file size               (blocks, -f) unlimited
pending signals                 (-i) 16382
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) unlimited
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Comment: Is this Ubuntu 32-bit with a PAE enabled kernel, or is this an Ubuntu 64-bit? If it is an Ubuntu 64-bit, then is it the Sun 64-bit JVM, or is it the Sun 32-bit JVM?
Comment: whoops.. I just noticed that this question dates from 19/12/2009. Got to it because there's no indicated answer for it.
Answer: javac generally spawns a separate process which should fall underneath different process rules.
-J options are for passing args via a wrapper/launcher to the JVM, I've not seen this on Tomcat.
Find out where the -Xmx is coming from:
find /your/install/dir/with/tomcat |xargs grep '-Xmx'
Comment: Hi Xepoch, I think you misunderstood me or my problem: There is no -Xmx *too much* that I want to find. It seems as if -Xmx is needed to run a JVM, and when starting Tomcat, also I could somehow inject a -Xmx, it still seems to be one -Xmx *to few*, because I still get this error. So I need to find a way to tell the JVM -Xmx on Tomcat startup.
Comment: Ohh, you were right. Originally I searched for a way to put my own -Xmx into the java arguments. Now I succeeded, but since Tomcat is appending its own -Xmx, mine is ignored. I tried your search (which looks exactly like I would have constructed it), bit it found nothing. I will keep on trying.
Answer: Try running ulimit -v unlimited before starting tomcat.  If this works, you can probably add this to one or both of the startup scripts, or in /etc/profile, ~/.bashrc or some other shell profile script.
Comment: No, this doesn't work neither. ulimit -v unlimited finishes without output (which is probably intented), but also without effect. A simple call to java still fails, and so does the startup of Tomcat. Thanks anyway.
Comment: Just out of curiosity, what is the output of `ulimit -a`?
Obviously I'm committed to it being a ulimit issue ;)
Comment: I edited the output of ulimit -a into the question, since I dont think I can insert it into a comment without becoming unreadable.
Comment: Oops. I lost connection to the server and thus used the ulimit -a on ly local machine. Now I ran it on the actual server and re-edited the question to show the right output.
Answer: In lack of alternatives I tried a dirty hack: replacing java and javac by shell scripts which ensure that the proper arguments are passed and allow me to see the exact parameter list. Since this in already an attempt at a very specific solution, and not part of the question, I feld like putting it into an answer.
I searched for all occurences of java in my filesystem. There were way to many, because I has several JREs and JDKs on my machine. Even after removing all but one version, there were still many of them. I used find / -name "java" |xargs file to find out which is the real one. It told me:
/var/lib/dpkg/alternatives/java:               ASCII text
/etc/alternatives/java:                        symbolic link to `/usr/lib/jvm/java-6-sun/jre/bin/java'
/usr/share/java:                               directory
/usr/lib/jvm/java-6-sun-220.127.116.11/bin/java:     symbolic link to `../jre/bin/java'
/usr/lib/jvm/java-6-sun-188.8.131.52/jre/bin/java: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
/usr/bin/java:                                 symbolic link to `/etc/alternatives/java'

So I knew that /usr/lib/jvm/java-6-sun-188.8.131.52/jre/bin/java was the executable. I renamed it to javaexec and placed a shell script at it's old location:
mv /usr/lib/jvm/java-6-sun-188.8.131.52/jre/bin/java /usr/lib/jvm/java-6-sun-126.96.36.199/jre/bin/javaexec
nano /usr/lib/jvm/java-6-sun-18.104.22.168/jre/bin/java
   (see below for file contents)
chmod +x #!/bin/bash -e

This ensures that every call to java in the end points to my script, which will call the executable with the right parameters. After that, I did similar terrible things to javac. The contents of my script:
#!/bin/bash -e
line=""
for i in $*
do
  if [[ "$i" == *Xmx* ]]; then
    echo "Seen -Xmx and removed"
  elif [[ "$i" == *MaxPerm* ]]; then
    echo "Seen -XX:MaxPermSize and removed"
  else
    line="$line $i"
  fi
done
exec="/usr/lib/jvm/java-6-sun-184.108.40.206/jre/bin/javaexec -Xms10m -Xmx100m $line"
echo Now executing $exec
$exec

It removes each and every parameter from the command line that involves -Xmx or something like -XX:MaxPermSize and puts in its own -Xms and -Xmx limits.
When I now start Tomcat, it still fails, but finally, the JVM starts up, does something, and then exits with a meaningful message. No reel success, but it leaves me a lot more satisfied, since from there on, I know what to do. While Tomcat still doesn't run, it has a nice side effect:
Now I can finally call java or javac on the command line or from a script, and they do not crash, which before was not possible at all! They just run! Hey, I feel like the king of the word, I finally got java to run on a machine with 44GB of Ram without complaing about insufficient memory. This is a great day in the history of computing, indeed!
Comment: Something else is amiss.  44GiB RAM I assume in 64 bits?  There are big reasons to be employing the `-XX:MaxPermSize` &c, you won't want to ignore these.
Answer: You could also check the java vms that you have installed. Make sure, it's not the gcj environment that's giving you problems.
try
update-java-alternatives -l

to see if sun-java6 is your default. Drop "-l" to see the other options for this command - e.g. how to change the default.
If I remember correctly, all java-problems I had on ubuntu had their root in gcj being the default (it might have come in as some dependency prior to sun-java6). If I don't remember correctly, it's at least the majority of the problems.
Last but not least (and only related to your question): You can put a file named "setenv.sh" into tomcat's bin directory. This file is not there, but will be read on startup if it can be found. You can make all of your changes here in order to refer to them later. The only minor drawback is, that they'll be read on startup as well as on shutdown.
Answer: Once I had similar problem.
You can try start java with

vm.overcommit_memory=1

set in /etc/sysctl.conf.
Or simply echo "1" > /proc/sys/vm/overcommit_memory
Or play with overcommit_memory, overcommit_ratio
http://www.redhat.com/magazine/001nov04/features/vm/


Como fazer um dump de um banco de dados MySQL com PHP?

Question: Atualmente, para exportar somente a estrutura de determinado banco de dados, eu uso o seguinte:
mysqldump -h host -u usuario --no-data --database banco > dump.sql -psenha

Isso gera um arquivo SQL, tudo resolvido. No entanto, esse é um processo manual que me custa tempo, e posso esquecer de fazê-lo, então, pensei em fazer um script em PHP para automatizá-lo dentro do meu sistema. O problema é que não sei como fazer isso.
Eu gostaria de saber se existe algum comando SQL específico para que eu possa gerar esse arquivo. O requisito de ser em PHP é que posso precisar executar isso em um servidor compartilhado, aí teria várias restrições de outras linguagens (como shell script, utilizar o próprio mysqldump, etc.).
Comment: Calebe, segue algumas pergintas : O servidor roda em linux ou windows? Você possui acesso ao crontab para agendar alguma execução de Script? Caso seja linux e caso tenha acesso ao crontab, podes agendar a execução de um .sh.
O Shell seria responsável por chamar o mysqldump.
Comment: So pra lembrar, passei um trabalhão pra fazer funcionar o mysqldump, por que os sites não explicam que o cmd deve ser executado na pasta bin de onde esta instalado o mysql (não adianta copiar os arquivos "mysql.exe" e "mysqldump.exe" para o c:/system32 que ele não acha o banco de dados), oooou... fazer um comando anterior que leve o cmd para a pasta bin, dessa forma "cd c:\xampp\mysql\bin" (no meu caso esta instalado dentro do xampp). Espero ter ajudado nas instruções, valeu estava procurando como executar em php.
Answer: Use a função system do PHP:
system('mysqldump -h host -u usuario --no-data --database banco > dump.sql -psenha');

Veja mais informações: http://php.net/manual/pt_BR/function.system.php
E então é só criar um cronjob para que o script seja executado 1 vez por dia, ou conforme desejar.

Aqui uma maneira de receber uma cópia do banco de dados por e-mail:
<?php
// Backup do site

$dbhost = 'localhost';
$dbuser = 'usuario_aqui';
$dbpass = 'password_aqui';
$dbname = 'database_aqui';

// Seu e-mail aqui
$sendto = 'Eu <firstname.lastname@example.com>';

// O remetente. Pode ser firstname.lastname@example.com
$sendfrom = 'Backup <firstname.lastname@example.com>';

// Assunto do e-mail
$sendsubject = 'Backup do site ' . date('d/m/Y');

// Corpo do e-mail
$bodyofemail = 'Backup diário do meu site';

$backupfile = 'Autobackup_' . date("Ymd") . '.sql';
$backupzip = $backupfile . '.tar.gz';
system("mysqldump -h $dbhost -u $dbuser -p$dbpass --lock-tables $dbname > $backupfile");
system("tar -czvf $backupzip $backupfile");

include('Mail.php');
include('Mail/mime.php');

$message = new Mail_mime();
$text = "$bodyofemail";
$message->setTXTBody($text);
$message->AddAttachment($backupzip);
$body = $message->get(array(
    'head_charset' => 'utf-8',
    'text_charset' => 'utf-8',
    'html_charset' => 'utf-8'
));
$extraheaders = array("From"=>"$sendfrom", "Subject"=>"$sendsubject");
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send("$sendto", $headers, $body);

// Remover o arquivo do servidor (opcional)
unlink($backupzip);
unlink($backupfile);
?>

Não lembro quem criou o script acima originalmente. Só lembro de ter modificado o código um pouco.
Comment: Então veja http://davidwalsh.name/backup-mysql-database-php. O link é antigo, mas fazendo algumas adaptações pode funcionar. Vou testar mais tarde.
Comment: Mas como ter certeza que o servidor me permitirá utilizar o `mysqldump`?
Comment: Se a função ``system`` estiver habilitada, o mysqldump vai funcionar. O único problema é que algumas hospedagens compartilhadas bloqueiam o uso dessa função, por ser perigosa.
Comment: Infelizmente, como tinha dito na pergunta, não posso executar em meu servidor. `Warning: system() has been disabled for security reasons in /home/... on line 48`
Comment: Funcionou perfeitamente.
Answer: Use o crontab para agendar tarefas de backup, além de compactar os bancos com gzip, o que deixa o tamanho dos backups muito menor.
Para agendar tarefas com o crontab, supondo que você tenha as devidas permissões no sistema, execute o comando crontab -e.
Por exemplo, no meu caso eu uso o crontab para agendar uym backup diário do meu banco:
0 * * * * /bin/sh /home/ec2-user/sh/backup_mysql.sh > /dev/null 2>&1

E dentro do backup_mysql.sh eu deixo diversos comandos mysqldump, no modelo abaixo:
mysqldump -u<usuario> -p<senha> <banco> | gzip > /home/ec2-user/backups/mysql/<banco>-`date '+%Y-%m-%d'`.sql.gz

Essa é o que eu acredito ser a melhor prática para uma rotina de backups periódicos de bancos de dados. Tente usar esse modelo para encontrar o que melhgor serve a seus propósitos.
Answer: Acabei chegando à uma solução em PHP mesmo, baseado no script do site postado pelo @Gabriel Santos. Segue:
class DatabaseDump {
    private $db;
    private $host, $user, $pass, $dbname;
    private $sql, $removeAI;

    public function __construct($host, $user, $pass, $dbname) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->dbname = $dbname;
        $this->removeAI = true;

        try {
            $this->db = new PDO('mysql:dbname='.$dbname.';host='.$host, $user, $pass);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            die;
        }
    }

    private function ln($text = '') {
        $this->sql = $this->sql . $text . "\n";
    }

    public function dump($file) {
        $this->ln("SET FOREIGN_KEY_CHECKS=0;\n");

        $tables = $this->db->query('SHOW TABLES')->fetchAll(PDO::FETCH_BOTH);

        foreach ($tables as $table) {
            $table = $table[0];
            $this->ln('DROP TABLE IF EXISTS `'.$table.'`;');

            $schemas = $this->db->query("SHOW CREATE TABLE `{$table}`")->fetchAll(PDO::FETCH_ASSOC);

            foreach ($schemas as $schema) {
                $schema = $schema['Create Table'];
                if($this->removeAI) $schema = preg_replace('/AUTO_INCREMENT=([0-9]+)(\s{0,1})/', '', $schema);
                $this->ln($schema.";\n\n");
            }
        }

        file_put_contents($file, $this->sql);
    }
}

Comment: essa classe só exporta a estrutura da sql.
Answer: mysqldump
A coisa não é tão simples assim. É melhor usar o mysqldump a partir do PHP com shell_exec ou system, ou simplesmente agendar um cronjob, conforme sugerido.
Eu particularmente uso cronjob a partir de um sistema remoto, que chama o mysqldump, gerando meus backup diários do banco de dados de pequenas aplicações de clientes meus por aí.

$this->dbutil->backup()
Certa ocasião, o servidor do provedor chato que hospedava a aplicação do projeto no qual eu estava trabalhando não permitia acesso remoto ao MySQL de jeito nenhum. Eu não tinha acesso SSH. O mysqldump não era uma opção. Não tinha um phpMyAdmin da vida pra me gerar um dump.
De modo que os desenvolvedores anteriores até já tinham feito o seu script PHP que fazia as queries, desde SHOW TABLES até tudo o mais que você imaginar, e montava o respectivo arquivo SQL, contendo o dump.
O problema é que não funcionava. Mas ninguém sabia disso. Aparentemente tudo ia bem. Porém, certas strings eram truncadas. Só "descobri" isso porque usando a minha versão local da aplicação, de repente notei um conteúdo ligeiramente diferente da aplicação remota. Fiquei intrigado, e investigando cheguei ao fato de que o script não funcionava suficientemente bem para gerar um dump fiel.
A solução que encontrei foi o método backup da Database Utility Class do Code Igniter. Consegui enfim obter meu dump 100% à prova de balas, a partir do PHP.
A implementação dessa função que gera o dump é uma tarefa delicada. Recomendo que dê uma olhada no código da função backup no repositório do Code Igniter (tem que dar uma olhada aqui também). O pessoal do projeto que trabalhei tentou reinventar essa roda e falhou.
Portanto, se precisar obter um dump de um banco de dados MySQL com PHP, sugiro que utilize essa função, ou que faça a sua versão a partir dessa, que comprovadamente funciona.
Exemplo de código:
// Carrega a classe de utilidades de banco de dados
$this->load->dbutil();

// Coloca o dump de todo o seu banco de dados numa variável
$backup =& $this->dbutil->backup();

// Gravando o dump num arquivo
$this->load->helper('file');
write_file('/path/to/mybackup.gz', $backup);

// Enviando o arquivo para o navegador
$this->load->helper('download');
force_download('mybackup.gz', $backup);

Configurações para o dump podem ser feitas através de um array de opções, a ser utilizado como o primeiro parâmetro para a função de backup. Por exemplo:
$prefs = array(
    'tables'      => array('table1', 'table2'),  // Tabelas para incluir no dump
    'ignore'      => array(),           // Tabelas para não incluir no dump
    'format'      => 'txt',             // gzip, zip, txt
    'filename'    => 'mybackup.sql',    // Nome do arquivo - APENAS PARA FORMATO ZIP
    'add_drop'    => TRUE,              // Incluir comandos DROP TABLE no dump
    'add_insert'  => TRUE,              // Incluir os dados das tabelas em comandos INSERT no dump
    'newline'     => "\n"               // Caracter para final de linha a ser usado no dump
);

$this->dbutil->backup($prefs);

Answer: Não sei se é isso que você precisa, mas segue um código completo pra fazer bkp do seu banco de dados, só salvar o código em um arquivo php, criar uma pasta chamada "db_bkp" e não esquecer de preencher os dados de acesso ao banco de dados
<?php
ini_set('display_errors',1); ini_set('display_startup_erros',1); error_reporting(E_ALL);//force php to show any error message

backup_tables(DB_HOST,DB_USER,DB_PASS,DB_NAME);//don't forget to fill with your own database access informations

function backup_tables($host,$user,$pass,$name)
{
    $link = mysqli_connect($host,$user,$pass);
    mysqli_select_db($link, $name);
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
        $i=0;
        while($row = mysqli_fetch_row($result))
        {
            $tables[$i] = $row[0];
            $i++;
        }
    $return = "";
    foreach($tables as $table)
    {
        $result = mysqli_query($link, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $return .= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        for ($i = 0; $i < $num_fields; $i++)
        {
            while($row = mysqli_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j < $num_fields; $j++)
                {
                    $row[$j] = addslashes($row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j < ($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }
    //save file
    $handle = fopen('db_bkp/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');//Don' forget to create a folder to be saved, "db_bkp" in this case
    fwrite($handle, $return);
    fclose($handle);
    echo "bkp efetuado com sucesso";//Sucessfuly message
}
?>

Comment: Olá, seja bem vindo ao StackOverflow em português, por favor evite ficar repetindo suas respostas em diversas perguntas! Quando você tiver pontos suficiente poderá inserir comentários em todas as peguntas e assim,  caso ache que sua resposta possa ajudar mais de um pergunta insira nos comentários da outra pergunta o link da sua resposta.
Answer: // aqui esta o script para tal função funcionando perfeitamente e testado
// exaustivamente em meu servidor; não inventei nada somente fiz a junção de
// uma parte de código que peguei aqui e uma outra parte de um outro lugar e // efetuei pequenas correções; Não necessita de mais nada além do código
// na tarefa CRON inclua php -q /home/usuariodosite/pasta aonde esta o script

<?php
// Backup do banco de dados do site

$dbhost = 'localhost';          //local aonde se encontra o banco de dados
$dbuser = '---';    // usuário do banco de dados
$dbpass = '---';         // senha do usuário do banco de dados
$dbname = '---';   // nome do banco de dados

// rotina que faz o backup não mexer

$backupfile = 'Autobackup_' . date("Ymd") . '.sql';
$backupzip = $backupfile . '.tar.gz';
system("mysqldump -h $dbhost -u $dbuser -p$dbpass --lock-tables $dbname > $backupfile");
system("tar -czvf $backupzip $backupfile");

// ROTINA DE ENVIO DO EMAIL COM O ANEXO

$to = "---";         //Quem vai receber o email
$from = "---";  //Quem está enviando (Endereço a ser apresentado como da pessoa que está enviando)
$subject = 'Backup do Banco de Dados Sql ';          //Assunto do email
$messagem = 'cópia do backup do banco de dados Sql'; //Mensagem a ser enviada
$path = "---";                  //Diretório onde o arquivo a ser enviado está salvo
$filename = "$backupzip";                        //Nome do arquivo anexo a ser enviado - não mexer aqui

// ---------- Não altere nada deste ponto em diante ----------

$headers = 'From: ' .     "$from\r\n" . 'Reply-To: ' . "$from\r\n";

$file = $path . "/" . $filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

$separator = md5(time());   // a random hash será necessário para separar conteúdos diversos a serem enviados
$eol = PHP_EOL;   // Define o retorno de carro a ser utilizado

// main header (multipart mandatory)
$headers = "From: < $from >" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol . $eol;

// messagem
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: text/plain; charset=\"utf-8\"" . $eol;
$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$headers .= $messagem . $eol . $eol;

// attachment
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: base64" . $eol;
$headers .= "Content-Disposition: attachment" . $eol . $eol;
$headers .= $content . $eol . $eol;
$headers .= "--" . $separator . "--";

//SEND Mail

if (mail($to, $subject, "", $headers)) {
   echo "Sucesso no envio do Email";
} else {
   echo "Erro! Não foi possível enviar o email solicitado";
}

// Remover o arquivo do servidor (opcional)
unlink($backupzip);
unlink($backupfile);
?>

Comment: Oi Amauri! Podes explicar qual é a(s) linha(s) do teu código que respondem à pergunta _"Como fazer um dump de um banco de dados MySQL"_?
Answer: Aqui tem um tutorial completo e atualizado para resolver sua necessidade:
https://startinn.com.br/blog/post?p=93_realizando-backup-automatico-do-banco-em-servidor-de-hospedagem-linux-com-php
Com ele é possível criar uma cópia do banco MySQL de maneira automática utilizando um arquivo PHP e uma tarefa CRON. O arquivo é compactado com ZIP.


Updating to Drupal 7.x-dev until next stable release

Question: I am currently using Drupal core 7.7 and Commerce 7.x-1.0-rc3 which requires changes that are only currently present in Drupal core 7.x-dev.
If I upgrade to 7.x-dev now in order to get the updates that the latest Commerce version needs, am I committing my project to following dev branch, and is there a danger of not being able to come back to stable cleanly, when the next stable release comes about?
It's not a live site, so temporary instability a dev branch may introduce is not necessarily an issue if I'll end up back on stable soon.
EDIT: Additionally, instruction for how to upgrade core from stable to dev using Drush would be super: Drush: Update core from stable to dev  :)
Answer: No you are not: the Drupal core development workflow makes minor versions just tags of the main 7.x development branch. Periodically, the branch maintainer decides enough things have been committed to the branch to make a release worthwhile, and a new minor version release is packaged.
So let's say you download a snapshot of 7.x-dev dated 2011-08-15. At the end of the month, Drupal 7.8 is released. Drupal 7.8 would contain all of the changes you had received in the 2011-08-15 snapshot, and anything else committed between that point and the end of the month. It's essentially the same as if you downloaded a new development snapshot on 2011-08-30.
So, if you need to use the dev branch, feel free to do so with relative impunity.


How to add / modify existing jquery functionality

Question: I'm trying to disable/enable a button based on the checkbox, which I am unable to do. Here is the sample I worked on. For enabled and disabled, different buttons have to be used.
function toggleContinue() {
  $(document).ready(function() {
        $("#swpRequired").click(function() {
              $("input,select").change(function() {
                $("#disableContinue").attr("style", "display:inline-block");
                $("#continueButton").attr("style", "display:none");
              });
         });

         $("#swpRequired").click(function() {
              $("input,select").change(function() {
                 $("#disableContinue").attr("style", "display:none");
                 $("#continueButton").attr("style", "display:inline-block;");
               });
          });
    });
 }

Comment: Are you using jQuery UI (which may replace the buttons with a bunch of UI junk) or just raw HTML with jQuery?  If it's raw HTML with jQuery, you should be able to set the `disabled` property to disable the button with very little fuss. `$("#myButton").attr("disabled", true);`
Comment: I have to use different buttons, so I think it may not work
Answer: Try this. use prop method of jquery

function s()
{
if($("#a").prop('disabled')==false)
$("#a").prop('disabled','true')
else
$("#a").removeAttr('disabled')

}

<input type="checkbox"  onchange="s()" id="b"/>enable
<input type="button" value="click" id="a">
Answer: You could use attr() to disable/enable the button based on checkbox's value:

$(document).ready(function() {
  $("#swpRequired").click(function() {
      $("#continueButton").attr("disabled", this.checked);
    });
});

<input type="checkbox" id="swpRequired" />
<button id="continueButton">continue</button>
Answer: You can use change event and take the help of disabled property of button.
Solution will be like:

$(document).on('change', "#checkbox", function()
{
  if ($(this).prop("checked") == true)
  {
    $("#btn").prop('disabled',true)
  }
  else
  {
    $("#btn").prop('disabled',false)
  }
});

<input type="checkbox" id="checkbox"/>enable
<input type="button" value="click" id="btn">
Comment: Object doesn't support property or method 'on'