What are the worst (commonly adopted) ideas/principles in statistics?

Question: In my statistical teaching, I encounter some stubborn ideas/principles relating to statistics that have become popularised, yet seem to me to be misleading, or in some cases utterly without merit.  I would like to solicit the views of others on this forum to see what are the worst (commonly adopted) ideas/principles in statistical analysis/inference.  I am mostly interested in ideas that are not just novice errors; i.e., ideas that are accepted and practiced by some actual statisticians/data analysts.  To allow efficient voting on these, please give only one bad principle per answer, but feel free to give multiple answers.
Comment: I don't know whether I would call these ideas "silly". If they are commonly accepted, then their wrongness is obviously not obvious. How about just calling them "worst ideas", or "worst practices"?
Comment: ARIMA : A marvel of theoretical rigor and mathematical elegance that is almost useless for any realistic business time series (auto.arima and similar automated tools always p,d,q orders that were just as well handled by a more intuitive ES approach).
Comment: @SkanderH.: do you want to post your comment as an answer? Maybe add a pointer to how incredulous the statistics community was when it turned out that ARIMA was no good at forecasting in the first M competition, as summarized very nicely and entertainingly by [Hyndman (2020, *IJF*)](https://doi.org/10.1016/j.ijforecast.2019.03.015).
Comment: Related:  https://stats.stackexchange.com/questions/219471/what-are-some-examples-of-anachronistic-practices-in-statistics
Comment: Related: https://stats.stackexchange.com/questions/4551/what-are-common-statistical-sins/44071
Comment: I feel like very basic statistics is not as much intuitive as basic school physics. Or maybe there are much more intuitive base but I don't came to know it.
Answer: I'll present one novice error (in this answer) and perhaps one error committed by more seasoned people.
Very often, even on this website, I see people lamenting that their data are not normally distributed and so t-tests or linear regression are out of the question.  Even stranger, I will see people try to rationalize their choice for linear regression because their covariates are normally distributed.
I don't have to tell you that regression assumptions are about the conditional distribution, not the marginal.  My absolute favorite way to demonstrate this flaw in thinking is to essentially compute a t-test with linear regression as I do here.
Comment: @fffrost I wouldn't recommend assessing the normality assumption via grouping by categorical predictors, but that is the idea yes.  The assumption of normality *is essentially about the residuals*, which explains why this assumption is often assessed via QQplots of the residuals.
Comment: I saw this one on Data Science earlier today: https://datascience.stackexchange.com/q/77456/73930. It also seems like we get this on here about every week.
Comment: Novice here. Regarding this point, are you essentially saying to group the outcome variable by the levels of the predictor (if categorical like this) and then to see whether that resulting distribution is normal? In fact, I thought that even this was besides the point and that it was simply the residuals of the model after you fit it that are required to be normal?
Answer: Post hoc power analysis
That is, using power analysis after a study has been completed rather than before, and in particular plugging in the observed effect size estimate, sample size, etc.
Some people have the intuition that post hoc power analysis could be informative because it could help explain why they attained a non-significant result. Specifically, they think maybe their failure to attain a significant result doesn't mean their theory is wrong... instead maybe it's just that the study didn't have a large enough sample size or an efficient enough design to detect the effect. So then a post hoc power analysis should indicate low power, and we can just blame it on low power, right?
The problem is that the post hoc power analysis does not actually add any new information. It is a simple transformation of the p-value you already computed. If you got a non-significant result, then it's a mathematical necessity that post hoc power will be low. And conversely, post hoc power is high when and only when the observed p-value is small. So post hoc power cannot possibly provide any support for the hopeful line of reasoning mentioned above.
Here's another way to think about the conceptual problem with these kinds of post hoc power (PHP) exercises -- the following passage is from this paper by Russ Lenth:

Note that the problem here is not the chronological issue of running a power analysis after the study is completed per se -- it is possible to run after-the-fact power analysis in a way that is informative and sensible by varying some of the observed statistics, for example to estimate what would have happened if you had run the study in a different way. The key problem with "post hoc power analysis" as defined in this post is in simply plugging in all of the observed statistics when doing the power analysis. The vast majority of the time that someone does this, the problem they are attempting to solve is better solved by just computing some sort of confidence interval around their observed effect size estimate. That is, if someone wants to argue that the reason they failed to reject the null is not because their theory is wrong but just because the design was highly sub-optimal, then a more statistically sound way to make that argument is to compute the confidence interval around their observed estimate and point out that while it does include 0, it also includes large effect size values -- basically the interval is too wide to conclude very much about the true effect size, and thus is not a very strong disconfirmation.
Comment: Ooh, this is a good one. +1
Comment: Small nitpick: I think the posthoc analysis **is** a reasonable idea (thinking hard about minimal clinical significance value, learning from the nuisance parameters, etc), but is often done in an extremely lazy, meaningless way. The point I want to make is the issue is more with people not taking the PHP seriously rather than the core idea itself. This is important, because if one uses this argument to *replace* PHP with something else, we need to chose something that will be used well by the masses, not just us.  Alternatively, maybe we shouldn't replace it all, just remove from requirements.
Comment: @CliffAB I agree with what I believe you are saying. I added a couple caveats & clarifications that I think are in the spirit of your point
Answer: The idea that because something is not statistically significant, it is not interesting and should be ignored.
Comment: that quote is also wrong - absence of evidence is *evidence* of absence, just not *proof* of absence
Comment: Commonly quoted as "The absence of evidence is not the evidence of absence" I believe.
Comment: @probabilityislogic conditioned on the fact I collect the right data and analyze it correctly, then I agree.
Comment: @probabilityislogic Absence of evidence of an effect is insufficient to serve as evidence of absence of an effect (of at least some size). You can actually provide evidence of the latter, and [it is not the same thing as the former](https://stats.stackexchange.com/tags/tost/info).
Comment: Aka, is it a lack of significance or a lack of measurement?
Answer: Removing Outliers
It seems that many individuals have the idea that they not only can, but should disregard data points that are some number of standard deviations away from the mean. Even when there is no reason to suspect that the observation is invalid, or any conscious justification for identifying/removing outliers, this strategy is often considered a staple of data preprocessing.
Comment: +1. I would add removing data points in general when they are arbitrarily deemed not representative (e.g. below instrument detectable limit)
Answer: Not addressing multiple hypothesis testing problems.
Just because you aren't performing a t.test on 1,000,000 genes doesn't mean you're safe from it. One example of a field it notably pops up is in studies that test an effect conditional on a previous effect being significant. Often in experiments the authors identify a significant effect of something, and then conditional on it being significant, then perform further tests to better understand it without adjusting for that procedural analysis approach. I recently read a paper specifically about the pervasiveness of this problem in experiments, Multiple hypothesis testing in experimental economics and it was quite a good read.
Answer: This seems like low hanging fruit, but stepwise regression is one error which I see pretty frequently even from some stats people.  Even if you haven't read some of the very well-written answers on this site which address the approach and its flaws, I think if you just took a moment to understand what is happening (that you are essentially testing with the data that generated the hypothesis) it would be clear that step wise is a bad idea.
Edit: This answer refers to inference problems. Prediction is something different. In my own (limited) experiments, stepwise seems to perform on par with other methods in terms of RMSE.
Comment: Gelman: https://statmodeling.stat.columbia.edu/2014/06/02/hate-stepwise-regression/ (The link agrees with you.)
Comment: @Dave God I love that blog.  Its like the XKCD of stats.  There is always a post by Gelman I can use for any situation.
Comment: @DemetriPananos, That is exactly my point. If LASSO is considered a good method and it is not generally superior to stepwise regression, that is a good enough reason to conclude stepwise regression is a good method (at least for some problems). That is why I suggest you make your answer more specific to highlight the misuses of stepwise regression in contrast to criticising stepwise regression per se.
Comment: Your answer seems to suggest stepwise regression is problematic regardless of its applications, which I think is incorrect. It also hints at one particular problem with stepwise regression, namely, hypothesis testing and taking the results at face value. In this I do see a problem. Could you perhaps make your answer more specific?
Comment: @RichardHardy In what applications would stepwise be advisable?  Stepwise takes an "all or nothing" approach to variable selection, where as sparse models like LASSO at least allow for the variable to partly contribute to the linear predictor albeit in a reduced capacity.  I think that's a much better approach than allowing a variable to either contribute fully or not.  Open to arguments to the contrary though.
Comment: @DemetriPananos, as far as I remember from "Elements of Statistical Learning" (and perhaps related books) and some papers by Tibshirani and coauthors, LASSO and stepwise regression are quite similar and either can outperform the other. I am pretty sure I have seen worked out examples showing just that. (LASSO is in between subset selection and ridge and can be outperformed by either depending on the true data generating process. Stepwise regression is just a form of subset selection.) So my takeaway is that stepwise regression is (almost or fully) as valid as LASSO for prediction.
Comment: @DemetriPananos, "Introduction to Statistical Learning" may also include relevant examples and even demonstrations with R as well as an intuitive explanation for when one model/method beats the other.
Comment: @RichardHardy In either book, I don't see any definitive evidence for one being superior to the other.  My initial preference for lasso or ridge is based off intuition, and so in the absence of any convincing experimental evidence, I'll stick with my gut but acknowledge I had little good reason to do so.  If you have any edits, feel free to suggest them.
Comment: @RichardHardy Sure, I've added an edit saying that this answer is mostly in the context of inference.
Comment: [How competitive is stepwise regression when it comes to pure prediction?](https://stats.stackexchange.com/questions/594106/how-competitive-is-stepwise-regression-when-it-comes-to-pure-prediction)
Answer: ARIMA!!! - a marvel of theoretical rigor and mathematical elegance that is almost useless for any realistic business time series.
Ok, that is an exaggeration: ARIMA and similar models like GARCH are occasionally useful. But ARIMA is not nearly as general purpose a model as most people seem to think it is.
Most competent Data Scientists and ML Engineers who are generalists (in the sense that they don't specialize in time series forecasting or econometrics), as well as MBA types and people with solid general statistics backgrounds, will default to ARIMA as the baseline model for a time series forecasting problem. Most of the time they end up sticking with it. When they do evaluate it against other models, it is usually against more exotic entities like Deep Learning Models, XGBoost, etc...
On the other hand, most time series specialists, supply chain analysts, experienced demand forecasting analysts, etc...stay away from ARIMA. The accepted baseline model and the one that is still very hard to beat is Holt-Winters, or Triple Exponential Smoothing. See for example "Why the damped trend works" by E S Gardner Jr & E McKenzie. Beyond academic forecasting, many enterprise grade forecasting solutions in the demand forecasting and the supply chain space still use some variation of Holt-Winters. This isn't corporate inertia or bad design, it is simply the case that Holt-Winters or Damped Holt-Winters is still the best overall approach in terms of robustness and average overall accuracy.
A brief history lesson:
Some history might be useful here: Exponential Smoothing models, Simple ES, Holt's model, and Holt-Winters, were developed in the 50s. They proved to be very useful and pragmatic, but were completely "ad-hoc". They had no underlying statistical theory or first principles - they were more of a case of: How can we extrapolate time series into the future? Moving averages are a good first step, but we need to make the moving average more responsive to recent observations. Why don't we just add an $\alpha$ parameter that gives more importance to recent observation? - This was how simple exponential smoothing was invented. Holt and Holt-Winters were simply the same idea, but with the trend and seasonality split up and then estimated with their own weighted moving average models (hence the additional $\beta$ and $\gamma$ parameters). In fact, in the original formulations of ES, the parameters $\alpha$, $\beta$, and $\gamma$ were chosen manually based on their gut feeling and domain knowledge.
Even today, I occasionally have to respond to requests of the type "The sales for this particular product division are highly reactive, can you please override the automated model selection process and set $\alpha$ to 0.95 for us" (Ahhh - thinking to myself - why don't y'all set it to a naive forecast then??? But I am an engineer, so I can't say things like that to a business person).
Anyway, ARIMA, which was proposed in the 1970s, was in some ways a direct response to Exponential Smoothing models. While engineers loved ES models, statisticians were horrified by them. They yearned for a model that had at least some theoretical justification to it. And that is exactly what Box and Jenkins did when they came up with ARIMA models. Instead of the ad-hoc pragmatism of ES models, the ARIMA approach was built from the ground up using sound first principles and highly rigorous theoretical considerations.
And ARIMA models are indeed very elegant and theoretically compelling. Even if you don't ever deploy a single ARIMA model to production in your whole life, I still highly recommend that anyone interested in time series forecasting dedicate some time to fully grasping the theory behind how ARIMA works, because it will give a very good understanding of how time series behave in general.
But ARIMA never did well empirically, see here. Hyndman writes (and quotes others):

Many of the discussants seem to have been enamoured with ARIMA models.
"It is amazing to me, however, that after all this exercise in identifying models, transforming and so on, that the autoregressive moving averages come out so badly. I wonder whether it might be partly due to the authors not using the backwards forecasting approach to obtain the initial errors". — W.G. Gilchrist

"I find it hard to believe that Box-Jenkins, if properly applied, can actually be worse than so many of the simple methods". — Chris Chatfield

At times, the discussion degenerated to questioning the competency of the authors:
"Why do empirical studies sometimes give different answers? It may depend on the selected sample of time series, but I suspect it is more likely to depend on the skill of the analyst … these authors are more at home with simple procedures than with Box-Jenkins". — Chris Chatfield

When ARIMA performs well, it does so only because the models selected are equivalent to Exponential Smoothing models (there is some overlap between the ARIMA family and the ES family for $ARIMA(p,d,q)$ with low values of $p$, $d$, and $q$ - see here and here for details).
I recall once working with a very smart business forecaster who had a strong statistics background and who was unhappy that our production system was using exponential smoothing, and wanted us to shift to ARIMA instead. So him and I worked together to test some ARIMA models. He shared with me that in his previous jobs, there was some informal wisdom around the fact that ARIMA models should never have values of $p$, $d$, or $q$ higher than 2. Ironically, this meant that the ARIMA models we were testing were all identical to or very close to ES models. It is not my colleague's fault though that he missed this irony. Most introductory graduate and MBA level material on time series modeling focus significantly or entirely on ARIMA and imply (even if they don't explicitly say so) that it is the end all be all of statistical forecasting. This is likely a holdover from the mind set that Hyndman referred to in the 70s, of academic forecasting experts being "enamored" with ARIMA. Additionally, the general framework that unifies ARIMA and ES models is a relatively recent development and isn't always covered in introductory texts, and is also significantly more involved mathematically than the basic formulations of both ARIMA and ES models (I have to confess I haven't completely wrapped my head around it yet myself).
Ok, why does ARIMA perform so poorly?
Several reasons, listed in no particular order of importance:

ARIMA requires polynomial trends: Differencing is used to remove the trend from a time series in order to make it mean stationary, so that autoregressive models are applicable. See this previous post for details. Consider a time series $$Y(t)=L(t)+T(t)$$ with $L$ the level and $T$ the trend (most of what I am saying is applicable to seasonal time series as well, but for simplicity's sake I will stick to the case trend only). Removing the trend amounts to applying a transformation that will map $T(t)$ to a constant $T=c$. Intuitively, the differencing component of ARIMA is the discrete time equivalent of differentiation. That is, for a discrete time series $Y$ that has an equivalent continuous time series $Y_c$, setting $d = 1$ ($Y_n'= Y_n - Y_{n-1}$) is equivalent to calculating $$\frac{dY_c}{dt}$$ and setting $d=2$ is equivalent to $$\frac{d^2Y_c}{dt^2}$$ etc...now consider what type of continuous curves can be transformed into constants by successive differentiation? Only polynomials of the form $T(t)=a_nt^n+a_{n-1}t^{n-1}...+a_1t+a_0$ (only? It's been a while since I studied calculus...) - note that a linear trend is the special case where $T(t)=a_1t+a_0$. For all other curves, no number of successive differentiations will lead to a constant value (consider and exponential curve or a sine wave, etc...). Same thing for discrete time differencing: it only transfroms the series into a mean stationary one if the trend is polynomial.   But how many real world time series will have a higher order ($n>2$) polynomial trend? Very few if any at all. Hence selecting an order $d>2$ is a recipe for overfitting (and manually selected ARIMA models do indeed overfit often). And for lower order trends,$d=0,1,2$, you're in exponential smoothing territory (again, see the equivalence table here).

ARIMA models assume a very specific data generating process: Data generating process generally refers to the "true" model that describes our data if we were able to observe it directly without errors or noise. For example an $ARIMA(2,0,0)$ model can be written as $$Y_t = a_1Y_{t-1}+a_2Y_{t-2}+c+ \epsilon_t$$ with $\epsilon_t$ modeling the errors and noise and the true model being $$\hat{Y}_t = a_1\hat{Y}_{t-1}+a_2\hat{Y}_{t-2}+c$$ but very few business time series have such a "true model", e.g why would a sales demand signal or a DC capacity time series ever have a DGP that corresponds to $$\hat{Y}_t = a_1\hat{Y}_{t-1}+a_2\hat{Y}_{t-2}+c??$$ If we look a little bit deeper into the structure of ARIMA models, we realize that they are in fact very complex models. An ARIMA model first removes the trend and the seasonality, and then looks at the residuals and tries to model them as a linear regression against passed values (hence "auto"-regression) - this will only work if the residuals do indeed have some complex underlying deterministic process. But many (most) business time series barely have enough signal in them to properly capture the trend and the seasonality, let alone remove them and then find additional autoregressive structure in the residuals. Most univariate business time series data is either too noisy or too sparse for that. That is why Holt-Winters, and more recently Facebook Prophet are so popular: They do away with looking for any complex pattern in the residuals and just model them as a moving average or don't bother modeling them at all (in Prophet's case), and focus mainly on capturing the dynamics of the seasonality and the trend. In short, ARIMA models are actually pretty complex, and complexity often leads to overfitting.

Sometimes autoregressive processes are justified. But because of stationarity requirements, ARIMA AR processes are very weird and counter intuitive: Let's try to look at what types of processes correspond in fact to an auto-regressive process - i.e. what time series would actually have an underlying DGP that corresponds to an $AR(p)$ model. This is possible for example with a cell population growth model, where each cell reproduces by dividing into to 2, and hence the population $P(t_n)$ could reasonably be approximated by $P_n = 2P_{n-1}+\epsilon_t$. Because here $a=2$ ($>1$), the process is not stationary and can't be modeled using ARIMA. Nor are most "natural" $AR(p)$ models that have a true model of the form $$\hat{Y}_t = a_1\hat{Y}_{t-1}+a_2\hat{Y}_{t-2}...+a_p\hat{Y}_{t-p}+c$$This is because of the stationarity requirement: In order for the mean $c$ to remain constant, there are very stringent requirements on the values of $a_1,a_2,...,a_p$ (see this previous post) to insure that $\hat{Y}_t$ never strays too far from the mean. Basically,$a_1,a_2,...,a_p$ have to sort of cancel each other out $$\sum_{j=1}^pa_j<1$$otherwise the model is not stationary (this is what all that stuff about unit roots and Z-transforms is about). This implication leads to very weird DGPs if we were to consider them as "true models" of a business time series: e.g. we have a sales time series or an electricity load time series, etc...what type of causal relationships would have to occur in order to insure that$$\sum_{j=1}^pa_j<1?$$ e.g. what type of economic or social process could ever lead to a situation where the detrended sales for 3 weeks ago are always equal to negative the sum of the sales from 2 weeks ago and the sales from last week? Such a process would be outlandish to say the least. To recap: While there are real world processes that can correspond to an autoregressive model, they are almost never stationary (if anyone can think of a counter example - that is a naturally occurring stationary AR(p) process, please share, I've been searching for one for a while). A stationary AR(p) process behaves in weird and counter intuitive ways (more or less oscillating around the mean) that make them very hard to fit to business time series data in a naturally explainable way.

Hyndman mentions this (using stronger words than mine) in the aforementioned paper:

This reveals a view commonly held (even today) that there is some single model that describes the data generating process, and that the job of a forecaster is to find it. This seems patently absurd to me — real data come from processes that are much more complicated, non-linear and non-stationary than any model we might dream up — and George Box himself famously dismissed it saying, "All models are wrong but some are useful".

But what about the 'good' ARIMA tools?
At this point would point out to some modern tools and packages that use ARIMA and perform very well on most reasonable time series (not too noisy or too sparse), such as auto.arima() from the R Forecast package or BigQuery ARIMA. These tools in fact rely on sophisticated model selection procedures which do a pretty good job of ensuring that the $p,d,q$ orders selected are optimal (BigQuery ARIMA also uses far more sophisticated seasonality and trend modeling than the standard ARIMA and SARIMA models do). In other words, they are not your grandparent's ARIMA (nor the one taught in most introductory graduate texts...) and will usually generate models with low $p,d,q$ values anyway (after proper pre-processing of course). In fact now that I think of it, I don't recall ever using auto.arima() on a work related time series and getting $p,d,q > 1$, although I did get a value of $q=3$ once using auto.arima() on the Air Passengers time series.
Conclusion
Learn traditional ARIMA models in and out, but don't use them. Stick to state space models (ES incredibly sophisticated descendants) or use modern automated ARIMA model packages (which are very similar to state space models under the hood anyway).
Comment: I do not think ARIMA belongs among the *worst statistical practices*. The quoted paper contains several more mentions of ARIMA, and, contrary to the ones you chose to cite, they are positive. What you identify appear to be some historical misuses of ARIMA and some unfounded optimism from early 1980s. The misuses are not the model's fault, and they are already obsolete among professionals, but of course there will be people lagging behind a couple (or more) decades repeating the old mistakes.
Comment: @RichardHardy: I do not think that ARIMA is among the worst practices. However, the continued unthinking preference for ARIMA as a benchmark certainly is. I have seen countless RfIs (Requests for Information) where we are asked whether our forecasting system contains ARIMA, which is completely, utterly, obviously useless in our use cases (retail forecasting). Nevertheless, one of the first things people learn when they read about forecasting is ARIMA, and they keep on asking for it. Its prevalence is out of all proportion to its practical usefulness.
Comment: @StephanKolassa, your comment sounds reasonable. I wish the answer adopted a similar tone. However, the current formulation (especially the opening statements) appear too harsh and not nuanced enough.
Comment: Some counter-evidence from current times: a 2020 paper ["Distributed ARIMA Models for Ultra-long Time Series"](https://arxiv.org/pdf/2007.09577.pdf) by Rob J. Hyndman and coauthors says that *ARIMA models also frequently serve as the benchmark methods for model
combination because of their excellent performance in time series forecasting (Wang et al., 2019; Montero-Manso et al., 2020).*
Comment: That the true process is different from the model is common to most statistical models, not only ARIMA. You can bash most of the models this way. The relevant point is, the model should be useful, while it does not have to be correct. The closing recommendation to use modern automated ARIMA model packages contradicts the criticism of the model itself. Perhaps the answer should be reformulated, directing the criticism against certain misuses of the model rather than the model itself? (I do not disagree with the whole answer nor do I find it useless, but I think it can be improved.)
Comment: @RichardHardy Thanks for the feedback. Can you point out the contradiction you mention in more detail so I can fix it? w/r regards, the paper I quote was just a ref backup to trends I am witnessing now in my local DS community at least.
Comment: Another point: you keep using (as in your other answers) $\dots+c+\sigma$ to denote what in time series literature is $\dots+c+\varepsilon_t$. The former notation is confusing; $\varepsilon_t$ is a random variable and varies with time, while $\sigma$ is a constant usually reserved for a scale parameter (typically, standard deviation) of a distribution. I also wonder whether the equations with hats make sense. What do the hats denote?
Comment: By *contradiction* I mean the coexistence of two claims in a single answer: (1) ARIMA is bad (deserving a spot in the list of worst statistical practices) and (2) Use advanced versions of ARIMA (such as `auto.arima`). Also, what do hats denote in your formulas?
Comment: @RichardHardy: I understand your point. But to be honest, I find the opening statement spot-on. YMMV.
Comment: +1. Credit where is due, this is a good thought-provoking post. (I "like" ARIMA and I use `auto.arima` without a second thought if it tops my cross-validation schema.)
Answer: Regression towards the mean  is a far more common problem than is often realised.
It is also one of those things that is actually quite simple but appears to be quite nebulous on closer inspection, and this is partly due to the narrow way that it is usually taught. Sometimes it is attributed entirely to measurement error, and that can be quite misleading. It is often "defined" in terms of extreme events - for example, if a variable is sampled and an extreme value observed, the next  measurement tends to be less extreme. But this is also misleading because it implies that it is the same variable being measured. Not only may RTM arise where the subsequent measures are on different variables, but it may arise for measures that are not even repeated measures on the same subject. For example some people recognise RTM from the original "discovery" by Galton who realised that the children of tall parents also tend to be tall but less tall than their parents, while children of short parents also tend to be short but less short than their parents.
Fundamentally, RTM is a consequence of imperfect correlation between two variables. Hence, the question shouldn't be about when RTM occurs - it should be about when RTM doesn't occur. Often the impact may be small but sometimes it can lead to completely spurious conclusions. A very simple one is the observation of a "placebo effect" in clinical trials. Another more subtle one, but potentially much more damaging is the inference of " growth trajectories" in lifecourse studies where conditioning on the outcome has implicitly taken place.
Answer: Equating a high $R^2$ with a "good model" (or equivalently, lamenting - or, in the case of referees of papers, criticizing - that $R^2$ is "too" low). More discussion is provided, e.g. here and here.
As should be universally appreciated, $R^2$ increases (more precisely, never decreases, see here) in the number of regressors in the model, and can hence always be made equal to 1 by including sufficiently many powers and interaction terms in the model (see the related illustration below). That is, of course, a very bad idea because the resulting model will strongly overfit and hence predict very poorly out of sample.
Also, when you regress something onto itself, $R^2$ will be 1 by construction (as residuals are zero), but you have of course learnt nothing. Yet, praising high $R^2$ in similar setups (e.g., this year's GDP as a function of last year's, which in view of growth rates of around 2% is more or less the same) is not uncommon.
Conversely, a regression with a small $R^2$ can be highly interesting when the effect that is responsible for that $R^2$ is one that you can actually act upon (i.e., is causalish).

<code># R^2 increases even if you regress on pure noise
n <- 15
regressors <- n-1 # enough, as we'll also fit a constant
y <- rnorm(n)
X <- matrix(rnorm(regressors*n),ncol=regressors)

collectionR2s <- rep(NA,regressors)
for (i in 1:regressors){
  collectionR2s[i] <- summary(lm(y~X[,1:i]))$r.squared
}
plot(1:regressors,collectionR2s,col="purple",pch=19,type="b",lwd=2)
abline(h=1, lty=2)
</code>
Comment: To be fair, this is not a problem of the R-squared in specific but rather of performance measures evaluated on the training data. So it is exactly the same problem for MSE, MAE, Accuracy, ...
Answer: You have a nice answer to one that I posted a few weeks ago.
Debunking wrong CLT statement
False claim: the central limit theorem says that the empirical distribution converges to a normal distribution.
As the answers to my question show, that claim is utterly preposterous (unless the population is normal), yet the answers also tell me that this is a common misconception.
Comment: There is this overstatement problem. I've heard it from professors 'we have 100 students taking the class, so the clt says the grades are normally distributed'
Comment: And there is the understatement problem. 'I cannot do a t test, my data isn't normal'. Here the clt would often help more than people see
Answer: Forgetting that bootstrapping requires special care when examining distributions of non-pivotal quantities (e.g., for estimating their confidence intervals), even though that has been known since the beginning.
Comment: @Johannes Efron, in the paper linked above, noted the issue with respect to the distribution of correlation coefficient estimates. See Section 8, Remarks B and E (pages 19-22). The plug-in estimator for the Shannon entropy is even more troublesome; see [this page](https://stats.stackexchange.com/q/156235/28500) for example. Dangers of blindly bootstrapping to get confidence intervals are discussed [here](https://stats.stackexchange.com/q/355781/28500).
Comment: What are examples of non-pivotal quantities for which this mistake is made?
Answer: "A complex model is better than a simple one". Or a variation thereof: "We need a model that can model nonlinearities."
Especially often heard in forecasting. There is a strong preconception that a more complex model will forecast better than a simple one.
That is very often not the case.
Comment: Someone could post as a misconception that simple linear models are always a good idea....
Comment: +1 Most of the time people have no idea how to take into account the uncertainties in the fit parameters of their complicated model when doing predictions. If you pretend that your point estimates are 100% accurate, you get very nice-looking forecasts that don't mean anything. Even worse: more often than not there is no agreed-upon method for propagating the errors in the model parameters into the forecast. Only Bayesian methods seem to have sure-fire methods for that.
Answer: Doing statistical inference with a - most certainly - biased convenience sample. (And then caring primarily about normality instead of addressing bias...)
Answer: People often assume that the uniform prior is uninformative.  This is usually false.
Comment: Yes! I wonder how many people realise that saying $X \sim U(0,1)$ is equivalent to saying $-\log(X) \sim Exp(1)$
Answer: Assuming that controlling for covariates is equivalent to eliminating their causal impact—this is false.
The original example given by Pearl is that of qualifications, gender, and hiring.  We hope that qualifications affect hiring, and want to know if gender does too.  Gender can affect qualifications (unequal opportunity to education, for example).
If an average man with a given education is more likely to be hired than an average woman who happens to have that same level of education, that is evidence of sexism, right? Wrong.
The conclusion of sexism would only be justifiable if there were no confounders between Qualifications and Hiring. On the contrary, it may be that the women who happened to have the same level of education came from wealthy families, and the interviewer was biased against them for that reason.
In other words, controlling for covariates can open back door paths.  In many cases, controlling for is the best we can do, but when other back door paths are likely to exist, the evidence for causal conclusions should be considered weak.
Comment: @ben It's not just a problem with "paths that go through other explanatory variables": it's about opening back doors that *would otherwise not be open*.  In other words, controlling for covariates can paradoxically make the situation worse.
Comment: Whilst this point has some merit (+1), when I have seen statisticians control for a covariate, they are almost always aware that this only controls for its impact through paths that don't go through the other explanatory variables, and so it does not eliminate causal impacts through other explanatory variables in the model.  In short, I agree with your substantive point that the described belief is an error, but I rarely see the statistical community make this error.  (Though perhaps that is just a matter of who you talk to!)
Answer: What does a p-value mean?
ALERT TO NEWCOMERS: THIS QUOTE IS EXTREMELY FALSE
"The probability that the null hypothesis is true, duh! Come on, Dave, you're a professional statistician, and that's Statistics 101."
I get the appeal of this one, and it would be really nice to have a simple measure of the probability of the null hypothesis, but no.
Comment: It seems a stretch to think of this as a "commonly adopted idea in statistics."  This instead belongs in a pantheon of mistakes made by non-statisticians.
Comment: There is some discrepancy between the title of the question ("commonly adopted") and the body of the question ("ideas that are accepted and practiced by *some actual statisticians/data analysts*", emphasis mine). By the latter, lower, threshold, I think this surely is a valid example. There is of course also no clear definition of a statistician/data analyst, but research suggests that, at least, applied researchers with considerable training in statistics make this mistake. E.g., http://www.psicothema.com/PDF/4266.pdf.
Answer: In the medical community especially, and somewhat less often in psychology, the "change from baseline" is usually analyzed by modelling the change as a function of covariates.  Doug Altman and Martin Bland have a really great paper on why this is probably not a good idea and argue that an ANVOCA (post measure ~ covariates + baseline) is better.
Frank Harrell also does a really great job of compiling some hidden assumptions behind this approach.
Comment: Even ANCOVA is biased unless the groups are balanced with respect to the outcome, which is quite a common problem in observational studies.
Answer: It's not purely statistics, but more statistical modeling in the large sense, but a very common misconception, that I have also heard in some University courses, is that Random Forests cannot overfit.

Here
is a question where they asked exactly this, and I tried explaining why this isn't true, and where this misconception comes from.
Answer: Not realizing to what extent functional form assumptions and parametrizations are buying information in your analysis. In economics, you get these models that seem really interesting and give you a new way to potentially identify some effect of interest, but sometimes you read them and realize that without that last normality assumption that gave you point identification, the model identifies infinite bounds, and so the model really isn't actually giving you anything helpful.
Answer: When analysing change, that it is OK to create change scores (<code>followup - baseline</code> or a percent change from baseline) and then regress them on <code>baseline</code>. It's not (mathematical coupling). ANCOVA is often suggested as the best approach and it might be in the case of randomisation to groups, such as in clinical trials, but if the groups are unbalanced as if often the case in observational studies, ANCOVA can also be biased.
Comment: Funny, this is the premise of one of the formulations of the extended Kalman filter. :)
Comment: In non-randomized trials, ANCOVA is often as source of the Lord's paradox showing no effect, if there was a real difference at baseline which diminished later: change scores will find this "negative" effect, but ANCOVA won't. And the opposite in randomized studies with no post-effect: the analysis of change may "react" to the differences at baseline, which are nothing but an artefact and must be ignored (due to randomization), while the ANCOVA on post-values will correctly show no effect. BTW, in may medical problems we don't care of the final values, only the changes from the starting point.
Comment: And yes, it's widespread. The adjustment for baseline in case of analysing the change scores is formally advised by both major regulatory agencies, the FDA and EMA (and some locals) - link below. However it's often said to do it conditionally, if the correlation with baseline will exceed 0.5. https://stats.stackexchange.com/questions/459279/is-there-any-formal-guideline-that-would-indicate-the-necessity-for-adjustment-f/459286#459286
Answer: Using interaction (product) terms in regressions without using curvilinear (quadratic) terms.
A few years ago I've been thinking about it (after seeing a few papers (in economic/management fields) that were doing it), and I realized that if in the true model the outcome variable depends on the square of some or all the variables in the model, yet those are not included and instead an interaction is included in the examined model, the researcher may find that the interaction has an effect, while in fact it does not.
I then searched to see if there is an academic paper that addressed this, and I did find one (could be more, but that is what I found):
https://psycnet.apa.org/fulltext/1998-04950-001.html
You might say that it is a novice mistake, and that a real statistician should know to first try to include all terms and interactions of a certain degree in the regression. But still, this specific mistake seems to be quite common in many fields that apply statistics, and the above linked article demonstrates the misleading results it may lead to.
Answer: I vote for "specification tests," e.g., White's test for heteroscedasticity, Hausman's tests, etc. These are common in econometrics and elsewhere, to the point where many people think they comprise the actual definition of the assumptions tested rather than a means to evaluate them. You would think the recent ASA statements on p-values would have dampened the enthusiasm for these methods. However, a Google scholar search for "Hausman test" turns up 17,200 results since 2019 and 8,300 since 2020; i.e., they are not fading away.
Comment: I have seen Ph.D. students in econ-related fields talk as if the meaning of the assumption is that it is "true" if it passes the test, and "false" otherwise.  That's what I meant by "many people think they comprise the actual definition."
Comment: Sure, p>.05 obviously does not imply that the null model is true. But perhaps more importantly, p<.05 does not imply that alternative model should be used (even if true). It all depends on size of the discrepancy. Simulation is a valuable tool for learning more.
Comment: Could you elaborate on your second sentence? I am not a native speaker, perhaps that makes it difficult for me to understand it.
Comment: So do you mean that passing a test merely indicates there is insufficient evidence against the null in the direction of a specific alternative in contrast to all the directions of all the possible alternatives?
Answer: The idea that because we have in mind an "average" result, that a sequence of data that is either below or above the average means that a particular result "is due".
The examples are things like rolling a die, where a large number of "no six" outcomes are observed - surely a six is due soon!
Comment: That one sounds more like a novice mistake than a widely accepted misconception, right?
Comment: But generally it is more subtle and even goes into philosophical territory about flavours of probabilistic uncertainty. Suppose I flip a coin 9 times and get 9 heads and  *I don't show you the result*. Now I ask you: "What is the probability that after the 10th flip, I will have flipped a sequence of 10 heads in a row?" Even though 9 flips are already done, *YOU* have little choice but to stick with 2^{-10}. Had I shown you the result, you'd have said 1/2.
Comment: If your chance of a hit is 0.25 and your first three attempts are misses, it is incorrect to say that on the fourth you are "due a hit".
Answer: Examining the t-test for each variable in a regression, but not the F-tests for multiple variables.
A common practice in many fields that apply statistics, is to use a regression with many covariates in order to determine the effect of the covariates on the outcome(s) of interest.
In these researches it is common to use t-test for each of the covariates in order to determine whether we can say that this variable has an effect on the outcome or not.
(I'm putting aside the issue of how to identify a causal relation ("effect") - for now let's assume that there are reasonable identification assumptions. Or alternatively, the researcher is interested only in finding correlation, I just find it easier to speak of an "effect")
It could be that there are two or more variables that are somewhat highly correlated, and as a result including them both in the regression will yield a high p-value in each of their t-tests, but examining their combined contribution to the model by using an F-test may conclude that these variables, or at least one of them, has a great contribution to the model.
Some researches do not check for this, and therefore may disregard some very important factors that affect the outcome variable, because they only use t-tests.
Answer: "Correlation does not imply causation."
This is a true statement. Even if there is causation, it could be in the opposite direction of what is asserted.
What I have seen happen is that, when the correlation is inconvenient, people take this to mean that correlation precludes causation.
I don't see professional statisticians making this mistake, but I have seen it happen when people use that phrase to sound quantitative and rigorous in their analysis, only to botch the meaning.
Comment: Correlation precludes causation is an even worse misinterpretation. But even saying that true correlation (not a type I error) can happen without some kind of direct, indirect, common cause or inverse causation is wrong. You don't know much about this causation, but you do know that it is there somewhere
Comment: @DavidErnst I'm including this caveat to warn people not to misinterpret/over-interpret what you're saying: Take two binary random walks ... (e.g. take two distinct coins, and toss each repeatedly and let the values of each series be number of heads minus number of tails seen so far on the coin generating that series). As the sample size (number of tosses) becomes large, typically the size of the absolute correlation between the two series will tend to be quite large. [This is an example of spurious correlation among nonstationary series that are not in any way causally connected.]
Comment: This doesn't imply what you said is wrong, but I fear people might be led to misunderstand what you were suggesting. Readers beware: just because you find a big correlation (like 0.98, say, even in a very long series) doesn't mean there's causation at all.
Answer: Using statistical significance (usually at $1\%$, $5\%$ or $10\%$) of explanatory variables / regressors as a criterion in model building for explanatory or predictive purposes.
In explanatory modelling, both subject-matter and statistical validity are needed; see e.g. the probabilistic reduction approach to model building by Aris Spanos described in "Effects of model selection and misspecification testing on inference: Probabilistic Reduction approach (Aris Spanos)" and references therein. Statistical validity of parameter estimators amounts to the certain statistical assumptions being satisfied by the data. E.g. for OLS estimators in linear regression models, this is homoskedasticity and zero autocorrelation of errors, among other things. There are corresponding tests to be applied on model residuals to yield insight on whether the assumptions are violated in a particular way. There is no assumption that the explanatory variables be statistically significant, however. Yet many a practitioner applies statistical significance of individual regressors or groups thereof as a criterion of model validity in model building, just like they apply the diagnostic tests mentioned above. In my experience, this is a rather common practice, but it is unjustified and thus a bad idea.
In predictive modelling, variable selection on the basis of statistical significance may be sensible. If one aims to maximize out-of-sample likelihood, AIC-based feature selection implies a cutoff level corresponding to a $p$-value of around $16\%$. But the commonly used thresholds of $1\%$, $5\%$ and $10\%$ are suboptimal for most purposes. Hence, using statistical significance of explanatory variables at common levels of $1\%$, $5\%$ and $10\%$ as a selection criterion is a bad idea also in predictive model building.
Answer: Post-selection inference, i.e. model building and doing inference on the same data set where the inference does not account for the model building stage.
Either: Given a data set and no predetermined model, a model is built based on the patterns found in the data set.
Or: Given a data set and a model, the model is often found to be inadequate. The model is adjusted based on the patterns in the data set.
Then: The model is used for inference such as null hypothesis significance testing.
The problem: The inference cannot be taken at face value as it is conditional on the data set due to the model-building stage. Unfortunately, this fact often gets neglected in practice.
Answer: The 'rule of thumb' that the standard deviation $S$ of a normal sample can be usefully approximated as sample range $D$
divided by $4$ (or $5$ or $6).$
The rule is typically "illustrated" by an example, contrived
so the 'rule' gives a reasonable answer. In fact, the appropriate divisor
depends crucially on sample size $n.$
<code>n=100
set.seed(2020)
s = replicate(10^5, sd(rnorm(n)))
set.seed(2020)  # same samples again
d = replicate(10^5, diff(range(rnorm(n))))
mean(d/s)
[1] 5.029495
summary(d/s)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  3.581   4.678   4.984   5.029   5.330   7.756
</code>
For, $n = 25,$ dividing the range by $4$ works pretty well,
and without great variation. For $n = 100$ and $500,$ respective
denominators are on average $5$ and $6,$ but with widely decreasing precision for individual samples
as sample size increases. A simulation in R for $n=100$ is shown above.
Note: The idea of approximating $S$ as $D/c_n$ is not completely useless: For $n < 15,$ dividing the range by some constant $c_n$ (different for each $n)$
works well enough that makers of control charts often use range divided by
the appropriate constant to get $S$ for chart boundaries.
Comment: (+1) Even worse is the adoption of the premise that you know the sample is from a normal distribution!  Even a slight alteration in the kurtosis can blow out the extreme values so that the sample range is very large indeed!  Unless there is an extremely good theoretic reason to believe a sample comes from a normal distribution, using the extreme points for an estimator, on the assumption of a normal distribution is playing with fire!
Answer: My favorite stats malpractice: permuting features instead of samples in a permutation test. In genomics, it's common to get a big list of differentially expressed, or differentially methylated, or differentially accessible genes (or similar). Often this is full of unfamiliar items, because nobody knows the literature on all 30k human genes, let alone transcript variants or non-coding regions. So, it's common to interpret these lists by using tools like Enrichr to test for overlap with databases of biological systems or previous experiments.
Most such analyses yield p-values assuming that features (genes or transcripts) are exchangeable under some null hypothesis. This null hypothesis is much more restrictive than it seems at first, and I've never seen a case where it's a) biologically realistic or b) defended by any sort of diagnostic.
(Fortunately, there are tools that don't make this mistake. Look up MAST or CAMERA.)
Answer: Calling type I assertion probability the "type I error rate" when it is neither a rate nor the probability of making an error.  It is the probability of making an assertion of an effect when there is no effect.
Calling type I assertion probability the "false positive rate" when it is not the probability of a false positive result.  It is the probability of making an assertion of an effect when any assertion of an effect is by definition wrong.  The probability of a false + result is the probability that an effect is not there given the evidence was + for such a finding.  The is a Bayesian posterior probability, not $\alpha$.
Thinking that controlling $\alpha$ has to do with limiting decision errors.
Comment: "Making an assertion of an effect when there is no effect" sounds like making an error. Could you please clarify?
Comment: But an alarm when there is no fire is, quite literally, a false alarm, isn't it?
Comment: Sure, you care about P(no fire | alarm went off) if you're woken up by a blaring alarm, but if you're Honeywell designing the smoke detector to a particular sensitivity, wouldn't your concern be the frequency with which the alarm goes off even though there is no fire (and the frequency with which the alarm fails to go off when there is a fire)?
Comment: Making an error implies that a mistake is being made.  The probability of making a mistake is the probability that an effect is not present when you assert that it is present.   This is just one minus the Bayesian posterior probability that the effect is present given the data.  Think of a smoke alarm.  We want P(fire | alarm) to be high and P(no fire | no alarm) to be high.  Type I probability would be P(alarm | no fire) which doesn't help us very much.
Comment: Yes but it's not the mistake or probability that you care about.  You want to know P(alarm mistaken) = P(mistake | alarm) = P(no fire | alarm), not P(alarm | no fire).
Comment: No, this is what you want: have the alarm sound if P(fire | air properties) > 0.02 while you are home or P(fire | air properties) > 0.01 while you are away.  Substitute  for 0.01 and 0.02 any values that reflect your utility function.
Comment: This looks like an argument for why type I error rate shouldn't be cared about as much as it currently is cared about, and that other things should be cared about more. Which is fine. But it is not the same as arguing that type I error rate is not an error and/or not a rate.
Comment: What about its definition makes you use the word error?  Be specific.  And it's not a rate (first derivative; rate of change).  Analogy to type I assertion probability: If I told someone that everything they say is false and they will be judged by whether they speak less than 1/20th of the time.
Answer:
I feel like very basic statistics is not as intuitive as basic school physics. Or maybe there is a much more intuitive base, but I haven't come to know it.

Statistics tells us if there is a correlation, not the mechanisms of causation. And correlation does not imply causation. To tell "why" two phenomena are connected, one has no other way than to find the causation. However, sometimes in classroom lectures or seminars etc., the importance of statistics is described in such a way that leaves a false impression that statistics is used to determine causal relation.

Misuse of statistics happen (intentionally or unintentionally) because statistics gives the place to do so. When things are lengthy, complicated; and the intuitive basis behind those rigorous treatments are not understood; there might be scopes for conceptual fallacies or conceptual mistakes.

A little learning is dangerous, especially when it comes to statistical terms; because statistical terms and graphs could be deliberately misused to establish a "damn lie" into apparent truth.
Comment: #4 is nonsense often repeated by individuals who conflate the human ability to deceive with some special property of the language of statistics. You can lie with statistics, just as you can lie with *any* language.
Comment: The first part of #4 (that a little learning is dangerous) is true.
Comment: From the OP: *To allow efficient voting on these, please give only one bad principle per answer, but feel free to give multiple answers.* Also, hardly any of the points actually is a bad statistical idea/practice.
Answer: Doing Proportional Odds Logistic Regression.
Ordinary logistic regression produces correct class probabilities only if the two classes are normally distributed, with a same variance. It is already uncommon enough to check for that.
However, in proportional odds, this condition cannot be satisfied, ever. If the classes $A$ and $BC$ happen to have equal variances, then classes $AB$ and $C$ cannot have them (except in a pathological case where they fully overlap).
Comment: You are confusing the PO model with something else.  The PO model has nothing to do with any of that and **definitely** does not assume normality.


Programming a reset button?

Question: I'm currently making a mortgage calculator, but I need some help. I have a reset button on my GUI that makes all of the forms blank again after typing something into them. The IDE already helped me make the button, so here is where I'm at:
private void resetActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

What do I need to put in here?
Comment: Can you reference all of the form fields? If so, how do you think you should approach it?
Comment: Probably your code to reset the form. Note This is not a site to write code for you, include what you have tried and why it didn't work
Answer: You either recreate your complete GUI (probably not an option), or painstakingly use .setText("") against each and every input field you have, and similar logic for radio buttons, etc. There's no royal way to it, unfortunately.

Programming a reset button?


Truncar valor inteiro PHP

Question: Preciso chegar no seguinte resultado:
4,2 = 5
85,02 = 9
256,9 = 3...

Por enquanto, usei o código:
$novoservico = '402,02';
$novoservico = str_replace(",",".",$novoservico);
$valor_redondo = ceil($novoservico);
echo $valor_redondo; ?>

Com esse código, eu consigo arredondar os números sempre pra cima:
4,2 = 5
85,02 = 86
256,9 = 257...

No caso, eu preciso fazer com que esses números sejam "truncados pra cima". Não sei se fui muito claro usando essa expressão. Mas foi a melhor maneira de explicar o que eu preciso fazer.
Agradeço desde já. sobre qualquer observação ou duvida sobre a pergunta, estou a disposição.
Comment: O resultado que você obteve é exatamente o resultado que você descreveu que quer obter, então a pergunta não fez sentido.
Comment: @RaulGermano e todos estão tentando te ajudar, se entendeu errado, não é culpa nossa. Sua pergunta não fez sentido, tanto que **todos** os que leram ficaram em dúvida. Se você é usuário ou desenvolvedor, iniciante ou avançado, pouco importa, mas a sua pergunta não está clara e demanda mais detalhes. Você foi questionado sobre o que quer fazer e não respondeu, então como quer ser ajudado assim? Na pergunta você diz que precisa de arredondamento para o inteiro acima e seu código faz **exatamente** isso. Se quer algo diferente, edite ([edit]) sua pergunta e descreva melhor o problema.
Comment: 85,02 = 9? Isso não é arredondamento.
Comment: Isso faz menos sentido ainda. Votei para fechar como não clara até ter mais informações.
Comment: Então recomeçando, voltamos a pergunta: você precisa que o resultado seja **sempre** apenas um dígito, independente da grandeza da entrada? Se eu entrar com 10000000, deve retornar 1, enquanto eu entrar com 10000001 deve retornar 2?
Comment: Só para ficar claro [isto não é um forum](https://pt.meta.stackoverflow.com/questions/2068/o-stack-overflow-em-portugu%C3%AAs-%C3%A9-um-f%C3%B3rum) e todo o mundo está tentando ajudar. "Tenho certeza que vocês entenderam o que eu quis dizer" - Certamente que não, e vê isso pela quantidade de perguntas feitas no comentários (eu próprio não percebi bem o resultado que você procura exatamente). O que pode ser evidente para si que está dentro do contexto, nem sempre é para outros que não estão no mesmo contexto.
Comment: @AndersonCarlosWoss ele disse querer 85 virar 9, imagino que ele queira apenas números inteiros de 1 dígito. Mas não ficou claro
Comment: Eu sou um USUÁRIO tentando programar. Vocês deviam ter um senso critico um pouco mais apurado.
Tenho certeza que vocês entenderam o que eu quis dizer. Custa tentar me ajudar? Isso aqui é um fórum voltado pra iniciantes e profissionais.
Eu estou começando no Stack Overflow. Ser "recebido" dessa forma não é nada agradável.
Eu agradeço pela ajuda Wees.
Eu não quero ser chato, só fique chateado com os comentários. Acho que um fórum serve pra ajudar
Comment: @DavidAlves tem razão, o sistema arredonda para o inteiro mais proximo
Comment: "porém ele só arredonda números após a virgula" - Esse é o conceito de arredondamento.
Comment: Vamos recomeçar. Acabei de editar
Answer: Se vc quer um número de 1 digito apenas, pode fazer assim:
$novoservico = '402,02';
$valor_redondo = $novoservico[0]+1;
echo $valor_redondo;

Ele vai imprimir sempre o próximo número, mas se for int realmente:
$valor_redondo = intval($novoservico[0]+1);

Comment: Sim. Porém ele irá subir um. Se eu por 100 ele vai pra 2, em vez de converter pra 1
Comment: se for 100 fica o 1 e se for 9?

Truncar valor inteiro PHP


How can I add an object to a form?

Question: How can I add an object to a form array to make it available to hook_form_alter() implementations?
I have an object I pass to a form, which may have the new property. I would like to implement hook_form_alter() in another module to add/change form items based on that property.
There is no need for the item to be available after submission. I would like to avoid the overhead of using a value form element.
Answer: You don't have to add the entire object to the $form array: You can just add the property you need to share with the hook_form_alter() implementations, for example with the following code.
$form['#mymodule_new'] = $object->new;

You don't have to worry about adding overhead because the values submitted in a form are transient by design, if they are not stored in the database.
As additional note, $form['#mymodule_new'] is available to form validation and submission handlers. The array key should not be already used by other Drupal modules, including Drupal core modules, to avoid conflicts.

How can I add an object to a form?


Migrating Exchange 2007 Users to Exchange 2013

Question: In our company up until now, we've had an on-site Exchange 2007 installation. For the purposes of this question, we have 3 servers :

Exchange07MBX01 (Mailbox, Hub Transport)
Exchange07MBX02 (Client Access)
Exchange07CAS01 (Client Access, Hub Transport)

Currently, all Outlook clients point to Exchange07MBX01, with HTTP proxy enabled pointing to webmail.mycompany.com.
Over the last couple of days, I've installed Exchange 2013 on different VMs. I've updated everything, so the two are successfully co-existing at the moment. The 2013 servers are :

Exchange13MBX01 (Mailbox)
Exchange13MBX02 (Mailbox)
Exchange13CAS01 (Client Access)
Exchange13CAS02 (Client Access)

I also setup a hardware load balancer between the two CAS servers, call it Exchange13LoadBalancer. I've also setup the external urls for all my Virtual Directories to be the same as the Exchange 2007 machines, webmail.mycompany.com.
I've successfully moved my own mailbox to the 2k13 servers, by using the Migrate Batch function. I can browse to OWA and access my mailbox.
At the end of the migration, Outlook popped up a message saying that "The Exchange Administrator has made a change requiring you to restart Outlook", which I did. However, no changes were applied. I'm assuming that this change would then point my Outlook Client to one of the new client access servers (my Outlook client still pointed to ExchangeMBX01, with the HTTP proxy pointing to webmail.mycompany.com).
I then took another user, started their migration, added two entries in the host file for :

webmail.mycompany.com -> Exchange13LoadBalancer
autodiscover.mycompany.com -> Exchange13LoadBalancer

When the migration completed, and asked this user to restart Outlook, still no changes were applied. Once again, when I manually changed it on his computer, it worked fine.
Onto my question... Is there an automatic way (i.e. AD policy/DNS setting/Voodoo) of changing this? Is this the proper way to migrate users to Exchange 2013? I can't change the DNS record for webmail.mycompany.com to point to the new Exchange servers, as their mailboxes are still on the Exchange 2007 servers... or can I?
What is the best way to move their mailboxes, while not requiring me to go to each user's computer and create a host file/change the mail account to point to Exchange2013LoadBalancer/delete the account and make a new account pointing to the new server?
Answer: Exchange 2013 CAS can proxy/redirect access to your 2007 mailboxes. You don't want the ExternalURL to be the same on CAS servers for both versions though. Your Exchange 2007 servers ExternalURL should be legacy.mycompany.com, and the 2013 CAS servers can continue to use webmail.mycompany.com.
You want to migrate CAS/transport to your new servers first, which will proxy/redirect access to your old mailbox servers. Once you verify that you can access mailboxes residing on the new and old environment and the new environment is handling bidirectional mail flow, you can cut over DNS. Then you can move mailboxes until you've cleared out the 2007 environment, at your leisure.
While I haven't yet done a complex 2007 to 2013 migration, I have done 2007 to 2010 and 2010/2010 site migrations. The following document should give you some helpful guidance around coexistence and how to properly configure it: http://technet.microsoft.com/en-us/library/bb310763%28v=exchg.141%29.aspx
Please let me know if any specific configuration questions come up.
Comment: In our (inherited) environment, HTTP Proxy is enabled for all Outlook clients. This points to webmail.mycompany.com. If I change the ExternalUrl of the 2007 machines to legacy.mycompany.com, and make the 2013 servers' ExternalUrl webmail.mycompany.com (at the moment they are both webmail.mycompany.com), will the users with 2007 mailboxes still be able to get their mail? Is that what the proxy does pretty much?
Comment: You have to have an InternalURL set on the old CAS servers that is reachable internally by the 2013 CAS servers. This will allow the 2013 servers to proxy connections to 2007 mailboxes. Having legacy.mycompany.com as your 2007 ExternalURL will allow redirecting to work. Proxying and redirecting happen in different cases depending on the location of the user, the location of the Exchange servers relative to each other, and the client access method being used.


Modulo and Congruence

Question: Little Fermats theorem states that
If $n$ is a prime number then $a^n \equiv a \mod{n}$
Equivalently
If $n$ is a prime number and $a$ is not divisible by $n$ then
$a^{n-1} \equiv 1 \mod{n}$
My doubt is
For any natural number $n$ if its correct that
$a^n \equiv a \mod{n}$
Then when i can also write it as
$a^{n-1} \equiv 1\mod{n}$
And when i cant write ?
Thanks in advance ........... :)
Answer: If $a$ is not divisible by $p$, you can write $a^{n-1} \equiv 1 \pmod n$, just by dividing both sides by $a$.
If $a$ was divisible by $p$ then $a \pmod p$ would be $0$.
Comment: Fermat's theorem states that $3^{560} \equiv 1 \pmod{561}$, not $3 \pmod{561}$
Comment: Consider this case :

$3^{561} \equiv 3 \mod{561}$ but $3^{560} \not\equiv 3 \mod{561}$
Comment: im sry , i mean its false that $3^{560} \not\equiv 1 mod (561)$
Comment: Ignore my previous comment, it turns out $561$ isn't a prime so Fermat's Little Theorem does not apply.
Comment: Yeah . my doubt is when we can cancel a on both sides for any number $n$

Modulo and Congruence


What would be a good/ ideal/ optimum method of self-learning piano?

Question: I started learning piano after I turned 50. It's been less than two years now. In between, my daughter went to college in US, I lost my parents to cancer in July 2017 and August 2018, and moved across the large country of India (from Mumbai to Kolkata). In spite of all these obstacles, my heart is still with those magical black and white keys. However, my learning has been stunted because of all of these.
But the bigger challenge has been to find a good tutor, meeting my knowledge & interest in various genres, age, pace of learning, location (home or class) etc. Piano is not an Indian instrument. Nor is western classical or jazz/ blues as popular in India as they are in China/ Japan/ SE Asia. This is because, India has a well developed and venerated classical music genre, and a popular music oeuvre based on that, and thus music tutors and academies in Indian music of various quality and cost are widely available. But not for piano. Thus it's been difficult for me to find a good Piano tutor, who will come home, spend adequate time, pay attention, share my interest in music, and provide the lessons / guidance accordingly.
On the other hand, the Web has made access to knowledge and instructions much easy. I have a feeling that judiciously chosen, between instructional youtube videos, books, and perhaps a learning app, one can take on the learning journey.
However, I am not very sure about exactly the path to take. About what to learn when, how to progress, how to get feedback, when to branch out in a genre (classical/jazz/popular) etc. (I know a fair bit of theory and can call myself a late beginner in playing).
So, I ask, what would be a good/ ideal/ optimum method of self-learning piano, given all the internet resources available?
Comment: Side note, I live in America, and can't find a sarangi teacher at all. So finding teachers of instruments that are not popular in our regions seems to be a world-wide problem. I never knew that piano was not popular in India.
Answer: Skype (or similar) lessons with a flesh and blood music teacher.  Though you'll probably miss out on some of the benefits that having someone literally look over your shoulder to detect and correct problems, the best route is still to hook up with a personal teacher.
Answer: There are various aspects of piano playing you need to be familiar with. As a beginner, start with focussing on your technique. Watch YouTube videos about hand and finger position for piano playing. Your wrist has to be loose and fingertips firm but relaxed. Start by doing simple exercises to train your fingers to move evenly and steadily. Try the finger exercises by Hanon.
Once your technique is in place, consider learning how to read notes. Get hold of a sight-reading book for beginners. You have to be very patient because it will take time and daily practice to become agile with your reading.
I would not be tempted to learn pieces using Synthesia. While you may learn a song fast, you won't learn any theory or notation.
Answer: It depends on the sound and skills you want to achieve. I wanted to play any song by ear.
I'll give you my practice:
I don't like meeting up with teachers. The only theory I get is from youtube and this site. I play well known songs by ear like anthems, pop songs, folk songs, rock songs, christmas songs and I play them in all keys. I like to see the piano as an extension of whistling/humming. I do this more often than practicing scales (altho I still practice scales) but I find that if you just practice scales you limit yourself to the sound of minor second and major second intervals whereas in actual songs you have a much more random range of intervals. And because the piano is uneven, by doing the same song in different keys you'll figure out the sound of the same interval but in different combinations on the keyboard.
What you're really trying to do is build muscle memory where you know the sound of every single interval. The more I do this (and I've been doing this now for roughly 2 years), the less mistakes I make to the point where I can play a new fairly basic song in any key. Any song that I can think of. Well except maybe a really hard song by Chopin or Liszt, but any song off the radio.
So my homework for you: take an easy song and try to play it by ear. Start with songs in a major key. So Mary had a little lamb in C major for example. Just play the melody. Now play it in D major. Now in all keys. Now go back and add harmony (chords) to it with your left hand (this would require you to know some theory like diatonic chords. start with I,IV,V. then add the other chords ii,iii,vi for more complicated songs) work your way up to songs -and these are just examples- like Happy Birthday, My Country Tis of Thee, Greensleeves (this is in a minor key), Scarborough Fair (Dorian mode) or anything you like off the radio. On top of your piano just have a list of songs you'd like to play. But do not look at sheet music. Just play them by ear and with some theory of chords and scales.
However, my method would not work for someone trying to work in an orchestra, or trying to attend academia, where reading sheet music is required. So as mentioned, really define what you want ahead of time.


Troca de tag com javascript

Question: Quero fazer a tag p ser substituída pela img no hover, já trazendo uma imagem que tenho no diretório. É possível fazer ou tem como fazer algo parecido? Se possível, na mesma função.
Código:

$(function(){
  $(".produto").hover(function(){
    $(this).toggleClass('produtocomprar produto');
  });
});
.produto {
  position: relative;
  width: 190px;
  height: 342px;
  margin-left: 40px;
  margin-top: 20px;
  float: left;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
}

.produtocomprar {
    position: relative;
    width: 190px;
    height: 340px;
    margin-left: 40px;
    margin-top: 20px;
    background: #f6f6f6;
    float: left;
    display: flex;
    flex-direction: column;
    border-radius: 5px;
    border: dotted 1px;
    box-shadow: 1px rgba(0, 0, 0, 0.5);
}

Hidratante Andiroba Linha Amazônica

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac
accumsan erat.

De: R$ 150,00

Por: R$ 80,00

    + Detalhes

Answer: André, Você precisa adicionar a tag  com a sua imagem e assim manipular ela com a sua função jquery. Segue um exemplo.

$(function() {
  $(".produto").hover(function() {
   $(".produto-detalhes").toggleClass("pdroduto-hidden");
   $(".produto-imagem").toggleClass("produto-imagem-show");
  });
});
.produto {
  position: relative;
  width: 190px;
  height: 342px;
  margin-left: 40px;
  margin-top: 20px;
  float: left;
  display: flex;
  border: dotted 1px rgba(0,0,0,0);
  flex-direction: column;
  background-color: #ffffff;
}

.produto:hover {
  background: #f6f6f6;
  border-radius: 5px;
  border: dotted 1px;
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.5);
}

.produto-imagem {
  display: none;
  transition:0.3s;
}

.produto-imagem-show {
  display: block;
}

.pdroduto-hidden {
  display: none;
}

Hidratante Andiroba Linha Amazônica

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac accumsan erat.

De: R$ 150,00

Por: R$ 80,00

    + Detalhes

Comment: Perfeito cara, muito obrigado!
Answer: Não precisa de javascript, pode fazer com css, esconda a imagem, e no hover da div pai mostre um e esconda o outro:

.produtodesc img {
  display: none;
}
.produtodesc:hover p {
  display: none;
}
.produtodesc:hover img {
  display: block;
}
.produto {
  position: relative;
  width: 190px;
  height: 342px;
  margin-left: 40px;
  margin-top: 20px;
  float: left;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
}

.produtocomprar {
    position: relative;
    width: 190px;
    height: 340px;
    margin-left: 40px;
    margin-top: 20px;
    background: #f6f6f6;
    float: left;
    display: flex;
    flex-direction: column;
    border-radius: 5px;
    border: dotted 1px;
    box-shadow: 1px rgba(0, 0, 0, 0.5);
}

Hidratante Andiroba Linha Amazônica

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac
accumsan erat.

De: R$ 150,00

Por: R$ 80,00

    + Detalhes

Comment: Obrigado Guilherme. Eu sei como fazer apenas com css, gostaria de saber com javascript pq to começando a estudar a linguagem

Troca de tag com javascript


Font Size Fluctuation and Inconsistency

Question: I am currently working on a ST2 powered web-app and experiencing something odd with the consistency of font-size across the entire app. Initially I thought it might be due to a font-size attribute I was setting in the custom SASS file, but when I strip all "font-size" properties from my SASS file I still see fonts rendering inconsistently.
We are pushing views from multiple "root" views, but with no font-size property set I would expect all fonts to render the same size. Am I missing something? Please note I am not talking about font-size across multiple devices...this is font-size in general for the app itself.
Check out the attached images and the path taken to arrive each view. They are the exact same view with same components - the only difference is the path in which the user has taken to arrive there. Keep in mind I have removed ALL custom font attributes, so it is purely referencing Sencha's styles at this point (have tested on Chrome, iOS emulator, and iPhone running app locally).
User Path: Dashboard View (Root View) > Team Profile

User Path: Dashboard View (Root View) > Programs View (Root View) > Team Profile

Notice how the second "Team Profile" view has a larger font size? With no font's set for the entire app I would expect it to be the same regardless of how you arrive at the view. Can someone please explain to me what might be going on here?
Thanks in advance!
Comment: Have you tried running it in a browser like chrome and using dev tools to inspect the element? You should be able to track down the rogue CSS property and whether it was created by your application or not
Comment: Yeah, I have scoured the DOM trying to figure out what might be causing the issue. There are zero font attribute values set by myself and only a few in the core Sencha files. I am almost certain at this point, it has something to do with the way views are being pushed in the Sencha architecture itself.
Comment: I have the same issue. Only mine is larger on the first view, and smaller on the second view, and subsequent views.
Answer: I found the issue for me was not including styleHtmlContent: true in the config of the view with the larger font. If you don't have that option set in the view, add it and see if it makes a difference.

Font Size Fluctuation and Inconsistency


Sum of squares of binomial coefficient with slight modification

Question: I know, These type of questions have been asked many times and infact, this question is very much similar to my question.
Let $ C_r$ denote ${}^nC_r$ (alternatively ${ n \choose k}$ )
Then for an even natural $n$ the value of  $$ S= 2\frac{\left( \frac{n}{2} \right)! \left( \frac{n}{2} \right)! }{n!}[ (C_0)^2 -2(C_1)^2 + 3(C_2)^2 +\cdots + (-1)^n(n+1)(C_n)^2 ]$$
I did this by the "classic" way.
Consider the expansion $$(1+x)^n=\displaystyle \sum_{r=0}^{n}C_rx^r \tag 1$$
Multiply both sides by $x$ and then differentiate w.r.t.
$x$ $$(1+x)^n+nx(1+x)^{n-1}=\displaystyle \sum_{r=0}^{n}(r+1)C_rx^r$$
Now multiply the corresponding sides of this equation and  $(1)$ (after substituting $x \rightarrow -x$) to get,
$$(1-x^2)^n+nx(1-x)(1-x^2)^{n-1} = [C_0+2C_1x+3C_2x^2+\cdots+(n+1)C_nx^n]\times[C_0-C_1x+C_2x^2-\cdots+(-1)^nC_nx^n]$$
On RHS, this $[(C_0)^2 -2(C_1)^2 + 3(C_2)^2 +\cdots + (-1)^n(n+1)(C_n)^2]$ thing is the coefficient of $x^n$.
Hence, on comparing the coefficient of $x^n$ on RHS, we get
$$(-1)^{\frac{n}{2}} {}^nC_{\frac{n}{2}} -n\cdot  (-1)^{\left(\frac{n-2}{2}\right)}{}^{n-1}C_{\frac{n-2}{2}}$$
Which on simplifying comes out to $(-1)^{\frac{n}{2}}(n+2)\frac{n!}{2 \left( \frac{n}{2} \right)! \left( \frac{n}{2} \right)! }$
Thus, $S= (-1)^{\frac{n}{2}}(n+2)$
Answer: I would let $n=2m$ and rewrite the identity as
$$\frac2{\binom{2m}m}\sum_{k=0}^{2m}(-1)^k(k+1)\binom{2m}k^2=(-1)^m(2m+2)\;,$$
which can immediately be rewritten as
$$\sum_{k=0}^{2m}(-1)^k(k+1)\binom{2m}k^2=(-1)^m(m+1)\binom{2m}m\;.\tag{1}$$
Now
$$\begin{align*}
\sum_{k=0}^{2m}(-1)^k(k+1)\binom{2m}k^2&=\sum_{k=0}^{m-1}(-1)^k(k+1)\binom{2m}k^2+(-1)^m(m+1)\binom{2m}m^2\\
&\quad+\sum_{k=m+1}^{2m}(-1)^k(k+1)\binom{2m}k^2\\
&=\sum_{k=0}^{m-1}(-1)^k(k+1)\binom{2m}k^2+(-1)^m(m+1)\binom{2m}m^2\\
&\quad+\sum_{k=0}^{m-1}(-1)^{2m-k}(2m+1-k)\binom{2m}k^2\\
&=\sum_{k=0}^{m-1}(-1)^k(k+1)\binom{2m}k^2+(-1)^m(m+1)\binom{2m}m^2\\
&\quad+\sum_{k=0}^{m-1}(-1)^k(2m+1-k)\binom{2m}k^2\\
&=2(m+1)\sum_{k=0}^{m-1}(-1)^k\binom{2m}k^2+(-1)^m(m+1)\binom{2m}m^2\\
&=(m+1)\sum_{k=0}^{2m}(-1)^k\binom{2m}k^2\;,
\end{align*}$$
so that $(1)$ reduces to
$$\sum_{k=0}^{2m}(-1)^k\binom{2m}k^2=(-1)^m\binom{2m}m\;.\tag{2}$$
(Up to here this is really just a slightly different version of user675453's argument that happens to be the way that I saw it.)
$(2)$ is moderately well-known but far from obvious (and not an identity in my ready armamentarium!); it can be proved with a nice combinatorial argument that I think I learned from Marc van Leeuwen. Suppose that you have $2m$ blue balls numbered $1$ through $2m$ and $2m$ red balls, also numbered $1$ through $2m$. A pair is a red and a blue ball with the same number. The lefthand side of $(2)$ counts the ways to choose a set containing equal numbers of red and blue balls, counting the set with a factor of $-1$ if the number of each color is odd.
I claim that the subsets that do not contain exactly one member of each pair cancel out in this counting. Suppose that $B$ is such a subset; then there is a smallest $\ell\in[2m]$ such that $B$ either contains neither ball numbered $\ell$ or contains both balls numbered $\ell$. If it contains neither of those balls, add them to $B$ to get a new subset $\hat B$, and if it contains both of them, remove them to get $\hat B$. In either case $\hat B$ still has the same number of red and blue balls, but that number has changed parity, so $B$ and $\hat B$ are counted with opposite signs. Finally, $\hat{\hat B}=B$, so we have indeed shown shown that the subsets that do not contain exactly one member can be matched up to cancel out in the count.
How many subsets contain exactly one member of each pair? They are subsets of size $2m$ in which the $m$ blue balls have precisely the $m$ numbers that are not on the $m$ red balls. Thus, each of these subsets is completely determined by the set of $m$ numbers on the red balls, and there are therefore $\binom{2m}m$ of them. Each of them is counted positively if $m$ is even and negatively if $m$ is odd, so the total count must be $(-1)^m\binom{2m}m$, as desired.
Answer: However, this problem can more neatly solved by the fact : $$ {n \choose k} = {n \choose n-k}$$
$$S=2\frac{\left( \frac{n}{2} \right)! \left( \frac{n}{2} \right)! }{n!}[ (C_0)^2 -2(C_1)^2 + 3(C_2)^2
+\cdots + (-1)^n(n+1)(C_n)^2 ] \tag 1$$
$$S= 2\frac{\left( \frac{n}{2} \right)! \left( \frac{n}{2} \right)! }{n!}[(C_n)^2-2(C_{n-1})^2+3(C_{n-2})^2-\cdots-n(C_1)^2+(n+1)(C_0)^2] \tag 2$$
Adding $(1)$ and $(2)$
$$2S=2\frac{\left( \frac{n}{2} \right)! \left( \frac{n}{2} \right)! }{n!}(n+2)[(C_0)^2-(C_1)^2+\cdots+(C_n)^2]$$
And Finally, $ S=(-1)^{\frac{n}{2}}(n+2)$
(Since n is even, $\displaystyle \sum_{r=0}^{n}(-1)^r(^nC_r)^2=(-1)^{\frac{n}{2}}{}^nC_{\frac{n}{2}}$)


projectRaster: Raster projection of bathymetry data ("NOAA.nc') in the pacific – worldmap with marmap in the pacific

Question: I would like to reproduce the last example from the marmap vignette: 'marmap-DataAnalysis' for a pacific region. The example shows the orthographic projection of the world centered at lon = 50. Here is the example:
library(marmap)
library(raster)
# Get data for the whole world. Careful: ca. 21 Mo!
world <- getNOAA.bathy(-180, 180, -90, 90, res = 15, keep = TRUE)

# Switch to raster
world.ras <- marmap::as.raster(world)

# Set the projection and project
my.proj <-   "+proj=ortho +lat_0=0 +lon_0=50 +x_0=0 +y_0=0"
world.ras.proj <- projectRaster(world.ras,crs = my.proj)

# Switch back to a bathy object
world.proj <- as.bathy(world.ras.proj)

# Set colors for oceans and land masses
blues <- c("lightsteelblue4", "lightsteelblue3",
           "lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))

# And plot!
plot(world.proj, image = TRUE, land = TRUE, lwd = 0.05,
     bpal = list(c(0, max(world.proj, na.rm = T), greys),
                 c(min(world.proj, na.rm = T), 0, blues)),
     axes = FALSE, xlab = "", ylab = "")
plot(world.proj, n = 1, lwd = 0.4, add = TRUE)

However, I would like to change the central to a pacific meridian, e.g. lon = 155.5. I tried this by changing the projection parameters to,
my.proj <- "+proj=ortho +lat_0=20 +lon_0=155.5 +x_0=0 +y_0=0"

but then,
world.ras.proj <- projectRaster(world.ras,crs = my.proj)

results in:
Error in if (nr != x@nrows | nc != x@ncols) { :
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In rgdal::rawTransform(projfrom, projto, nrow(xy), xy[, 1],     xy[,  :
  259 projected point(s) not finite
2: In rgdal::rawTransform(projection(raster), crs, nrow(xy), xy[,     1],  :
  4 projected point(s) not finite

How can could I plot the 'bathymetric world' in a pacific region?
Answer: I have simplified your question (always good, and for me  the data download did not work). In essence:
library(raster); library(rgdal)
prj1 <- "+proj=ortho +lat_0=0 +lon_0=0 +x_0=0 +y_0=0"
prj2 <- "+proj=ortho +lat_0=20 +lon_0=155.5 +x_0=0 +y_0=0"
r <- raster()
r <- init(r, 'col')

# works
x1 <- projectRaster(r, crs = prj1)
# fails
x2 <- projectRaster(r, crs = prj2)

This is a bug. I have fixed it in raster version 2.6-2 (under development, should be available next week or so)
Comment: Thank you. Looking forward to the update. Any more details on this bug? Is it related to the type of projection (+proj=ortho)?
Comment: The problem was with projection across the date-line
Answer: This can be solved in marmap with the current/previous version of the raster package. You have to use the antimeridian=TRUE argument of the getNOAA.bathy() function and some trickery to allow the computations of the projection by the raster package.
The first trick is to download data with lon1 = lon2 = 0 since the antimeridian downloads 2 distinct datasets: from the antimeridian to lon1 and from lon2 to the antimeridian. Setting lon1 and lon2 equal to 0 downloads the whole world.
Then, you have to manually switch back to values of longitudes between -180 and 180 (and not 0 to 360 as produced by the animeridian argument of getNOAA.bathy()), hence the rownames(world2) <- ... line.
Finally, you have to apply the same -180 correction to specify the projection.
Here is the code:
library(marmap)
library(raster)
# Get data for the whole world. Careful: ca. 21 Mo!
world2 <- getNOAA.bathy(0, 0, -90, 90, res = 15, keep = TRUE, antimeridian=TRUE)
rownames(world2) <- as.numeric(rownames(world2))-180

# Switch to raster
world.ras <- marmap::as.raster(world2)

# Set the projection and project
my.proj <-   "+proj=ortho +lat_0=20 +lon_0=155-180 +x_0=0 +y_0=0"
world.ras.proj <- projectRaster(world.ras,crs = my.proj)

# Switch back to a bathy object
world.proj <- as.bathy(world.ras.proj)

# Set colors for oceans and land masses
blues <- c("lightsteelblue4", "lightsteelblue3",
           "lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))

# And plot!
plot(world.proj, image = TRUE, land = TRUE, lwd = 0.05,
     bpal = list(c(0, max(world.proj, na.rm = T), greys),
                 c(min(world.proj, na.rm = T), 0, blues)),
     axes = FALSE, xlab = "", ylab = "")
plot(world.proj, n = 1, lwd = 0.4, add = TRUE)

And here is the result:

The new version of raster (2.6-7) solves the problem of projecting across the date-line. However, due to rounding errors when downloading bathymetric data from NOAA servers, some missing cells may appear in plots. Here is an example with the code you posted in your original question:

And here is the summary() of the data:
summary(world)
# Bathymetric data of class 'bathy', with 1440 rows and 720 columns
# Latitudinal range: -89.88 to 89.88 (89.88 S to 89.88 N)
# Longitudinal range: -179.88 to 179.88 (179.88 W to 179.88 E)
# Cell size: 15 minute(s)

# Depth statistics:
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
#  -10635   -4286   -2455   -1892     214    6798
#
# First 5 columns and rows of the bathymetric matrix:
#          -89.875 -89.625 -89.375 -89.125 -88.875
# -179.875    2746    2836    2893    2959    3016
# -179.625    2746    2835    2892    2958    3015
# -179.375    2746    2835    2891    2957    3014
# -179.125    2746    2834    2890    2956    3013
# -178.875    2746    2834    2889    2955    3012

Hence, the solution using antimeridian=TRUE detailed above should be best.


Accessing data on Drupal with external application

Question: I'm developing a native iOS application for a small company. The company has a career website on which they publish job offers. The contents such as job descriptions and contact person information are maintained with Drupal. Is there a way to get the plain data of the contents from an iOS application? I never used Drupal before, please help me.
Thanks a lot in advance!
Answer: Yes, you can use module Views to create content listings (http://drupal.org/project/views) with Services (https://drupal.org/project/services) and combine them to web services with the content listings using Services Views module (https://drupal.org/project/services_views).
Also, look at Drupal iOS SDK (https://github.com/kylebrowning/drupal-ios-sdk) for some basic already implemented connectors from ios to drupal. (Retrieving specific single user/piece of content, retrieving already mentioned views etc...)
I would start with downloading and enabling the modules, understanding views (https://drupal.org/node/1911062), then read the documentation for services (contained in the module)
Comment: Is it also possible to access the database directly with SQL queries?
Comment: Accessing DB directly would give you a headache, all the tables are normalized so you would have to do mysql joins a lot. The Services module allows you to simply configure all this without writing a single line of code. I updated the answer. If you find it helpful, please accept it.
Comment: I have one more question. Using the techniques you described above, can I retrieve only the HTML of a site or also the values for each field (e.g. author, date of post, title, body etc.)?
Comment: You can retrieve whatever you need. IMO, the most convenient way in such situation is to create json service with some specific node fields.