What are "instantaneous" rates of change, really?

Question: Here's how I see it (please read the following if you can, because I address a lot of arguments people have already made):
Let's take instantaneous speed, for example. If it's truly instantaneous, then there is no change in $x$ (time), since there's no time interval.
Thus, in $\frac{f(x+h) - f(x)}{h}$,  $h$ should actually be zero (not arbitrarily close to zero, since that would still be an interval) and therefore instantaneous speed is undefined.
If "instantaneous" is just a figure of speech for "very very very small", then I have two problems with it:
Firstly,  well it's not instantaneous at all in the sense of "at a single moment".
Secondly, how is "very very very small" conceptually different from "small"? What's really the difference between considering $1$ second and $10^{-200}$ of a second?
I've heard some people talk about "infinitely small" quantities. This doesn't make any sense to me. In this case, what's the process by which a number goes from "not infinitely small" to "ok, now you're infinitely small"?
Where's the dividing line in degree of smallness beyond which a number is infinitely small?
I understand $\lim_{h \to 0} \frac{f(x+h) - f(x)}{h}$ as the limit of an infinite sequence of ratios, I have no problem with that.
But I thought the point of a limit and infinity in general, is that you never get there.
For example, when people say "the sum of an infinite geometric series", they really mean "the limit", since you can't possibly add infinitely many terms in the arithmetic sense of the word.
So again in this case, since you never get to the limit, $h$ is always some interval, and therefore the rate is not "instantaneous".
Same problem with integrals actually; how do you add up infinitely many terms? Saying you can add up an infinity or terms implies that infinity is a fixed number.
Comment: Do you have a similar problem with instantaneous *position*? If not, then what is the relevant difference between instantaneous velocity and instantaneous position of a moving object?
Comment: If you are not yet familiar with the paradoxes of Zeno, you should read up on them; your concerns were first expressed millennia ago, and there is a fair amount of literature discussing these seeming paradoxes.
Comment: [A similar question](http://en.wikipedia.org/wiki/Zeno's_paradoxes#Arrow_paradox) was posed a while ago.
Comment: Maybe you should try not thinking of limits as movement, because then, as you say, you never "get there". Rather, when you see a limit like the derivative, imagine that there is a number that you cannot calculate, but that you can approximate with arbitrarily high precision. This is not some fuzzy thinking that cheats by evading the concept of instantaneous rate of change; if you can approximate a number **arbitrarily** well, then you know **exactly** what it is, even if you cannot calculate it "directly". (...)
Comment: In a sense I agree, in the classical framework the instantaneous rate of change is not really a "rate" which is maintained for any quantity of time, which is somehow problematic. At the same time, we are allowing for arbitrary resolution by working this way. If we don't do this, then now all functions are piecewise linear, possibly with extremely small pieces. But then how do you pick how small the pieces should be?
Comment: As an aside, an absolutely convergent series really is a proper generalization of a "sum", because you can shuffle the terms all around and still get the same result. This isn't built into the definition, but it shows us that at least in this setting our definition makes sense.
Comment: I think of it this way... Imagine you are driving a car, down a highway. At some point, you take a picture of the view out of the windshield, your dashboard, and all the meters. Surely, this picture represents a single moment, an interval of time with zero length (it's just a picture after all), and, your speedometer will have a reading, in that picture, that captured instant.
Comment: Regarding "infinitely small" quantities: in normal calculus, these are just limits: quantities that approach zero. but you should check out Non-Standard Analysis, which treats infinitesimals as actual numbers (not just a concept but actual, rigorously defined objects). Infinitesimals are "hyperreal" numbers that are smaller than every real number but still not equal to zero. This takes away the idea of a "moving limit" while still providing an explanation for "instantaneous" rates of change.
Comment: To reword what others have said, 'instantaneous' is just a metaphor to help with intuition. In the metaphor, there's a contradiction, movement over no time at all which really isn't movement. So that's a problem with the intuition, not the formal mathematics.
Comment: Sum of a infinite series means that as I keep on taking the partial sums the values keeps approaching a certain value
Comment: This isn't the main focus of your question, but as someone with an affinity for infinite series I'll add my two cents: Saying that you "add up infinitely many terms" does not mean add infinitely many things and then stop. As you say, that would imply infinity has an end, and must be finite. Instead it defines a process that never stops. For example the sum $$\sum_{n=0}^\infty 2^{-n}$$ is shorthand for $$\lim_{N \to \infty}\sum_{n=0}^N 2^{-n}$$ Some of these processes converge. We say the limit of that sum is $2$, because we get arbitrarily close to $2$. $N$ can be as big as we want.
Comment: Instantaneous speed: Are you talking of Heaviside like jumps of some quantity, here position, and its derivative the Dirac delta as rate of change?
Comment: It isn't discrete. Maybe the physical process you're trying to model actually is discrete somehow, but the mathematical object we've constructed is truly continuous. (As an aside, the question of whether physical space is quantized is open; to my understanding this question hinges on how quantum gravity works.)
Comment: As for the issue with absolutely convergent sums, what I mean is that if an infinite sum is absolutely convergent, then any sum consisting of the same set (multiset, perhaps, if some terms are repeated) of values converges to the same value. This is easy to state formally: if $p$ is a bijection from $\mathbb{N}$ to $\mathbb{N}$ and $\sum_{n=1}^\infty a_n$ converges absolutely, then $\sum_{n=1}^\infty a_n = \sum_{n=1}^\infty a_{p(n)}$. (This is not that easy to prove, though.)
Comment: I also think that you are artificially limiting your understanding by thinking of limits and infinity as "if you could ever get there then you would get this". Studying some (elementary) set theory might help with this.
Comment: @EricLippert, The conclusion is probably that I'm not actually clear on what position is, but in my mind position can be described independently of time, whereas velocity is defined as the ratio of position to time, whereby if time is 0 (an instant in time, as opposed to an interval), then you have position/0, which makes no sense.
I guess I just see velocity as *having* to be defined over a time interval.
Comment: Do you understand the epsilon-delta definition of limits?
Comment: In physics, at least, something is "instantaneous" if it's small enough to be ignored. Or too small to be measured. (Though I don't know if physicists call it that.)
Comment: @jeremyradcliff I wouldn't include the "infinite series" bit, we're talking about the behavior of the real function. But otherwise it's good. The fact that you can take the limit down to zero and approach some value for the rate of change justifies calling it an "instantaneous" one.
Comment: @Rememberme: that's just one of many ways in which you could define what the sum of a series means; and, as the problem with conditionally convergent series shows, not a very good one.
Comment: (...) With this point of view, the limit is not a process that will never end. Instead, it's an indirect way of specifying (without ambiguity) a number that you couldn't otherwise calculate. Maybe this will help.
Comment: You can see [The Analyst](https://en.wikipedia.org/wiki/The_Analyst) and the complete [text](http://www.maths.tcd.ie/pub/HistMath/People/Berkeley/Analyst/Analyst.pdf).
Comment: A bit late, but I think of this as "small enough", not "instantaneous". When $h$ is small enough, the change gets as close are you like to the desired value.
Comment: @Ian, re: "how small should the pieces be?". Couldn't you say "as small as you want them to be"? Which would still be different from claiming that there is such a thing a true continuity. I've always though of "continuous" functions in this way anyway. We allow for infinite granularity as a potential because we want to be able to input any value into the function, but ultimately it is still a discrete process. Is it wrong to think of it this way?
Comment: @Ian , re: sum. Can you really say you're shuffling the entire sum, though? I think you can shuffle the terms of a partial sum, but shuffling infinitely many terms still doesn't make sense.
Comment: @hobbs, i think I do. I think of epsilon as "give me an interval as small as you want and by continuing to add terms to my infinite series, I'll always be able to get closer to the limit than the epsilon you defined".
Please let me know if this is wrong.
Comment: ...and this is why we (should) teach what real numbers are before calculus.
Comment: A Primer of Infinitesimal Analysis, John L Bell.
Comment: I see it this way: The instantaneous rate of change at a point gives you a measure of that point's contribution to (or role in) the change of the values of the function, describing to you how the function changes one point before and/or after that specific point. It tells you if you could continue your journey one unit further or one unit back under the same circumstance governing that point, how much change you would experience. So, a tangent line can be seen as a collection of points which have contributions to the change of the values equal to that point on the graph of the function.
Comment: I'm voting to close this question because it has already attracted a fair amount of low quality answers that had to be deleted.
Answer: In math, there's intuition and there's rigor. Saying
$$f'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}h$$
is a rigorous statement. It's very formal. Saying "the derivative is the instantaneous rate of change" is intuitive. It has no formal meaning whatsovever. Many people find it helpful for informing their gut feelings about derivatives.
(Edit I should not understate the importance of gut feelings. You'll need to trust your gut if you ever want to prove hard things.)
That being said, here's no reason why you should find it helpful. If it's too fluffy to be useful for you that's fine. But you'll need some intuition on what derivatives are supposed to be describing. I like to think of it as "if I squinted my eyes so hard that $f$ became linear near some point, then $f$ would look like $f'$ near that point." Find something that works for you.
Comment: The best I've come up with thinking about the limit definition of a derivative, is "if there were such a thing as an instantaneous rate of change, this is what it would be", kind of the way you could think of a limit as "if we could ever get to infinity, that's the value we'd get". Is this wrong in the sense that I could limit my understanding of certain math concepts in the future by adopting this view?
Comment: It seems to me that you understand what's going on. Limits are weird at first, and derivatives are usually people's first exposure to serious limits. If you keep asking good questions, I suspect you'll be just fine.
Comment: @Yakk: Not very well. Non-standard analysis requires you to keep shifting  back and forth between working in the hyperreals and restricting your attention to standard reals, and the only principle for when to do what seems to be "think back to your knowledge of ordinary limit-based analysis and fudge your choice so you get the result you already know is right".
Comment: This answer seems to neglect the fact you can use infinitesimals to build a rigorous definition of calculus.
Comment: Interesting remark "You'll need to trust your gut if you ever want to prove hard things." I've been told by some people that at some point, things may become so unintuitive and abstract that you can't rely on your feelings to prove things anymore.
Comment: The snarky response is to "have better feelings." The serious response is that much of the hard work of mathematics is to build your intuition even for highly abstract fields. Forcing, for example, is outrageously abstract (compared to arithmetic, anyway). But it's useful to feel like forcing is 'adding the right member to a model.' The rigor is abstract, but it's practical to have intuition with simple terms. On the other hand, some intuition typically becomes less helpful at high level. E.G, 2D geometry intuition sucks in Banach Spaces. So we must find better, more helpful feelings.
Comment: @Henning NSA doesn't require you to shift back and forth between reals and hyperreals, for example there are no hyperreals in the IST approach.
Comment: @mt_: The words may be different than "hyperreals", but IST certainly has a distinction between standard and non-standard reals.
Answer: The idea behind $$\lim_{h \to 0} \frac{f(x+h) - f(x)}{h}$$ is the slope of the graph $y=f(x)$ .
Now for a moment forget about your instantaneous velocity and think about your average velocity. What is average velocity? I think average velocity is $$\frac{x_f-x_i}{t_f-t_i}$$. Now if look at this carefully this is my slope but in a given interval of time.
So you might question what is the difference between instantaneous velocity and average velocity , Both of them talk about intervals .
No that not the idea over here. Now if it had been a linear graph it would have been very easy to calculate your instantaneous velocity , but in your you graph that's not the case. Here you see the particle (or object) is changing its velocity every moment of time and that becomes impossible to deal with . So to remove this element of doubt what we do is try to take the limit and try to get close to the frame of time and try finding the velocity and name it instantaneous velocity.
Comment: In other words, replace the function with its tangent line approximation. +1
Comment: nice answer(+1).
Answer: Instantaneous Rate of Change at a Point, not over an Interval
You can describe rate of change without any interval at all, at a specific point.  In fact, to try and involve an interval, even a very small one, is somewhat counter to the concept.  If you involve an interval in describing a rate of change, then you would be talking about an average rate of change.  For example, when people describe the velocity(rate of position change) of a vehicle over an interval of 100ft, then you would usually be talking about the average speed, assuming it wasn't constant over the entire interval.
Therefore, a rate of change is always instantaneous.  You can identify any point, which has no length/interval, and say what the rate of change at that point is.  Instantaneous rate of change is analogous to a point.
This also helps understand why certain points have an undefined rate of change, and why the "ever smaller interval" concept is somewhat misleading.

If you tried to use the very very tiny interval concept to identify the rate of change across point p and point q by sampling a point just to the left and right of p to define an interval, then you'd see a very large change.  Perhaps point p is at x coordinate 1.00, and we define an interval from .99 to 1.01 and sample values of .99,2 and 1.01,10.  This would be a rate of change of 400 y per x.  If you make your interval smaller and smaller, your rate of change appears to approach infinity, which again is very misleading, because the instantaneous rate of change at p is undefined.
I'm not trying to disregard the intervals concept as useless, but to emphasize that very small intervals are a concept that can't be applied rigorously.  They certainly help understand the concept of a derivatives, because if you were to imagine that you don't know what the instantaneous rate of change at a particular point is, then you'd have to observe how much change occurred over an interval in order to estimate the rate of change.  It helps to understand how these functions were "designed".
There is no observed change, but we know the RATE of change

Let's take instantaneous speed, for example. If it's truly
instantaneous, then there is no change in x (time), since there's no
time interval'

You are absolutely right! There is no change in position as there is no defined interval.  However, at a specific point, we can still describe what the instantaneous rate of change is, which is a way of saying how much it will change if an interval were defined.  Imagine we freeze a frame of a movie where someone tells you a bullet just exited a barrel at an instantaneous velocity of 300 meters/s.  That's not hard to understand right?  If someone asked, disregarding air resistance and gravity, where will that bullet be two seconds from then?  Now you've introduced an interval, and using two things, the initial position, and the instantaneous rate of change at that position, you can confidently draw a line along the bullet's trajectory and conclude it will be 600 meters away in that two seconds.  Based on that instantaneous information, we can model for any interval how that bullet's position will change.  We can apply the instantaneous velocity across the entire interval only because we assumed it was constant across the interval.
Where calculus comes to the rescue is that we often deal with non-constant rates of change.  We know in reality that the bullet will slow down due to air resistance A(), and it's trajectory will be an arc instead of straight line due to the constant acceleration of gravity G() (which results in a non-constant velocity).  If we have functions that describe air resistance and gravity's influence on our velocity, then we can describe the non-constant instantaneous velocities over any point on the entire interval.  Since those are instantaneous points and are non-constant, they are somewhat useless. We could use the "very small interval" approach of sampling changes in position to sum up across the entire interval, but since the velocity is constantly changing, we'd be accumulating alot of error.  E.g. if the initial velocity is 300 m/s but slows to 250 m/s after half a second, then how far did the bullet travel in half a second?  You could try to average, but that assumes linear change in speed which might not be the case.  Just about any iterative approach you take that involves small intervals will introduce error.  However, with the help of calculus we can directly and accurately incorporate the influence of A() and G() on our non-constant velocity to directly calculate the change in position.
More than just a Concept
In addition to being an aid in understanding concepts, the "very small interval" concept is often applied in computational models where direct methods are not feasible, perhaps because a computer algorithm cannot determine a direct method.  This is exactly how physics are simulated in many computer games.  Each iteration it may know that .03 seconds has passed, and based on various rates of changes(usually determined based first on what forces are in affect) it will determine what has changed across that interval.  In certain situations this can be extremely inaccurate, but in other cases with small enough intervals it may be sufficiently accurate to meet desired requirements.
Comment: I'm rereading the answers to my question after several months of Calc (and a lot more thinking) and your answer is very helpful and makes a lot more sense than it did then, thank you!
Comment: @jeremyradcliff This is a better Answer than the currently-accepted one, which I [disagree](https://math.stackexchange.com/a/4270406/21813) with.
Answer: Think of a mountain: far away it's nearly flat; near the top it's more steep.
If you ask "How steep is it where I am standing right now?", you're asking exactly the same thing as "What is the rate of change of my elevation with respect to my position right here?"
I feel that should be pretty intuitive; that's what instantaneous rate of change means.
(Side note: in this case, you can move in two independent directions: north/south and east/west. That means there is a separate rate of change of elevation for each of those directions at every possible position on the ground. But in your case, you're only dealing with time, which can only go forward/backward, and hence there's only one number to worry about at each instant, not two.)
Answer: As the accepted answer stated, the English language statement is informal and exists to provide intuition only.
That does not mean it might not be finessed.
If one rewords to
<code>Rate of change applying at a specific instant
</code>
then I think this is consistent with:

A rate of change being defined only on intervals
Those intervals being arbitrarily small
We have a unique value meaningful for a given instant, provided of course that the limit exists.
Answer: I will answer your question with a question.
You are driving a car. 60 miles per hour is 88 feet per second (which is pretty cool in and of itself. You look down at a text for 1/2 second? You moved 44 feet.) Now, when I ask where you were in a given second, you could have been anywhere within +/- 44 feet. So you say "which 1/100th second are you asking about?" But 44 feet is 528 inches, so even if I say at time = 6.31 seconds past 2:30, you only know within a 10 inch range.
Can you ever tell me precisely where you are if you are in motion?
Instantaneous rate is a calculus concept, but it should be understandable to you as the slope of a tangent line.

The line tangent to the parabola has a slope of 2. Even though the "slope" is just a point.
Answer: I think the answer of @ZachStone already expresses the essence of your question.
I would add a more Physical/Engineering point of view, because you call in the intuition, and in applied maths, as usually found in engineering, you need a lot of intuition.
As a concrete example, let's consider the speed of a car (or of any point mass). There is the average speed which is trivially and very understandably defined as:
\[
v_m = \dfrac{\Delta s} {\Delta t}
\]
You define the instantaneous speed as the limit of that ratio as the time interval tends to zero:
\[
v = \lim_{\Delta t \to 0} \dfrac{\Delta s} {\Delta t}
\]
Of course if you knew a mathematical expression for s(t) you could do all your usual math, and that's ok. But what does it mean that limit in practical applications? It means that you look for a value of the "average speed" over a "very small" time interval, where "very small" means "as small as possible in relation to the application". That usually means that $\Delta t$ is so small that s can be deemed constant over that time interval, because the allowable measurement error is larger that the variation of s over that interval.
In a sense, you approximate your motion as you go ahead: at any time instant you say to yourself "if I had to approximate now the motion with a constant speed motion, which speed would the car have?". The answer is "the instantaneous speed" (which is, as I said before, approximately computed as an average speed over a "small enough" time interval).
Answer: I think this question should belong into meta, as it is a question between finitism and platonism, but I try to answer you as best as I can:
The dividing line where a number $\epsilon$ is small enough is when someone gives you a number $\delta>|x-c|>0$, there exists $\epsilon>|f(x)-L|$, where $c$ is a point near $x$, $L$ is the limit. So you need not think $h$ as an interval, but as a number.
In arithmetic sense, you can add infinitely many terms if they follow a rule which can be mathematically constructed: the geometric series is a good example. The existence of integral is therefore quite natural.
Addressing your first question in a philosophical manner:
Say that there exists events that happen instantaneously. If they do exist, they need to be observed. For the observation to happen, time needs to pass, so we can think "instantaneous" as an event which occurs in the least time possible for the event to actually happen.
Comment: You misunderstand the purpose of meta forum - it is for discussing **the website** Math Stack Exchange and its operation. Mathematical questions of any sort are off-topic there.
Answer: This was stated in another form in a different answer, but I thought I'd say it in a way that might be conceptually easier to grasp:

The instantaneous rate of change at any point in a function is the slope of the line that is tangent to the function at that point.

If you imagine a line that intersects two points on an arbitrary function that are some arbitrary distance apart, and then slide those points together, you will see that the slope of the line changes depending on the distance between them. When the two points are so close together that they become one, then the slope of the line is equal to the instantaneous rate of change of that function.
Answer: Why don't we just say "approximately instant" to appease  our intuition, and then define our velocity as an arbitrarily close approximation to an average one?
As a bit of an aside, 'closeness' is tied to so many higher levels of Mathematics. So many things hang on it. Topology, Analysis, and the like to be sure. So, as mathematicians, we've become comfortable with the idea of the limit as a definite value to make so many other things work out.
I always have in the back if my mind that that denominator IS NOT zero but gets really close to it. And for me the limit is hanging onto that closeness and rejecting the idea that it can actually be zero - because it can't be.
Comment: I should add here that epsilon and delta are precisely the differences between the quantity that is _approaching_ zero and zero itself.  If you study higher level mathematics, you will use epsilons and deltas many times over!
Answer: The expression $\dfrac{x^3-8}{x-2}$ is undefined at $x = 2$. When $x = 2$ you get $\dfrac 0 0$, which is undefined. So suppose we decide to define the value of  $\dfrac{x^3-8}{x-2}$ when $x = 2$. What number makes the most sense and why? Well, when $x \ne 2$ we can simplify
$$\dfrac{x^3-8}{x-2} = \dfrac{(x-2)(x^2 + 2x + 4)}{x-2}=x^2 + 2x + 4$$
and $x^2 + 2x + 4 = 12$ when $x = 2$.
If you graphed $y = \dfrac{x^3-8}{x-2}$ you would get the graph of
$y = x^2 + 2x + 4$. Depending on how good your graphics software is, it may or may not indicate that there is something wrong at $x = 2$, but the point
$(2, 12)$ is actually missing. We call points like this "removable discontinuities".
A rate of change of a function $f(t)$ between a variable time $t$ and a fixed time $a$ looks like $\dfrac{f(t) - f(a)}{t-a}$ and you notice that, if you let $t=a$, you get $\dfrac 0 0$.
A whole lot of the time, $ y = \dfrac{f(t) - f(a)}{t-a}$ has a removable discontinuity at $t = a$. If the missing point is (a, A), then it turns out that $\displaystyle lim_{t \to a}\frac{f(t)-f(a)}{t - a} = A$. The number A is called "the derivative of $f(t)$ at $t = a$" and it is described as "the instantaneous rate of change of $f(t)$ with respect to $t$ at $t=a$.
Answer: What makes Calculus "useful" in the "real world" isn't the formalism about limits or infinitesmials1.  It is the fact that most functions in the "real world" are relatively smooth and well behaved.
Such functions act linearly if you zoom in "enough" -- they act like little linear functions (well, affine functions -- linear with an offset).
The derivative associates each point on a function's domain (valid input) with a linear function.  This describes the "slope" at that point.
If you are "close enough" to the point, then the linear function that the derivative gives you is a good approximation to the original function.
As linear functions are ridiculously easier to work with than other functions, this makes understanding the original function easier.  Even if we are forced to understand an infinite number of such linear functions to understand a single non-linear function (the family of derivatives).
If a function goes from $\mathbb{R}$ to $\mathbb{R}$, then the linear maps have a natural bijection with elements of $\mathbb{R}$ -- so instead of the derivative returning a function, we denote it as returning a single real value.
If $f'(x) = g(x)$, then the affine map that approximates $f$ near $x_0$ is $h(x) = f(x_0) + g(x_0)*(x-x_0)$.  Most of that is boring, so we just talk about $g(x_0)$.
In higher dimensions, the value returned from "the derivative" is a higher dimension linear function, which is represented by a matrix.
These linear functions are "guaranteed" to be "useful" if you are close enough to the point in question.  How close can vary with the function in question (see the error bounds on prefixes of the Taylor series).
This is the "slope at the point" because talking about the interval around the point where it is half-decent is hard to talk about, but we do know that if we make the area small enough it is going to be good.

1 There are multiple formulation of calculus that acts on infinitesmials -- the smooth analytic analysis or non-standard analysis.
In it, you actually talk about points $x+h$ infinitesimally close to $x$, and evaluate $\frac{f(x+h)-f(x)}{(x+h)-x}$.  The result is the derivative of $f$.
The delta -- $h$ -- is smaller than every classical real number.  In a sense, $x+h$ is "still at $x$" (as far as classical real numbers are concerned), but in the non-standard analysis it isn't the same value.
Under this formalism, "at the point" could refer to "at the point, and infinitesimally close to the point".
Comment: $(f(x+h) - f(x)) / ((x+h) - h)$ is not the derivative of $f$: it is merely *infinitesimally close* to the derivative (assuming the derivative exists).
Answer: To talk about instantaneous rate of change, you have to first have a sufficiently nontrivial idea of an instant. The main point of differential calculus is to flesh out the idea of an instant, how to do calculations in instants, and how to use integrals to "add" them all up.
In a more precise sense, the central idea is that at a point, you can have numbers that encode what happens near that point.
The simplest example of this is the meaning of continuity: if you know $f(a) = b$, then you also know that $f(c) \approx b$ whenever $c \approx a$. So when you're working with continuous functions, knowing what happens at a particular point means you have some idea about what happens near that point too. Another example of something you know is that $\lim_{x \to a} f(x) = b$.
The derivative is another example of this, and there is a lot of circumstantial evidence that links it to being a rate of change. For example:

The mean value theorem, differential approximation, and similar things allow you to use a derivative to estimate a rate of change. e.g. $$y - y_0 \approx (x - x_0) \frac{\mathrm{d}y}{\mathrm{d}y}$$
I can use an integral to "accumulate" the derivatives to produce an actual change: $$\int_a^b f'(x) \mathrm{d}x = f(b) - f(a)$$
If you plot the graph of the rate of change (i.e. the difference quotient) of a differentiable function between $x_0$ and $x$, there is hole that really ought not be there (in a very similar sense how one would like to say that $t/t = 1$). The derivative is the value that fills that hole.
In many circumstances (all of them, when suitably treated), one can compute a derivative formally by the procedure of writing down $(f(x) - f(x_0))/(x - x_0)$, doing simplifications to cancel out the denominator, then making the substitution $x \to x_0$.

Rather than being stuck on the fact that pre-calculus tools fail to express the idea of a rate of change in the situation where the derivative applies, you should instead be looking to see how the method of using derivatives allows you to study the idea of rates of change in situations where the pre-calculus tools were unable to help.
Answer: I had come to accept the slope intuition of derivatives a long time ago, when I first learned calculus. I never really understood it completely, I must confess, but since it proved useful in so many different applications (particularly in physics), I began to accept that interpretation without having to think about it at all after a certain point.
It was when I studied calculus slightly more formally that I gained a better understanding of the concept of limit and derivatives as a whole. The breakthrough came when I understood how sequences/series of numbers and their limit points work. Consider the following infinite sum:
\begin{equation}
1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + ...
\end{equation}
The 'limit' of this sum is equal to $2$. Now obviously, you can't go on adding infinite terms to get exactly $2$, yet we say (and we say this as a proper mathematical statement - not as an ambiguous expression of out intuition) that the limit of the sequence is $2$.
The idea behind the limit (in the case of sequences/series) is that if you kept on evaluating the sequence with more and more terms, you would come closer and closer to $2$. You wouldn't be 'converging' to $\textbf{any other number}$ other than $2$. We call $2$ a limit point of the sequence.
In a similar manner, when we talk about 'instantaneous' rates, what we are saying is that if we calculate the rate with smaller and smaller intervals, we get closer and closer to the value we call the 'instantaneous' rate. We never actually attain that value, but we get closer and closer to it.
In a sense, it's kind of like a 'sacred' value that your expression is always striving to reach. You can't ever really be sure of it even if you study the behaviour of the expression for very long. As an example, you might conclude that the sequence I showed above has a limit of $2.000000000001$, just by computing the value with more and more terms. But if you went even further, you would discover that the sum's distance from $2.000000000001$ begins to increase after some time (suppose you hit the midpoint of $2.000000000001$  and $2$, the true limit; continuing with the evaluation of the sum from there on out would lead you closer to $2$, and thus farther away from $2.000000000001$).
So you see, the thing about the limiting value of an expression is that it is not an easy task to determine it just by studying the way the expression behaves numerically (which is what the intuitive explanation of 'instantaneous' may lead you to believe). This is why the mathematics of limits is so profound. You can compute the $\textbf{exact}$ value that the expression converges to, regardless of 'practical artefacts' like numeric precision. It is actually quite an elusive value, the limit of an expression...but it has a lot of meaning to it.
If you continued forever in the direction of the limit, you would continuously get closer to the limiting value (limit point), but you would never reach it. If we could measure the rate in an intervals of ever decreasing length, we would approach the instantaneous value - but we never get an exact match.
Comment: I was hoping somebody already gave an answer like this so I wouldn't have to. If we compute average velocity on smaller and smaller intervals and observe a sequence like $2.01$, $2.001$, $2.0001$, $\dots$, then we appear to be converging to the "true" velocity of $2$ at that instant.


Examples of natural transformation-like but doesn't commute?

Question: While studying concrete categories (Top, Cat, Grp, Ring, etc), a lot of times I get two functors $F,G: C \to D$ as well as a family of morphisms $\eta_c:Fc \to Gc$. So far, it has never been the case that $\eta$ is not a natural transformation. Given this, it is very tempting to not check commutativity of the square.
Mostly to convince myself to actually check the square for future instances, what are some "natural" examples that one could encounter on the wild that seem like natural transformations, but actually aren't? I.e. there are $\eta_c$ but the square doesn't commute.
Answer: A standard example is the universal coefficient theorem for homology: given a topological space $X$ and an abelian group $A$, there is a natural short exact sequence
$$
0 \to H_i(X;\mathbb{Z}) \otimes A \to H_i(X;A) \to \mathrm{Tor}(H_{i-1}(X;\mathbb{Z}), A) \to 0.
$$
This splits, but not naturally: there are non-natural isomorphisms
$$
H_i(X;A) \cong H_i(X;\mathbb{Z}) \otimes A \oplus \mathrm{Tor}(H_{i-1}(X;\mathbb{Z}), A).
$$
So take the two sides of this isomorphism to be your two functors.


Is this question completely defined

Question: I saw this question on a page:
If $a$ is additive identity then:
a)$a+a=2a$
(b)$a+a=1$
(c)$a+a=a$
(d)$a+a=0$
I think the question is undefined,Here the intended answer is c) but I think the question is undefined since the set is not mentioned to which $a$ is additive identity
Update: I guess a), c) and d) can be the correct answers at the same time or is there an example of a group which only satisfies c)?
Comment: All four answers are true in the trivial ring.
Comment: How is b) true?
Comment: It's a joke. The trivial ring has $1=0$.
Answer: In an additive group $(G, +)$ you have a unique (additive) identity $e$. This elements satisfies that $e + g = g$ for all $g \in G$. In particular you have $e + e = e$.
Example: Think about the additive group $\mathbb{Z}$. Here $0$ is the identity because you indeed have $0 + n = n$ for all $n\in \mathbb{Z}$. In particular you have $0+0 = 0$.
So it is pretty obvious that (c) is the right answer since this is the defining property. However, I agree that it might be confusing.
One could argue that (d) is the right answer because $0$ usually is the "symbol" we use for the (additive) identity, and so you would have $a = 0$ and so (d) would be right.
(b) definitely isn't the right answer because $1$ usually denotes the multiplicative identity.
(a) could be considered right since we usually take $2a$ to mean $a+a$ by definition.
Comment: You make the question more confusing!
Comment: @HashirOmer: The point is that the answer is pretty obvious. But I can see that it might seem confusing. I don't think that the question is worded well.
Answer: The question is well-defined. In any group $(G,+)$ if $a$ is the identity then $a+x=x$ for all $x \in G$. Therefore when $x=a$ the result follows.
Comment: If there could be more than one answer in MCQ format then surely it is ill defined.
Comment: See Thomas answer!
Comment: Thomas's answer simply suggests that if we follow some conventions (like $2a$ means $a+a$ Or sometimes we denote $0$ as the additive identity) then there could be more than one answer. However this still does not make the question ill defined.

Is this question completely defined


Include constant to estimate propensity scores?

Question: Should we include the constant when we estimate propensity scores?
We model the probability that $D_i=1$ using a set of controls $x$
$$ p (D_i=1 | X=x) = \alpha + x \beta + \varepsilon $$
to created predicted values $\hat{p}$. Should we include the $\alpha$?
Answer: Why wouldn't you? The goal is to get good predicted probabilities, and surely you will get better predicted probabilities with an intercept in the model. But you don't have to wonder; you can try your way, assess balance after matching or weighting on the resulting propensity scores, try the other, and compare performance. I really can't imagine too many scenarios in which you wouldn't want an intercept. It removes 1 extra degree of freedom but will likely dramatically improve the performance of the model.
Comment: Agreed, I just thought it might be strange to think that the probability of success is larger than zero if all X are zero.
Comment: Well usually one uses a model that ensures the predicted probabilities are between 0 and 1, like a logistic regression model. It is possible to get predicted probabilities less than 0 or greater than 1 with a linear probability model, so I don't recommend using one.
Answer: I agree with @Noah. I just want to add the following. Suppose we have the outcome $y$ and predictor variables $X_i$ in a regression model, where $i = \{1, 2, ...\}$. Then we have the option to standardize the predictor variables $X_i$ before fitting the regression model and regress $y$ on $X_i - \bar{X_i}$ instead of $X_i$. Therefore, if we use propensity score $\hat{p}$ (estimated from $X_i$) instead of $X_i$, e.g., in PS adjustment, then we could as well "standardize" $\hat{p}$ if that gives us some desirable propriety, e.g., to achieve some interpretation of model parameters, etc. So my view is that it depends on what we want to accomplish with $\hat{p}$.


How to add profile2 field data to a programatically created user

Question: I create a user from a form (that part works fine) but no profile2 information seems to be created....
profile2_load_by_user returns an empty array which results in the below error.  Do I need to some other step to first associate an "ae_sa" profile with the newly created user?

Recoverable fatal error: Argument 1 passed to profile2_save() must be an instance of Profile, instance of stdClass given, called in D:\FULLREPO\trunk\sites\all\modules\sps_users\sps_users.module on line 115 and defined in profile2_save() (line 291 of D:\FULLREPO\trunk\sites\all\modules\profile2\profile2.module).

...
$account = user_save(null, $new_user);
$obj_user = user_load($account->uid) ;
$profile2 = profile2_load_by_user($obj_user) ;
$profile2["ae_sa"]->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile2["ae_sa"]->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile2["ae_sa"]->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile2["ae_sa"]->field_bio[LANGUAGE_NONE][0]["value"] = $bio;
profile2_save($profile2["ae_sa"]) ;

Comment: You using Drupal7? If so, Why not use the field-able profile fields that come "out-of-the-box"?
Comment: Working on a project begun by someone else, switching at this point is not an option
Answer: You need to create the new user's profile:
$profile = profile2_load_by_user($user->uid, 'ae_sa');
if(empty($profile)) {
  $profile = profile2_create(array(
    'type' => 'ae_sa',
    'uid' => $user->uid,
  ));
}

// Fill fields
$profile->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile->field_bio[LANGUAGE_NONE][0]["value"] = $bio;

// Save the newly created OR updated profile
profile2_save($profile);

Comment: this is perfect answer, when user dont have profile data that time you are not able to load profile and save data , thats time you have to use

 $profile = profile2_create(array(
    'type' => 'ae_sa',
    'uid' => $user->uid,
  ));
Answer: You need a second variable for the profile2_load_by_user($obj_user) function.  What you currently get back is an array of profiles, e.g
'candidate' => Profile object,
'person' => Profile object,
'student' => Profile object

You need to specify the profile in the call and then you just get a profile object back.  Then you can save the profile as it is an Profile object.
e.g. profile2_load_by_user($obj_user,'candidate');


How to generate direct download link for google drive link by file id

Question: I want to generate google drive direct download link without opening web page.
I have found 1 site which do same thing but I did not find how he is doing.
below is the site which generates direct download link without opening google drive page.
https://links-safety.com/download.php?id=0B475ByfcR9n4a1JMVEZxQno2Tmc
0B475ByfcR9n4a1JMVEZxQno2Tmc is google file and replace with any file.
can anyone tell me how can I do that?I want to make same page like above site.
I tried this url but its not working. instead of starting download it opens page.
Please guide me to do this on wordpress source code
Comment: Please before asking a question, read [mcve]
Comment: please show what have you tried (use the "edit" button to insert the corresponding code in your question). Best regards
Answer: Here is how I did it.
https://drive.google.com/u/3/uc?id=<your ID here>&export=download
just replace  with you file id
NOTE:
not related but helpful tip
To get you file ID

click the file on google drive
then find 3 dots on right most part of window
select Open in new window option
that will open a new window with link like https://drive.google.com/file/d/<Your file ID>/view


Character Sums, Weights, and Cohomology

Question: I know, vaguely, that certain bounds for character sums over finite fields can be determined by looking at weights and the dimensions of certain compactly supported cohomology groups.  However, I've never seen this spelled out explicitly and have been searching in vain for a source that does so.
To be somewhat more explicit, we can obtain something like
$$\sum_{x \in \mathbb{F}_{p}} \chi(f(x)) \leq C \cdot p^{d/2} $$
for $\chi$ a nontrivial multiplicative character. I've been told C is the dimension of a certain cohomology group and d is a weight.  Anyone know a place where this is made explicit?
Answer: Terence Tao recently wrote a blog post that seems to answer this question.

Character Sums, Weights, and Cohomology


Validate precise scale with less precise scale

Question: Is it possible to validate the measurements of a precise scale with a scale wich is less precise?
Let's say I have a scale wich can display values down to 1g and another scale which can display the values down to 0.01g. I measure for example 100 pieces, which I know are about 1g, on the precise scale an save all the individual measurements. Then I measure the total weight of all pieces on the less precise scale and write this value down. If needed, I can make as many measurements as needed on the less precise scale and use all these measurements.
With the information gained, total weight and individual weights off the precise scale, what can I say about the accuracy of the precise scale?
Comment: Using the less-precise scale you have made just a single measurement? If so, your job of validation is going to be very difficult.
Comment: You can't say anything whatsoever about accuracy until you know the accuracies of the scale used for the measurements!
Comment: @rolando2 i can make as many measurements with the less precise scale as needed. I added this fact in to the question.
Comment: @whuber assume the accuracy is the same as the displayed value on the scale.
Answer: You can do this if you are sure that the measurement error for the coarse scale is low (that is, if you are sure that when your measure one hundred thousand 0.01 gram samples you will have a reading of 1000 gram +- some small error). In this case you will have a solid expected value for sums of fine-grained measurements and you will be able to see if these sums are well behaved (not biased towards lower or bigger values and have reasonable variance).
Comment: I understand the bias you mention in the answer. But can you add some more details about the variance? What can I say about the variance?
Comment: Actually, you don't need the coarse scale to estimate the variance. If you measure something 1000 times and add the results you will obtain a point sample from a population of _sums of 1000 individual measurements_. Since the measurements are independent from each other, you can sample in this manner several times, estimate the variance of this sample-of-sums and then simply divide by 1000: variance of a sum of i.i.d. variables equals the sum of their variances. You need the coarse-but-low-error measurement to check if fine-scaled measurements are biased.


Prevent IPs from downloading a file multiple times on server

Question: I have a program that users can download from my site via a button which posts to a php page. The php logs the download request into my DB then serves up the actual program for them to download. However, I've noticed from time to time that certain IPs will download the program every half hour...sometimes hundreds of times over many days. Not sure what it is, assuming it's a bot, and the IPs are always in countries like Romania or Hungary.
Initially I was blocking IPs in my .htaccess, but I don't want to keep doing that every time. So I've added code to my php which only allows users to download the program a specific # of times each day. That works fine, however, it's easy enough for someone to just get the direct url to my program and download it that way bypassing the php logic.
1) Is there are way to prevent this? Can the .htaccess be modified to prevent direct downloads of the file but allow my php to serve it up?
2) Should I even be worried about this at all? I'm using a shared server so I'm really just concerned about the bandwidth impacts.
Comment: i don't know if you can prevent direct downloads in .htaccess file, but you can move the file outside the publicly accessible directory and have php script serve it from there (after checking the IP and applying the limit)
Comment: IP != user. you need a proper user management system here
Comment: You could save the IP to your database. when the page loads make it check the database, and if the ip is found then use a if else statement to prevent the download link from showing up? and use a dynamic link saved in the database to prevent repeated access to the same link.
Comment: 1) you shouldn't and 2) you shouldn't. think about NAT: multiple valid users sharing the same public IP. then think about carrier grade NAT: *thousands* of valid users sharing the same public IP. now think about potential attackers of any kind: single evil minds with knowledge and technology to use thousands of different IP addresses.
Answer: If what you want is not allowing users to bypass the PHP logic, you can render and output the file with PHP script.
<?php
$file = some file from query;

if (some logic matches)
    die('Download forbidden');

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

See: http://php.net/manual/en/function.readfile.php
Suppose your file is stored in /files/, put the script in somewhere like /down.php, and add the following code in .htaccess in /files/.
Deny from all

More on this, you can see: Deny access to one specific folder in .htaccess
Besides, if you really care about the bandwidth, you can enhance your download prohibit logic, like create user system, or put the user IP into the database to manage/restrict the total download bandwidth of each user.
Comment: Thanks. That's exactly what I need.


Facebook session dissappears when refreshing the webpage

Question: I'm new to the facebook login SDK for PHP and i'm trying to create a "log in with facebook" function on my website.
I'm using this code which works great:
session_start();

require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'Facebook/HttpClients/FacebookCurl.php' );
require_once( 'Facebook/HttpClients/FacebookCurlHttpClient.php' );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookHttpable;

FacebookSession::setDefaultApplication('app-id', 'app-secret');

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'app-redirect-link' );

try {
  $session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
  // When Facebook returns an error
} catch( Exception $ex ) {
  // When validation fails or other local issues
}

// see if we have a session
if ( isset( $session ) ) {
  // graph api request for user data
  $request = new FacebookRequest( $session, 'GET', '/me' );
  $response = $request->execute();
  // get response
  $graphObject = $response->getGraphObject();

  // print data
  echo  print_r( $graphObject, 1 );
} else {
  // show login url
  echo 'getLoginUrl() . '">Login';
}

If I press "Login" I get my details and everything I need, but as soon as i'm refreshing the page - the "Login" link appears again, as if the session does not exist anymore.
Any help would be appreciated.
Comment: You probably need to store the session somewhere, and load it if it exists.
Answer: Defining a new session and using it helped.


taking query string values without full postback

Question: i have a page in which the left column contains category list and the right column will display the corresponding items on choosing a particular category from the left
each category list contains a hyperlink whose navigate url contains query string values.
on clicking the link i get the items listed in the right matching the querystring value
question is: i want to prevent the full postback and at the same time to catch the querystring values to without which i wont be able to get the items list in the right.
i used an update panel but the full post back is happening again.
is there any way to get query string values without full postback???
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

Categories

        <asp:Accordion ID="Accordion1" runat="server">
            <Panes>
                <asp:AccordionPane ID="AccordionPane1" runat="server">

                            Electronics

                    <Content>

                                      <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="show_products.aspx?category=Electronics&sub_category=Cameras Accessories">Camera Accessories</asp:HyperLink>

                    </Content>
                </asp:AccordionPane>

        </asp:Accordion>

     </ContentTemplate>
    </asp:UpdatePanel>

    <asp:UpdateProgress ID="UpdateProgress1" runat="server"
        AssociatedUpdatePanelID="UpdatePanel1">
    <ProgressTemplate>

                    <asp:Image ID="Image1" runat="server" ImageUrl="~/staticimages/progress_bar_animated (1).gif"
                        ImageAlign="Top" />

    </ProgressTemplate>
    </asp:UpdateProgress>

Comment: can you show us the code you tried with your update panel.
Answer: Well, yes you can do this But it's not the easy task..
You need to write some JQUERY and have to use AJAX with that.
And using that you can easily achieve this.
i am not much familiar but this, but i know that this can be done using AJAX and JQUERY.
It might also be required to add some web services in your project to achieve this.
This link can help you http://api.jquery.com/jQuery.ajax/.
Answer: You can put such a value in the CommandArgument property of your link button and then you will be able to access it in code behind like...
protected void lbtn_Click(object sender, EventArgs e)
{
    ((LinkButton)(sender)).CommandArgument
}

Comment: i am using hyperlink not link button coz for 100 categories i dont want to have 100 button click event.
Answer: You can get it using javascript: http://www.west-wind.com/weblog/posts/884279.aspx
Then can use any ajax way to send this back to the server.


html - como criar um botão que quando eu clicar nele aparecer outro

Question: quero criar um botão que quando eu clicar nele realizar um ação por exemplo abrir um site e junto aparecer um botão abaixo.
tipo,para acessar o site clique nesse botão e depois que a pessoa clicar nele abrir um site e aparecer outro botão abaixo.
outro exemplo:  Para baixar clique neste botão e acesse o nosso site primeiro e depois que a pessoa clica e acessar o site aparecer o botão de download.
Me ajude...
Comment: Você pode usar uma função onclick (do JavaScript) para manipular o display do botão, que você quer exibir ao clicar no outro
Answer: Imagino que essa solução é adequada para você:
HTML

  <button class = "b1">
    Clique-me!
  </button>

  <button class = "b2" style = "display: none;">
    Outro botão!
  </button>

JavaScript
var button = document.querySelector(".b1");
var button2 = document.querySelector(".b2");

button.onclick = function() {
 window.open('www.google.com', '_blank');
 button2.style.display = "block";
}

Ao clicar no botão b1, a função atrelada ao onclick abrirá uma nova aba e alterará o display: none para display: block do segundo botão, de classe b2.
JsFiddle: https://jsfiddle.net/xuuj2qv4/
Comment: é possivel adiciona codigo javascript em blogger html?
Comment: não consigo fazer o de html funcionar coquei o codigo de html e não pega
Comment: Sei que é possível, só não sei como exatamente. O HTML precisa do JavaScript para funcionar.


Rails3 routing error

Question: My scenario: Movies have reviews, reviews have comments.
Movie model:
has_many :reviews

Review model:
has_many :comments
belongs_to :movie

Comment model:
belongs_to :review

Routes:
resources :movies do
  resources :reviews do
    resources :comments
  end
end

Comments controller:
def create
  @movie = Movie.find(params[:movie_id])
  @review = Review.where(:movie_id => @movie.id)
  @comment = @review.comments.create(params[:comment])  // Line 5
  redirect_to movie_path(@movie)
end

Comment view:
<%= form_for([@movie, r, r.comments.build]) do |f| %>

    <%= f.text_area :body %>

    <%= f.submit "Submit" %>

<% end %>

The error that I get is:
NoMethodError (undefined method `comments' for #<ActiveRecord::Relation:0x007ff5c5870010>):
app/controllers/comments_controller.rb:5:in `create'

Can somebody please tell me what I'm doing wrong?
Thanks in advance..
Answer: Review.where returns a list of reviews, what you want is an instance
@review = Review.where(:movie_id => @movie.id).first

or
@review = Review.find_by_movie_id(@movie.id)

Make sure to handle nil case.
Comment: works perfect.. (i just accepted an answer for another question and it asks me to wait for 4mins).. will accept it after 4.. thanks a lot

Rails3 routing error


managed_file not initialised after form ajax

Question: I'm having issues with a managed_form field not beeing initialised after it is introduced via a ajaxcallback in a custom checkout Pane:
/**
 * Provides a custom message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "video_greeting",
 *   label = @Translation("Gift Information"),
 *   default_step = "video_greeting",
 * )
 */
class VideoGreetingPane extends CheckoutPaneBase {

 // ...

 public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $form_state->set('uploadPath', 'public://orders/' . $this->order->get('order_id')->getString() . '/');

    // ...

    $pane_form['expandable'] = [
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'container'
    ];

    $pane_form['expandable']['video'] = [
        '#type' => 'inline_template',
        '#template' => "{% include '@vanity/commerce/video-thumbnail.html.twig'  %}",
        '#context' => [
          'video' => $video,
          'order' => $this->order
        ],
      ];

      $class = get_class($this);

      $pane_form['expandable']['remove'] = [
        '#type' => 'button',
        '#value' => $this->t('Remove'),
        '#name' => 'removeButton',
        '#attributes' => [
          'class' => ['btn', 'btn-remove'],
          'type' => 'button'
        ],
        '#ajax' => [
          'callback' => [$class, 'ajaxRemoveVideoCallback'],
          'event' => 'click',
          'wrapper' => 'video-greeting-expandable',
          'method' => 'replace',
          'progress' => [
            'type' => 'throbber',
            'message' => ''
          ]
        ]
      ];

    // ...

 }

  public function ajaxRemoveVideoCallback(array &$form, FormStateInterface $form_state) {

    $form['video_greeting']['expandable']['video']['#access'] = false;
    $form['video_greeting']['expandable']['remove']['#access'] = false;

    $form['video_greeting']['expandable']['file'] = [
      '#type' => 'managed_file',
      // '#parents' => array_merge($form['video_greeting']['#parents'], ['file']),
      '#required' => false,
      '#upload_location' => $form_state->get('uploadPath'),
      '#upload_validators' => [
        'file_validate_is_video' => [],
        'file_validate_extensions' => ['mp4'],
      ],
      '#description' => t('Please upload a video file.'),
      '#default_value' => null, // don't need
      '#accept' => 'video/mp4',
    ];

    return $form['video_greeting']['expandable'];
  }

  // ...

}

The ajax replace works fine, but the js-component of the managed file get's not initialized somehow. It stays like this after the replace:

Any hint would be greatly appreciated.
Answer: You are creating form elements in the Ajax callback. These will not work, as the Drupal settings are created before the Ajax callback is called, and therefore any elements added in the ajax callback do not have their JS settings sent to the browser, and therefore the managed file ajax is not initialized.
You need to add any form elements, including your managed_file element, in a conditional in the form definition. This conditional should check if the form has been submitted, and add the form elements accordingly, in the form definition, NOT the ajax callback.
Comment: Dear @Jaypan, thx a lot for your knowledgeble answer - any chance you could post an example of a "conditional" or a link? The concept is so far new to me.


ERROR: Unsupported PIVOT column type: text

Question: I'm trying to perform a PIVOT but getting an error. I'm trying to see which patients have more than one Interval session. The column is a text type. I attempted to convert the column type to VARCHAR(MAX) in my query but still getting the error.
Here is my code:
SELECT patientname, IntervalName1, IntervalName2, IntervalName3
  FROM (SELECT DISTINCT
               patientname,
               CAST(IntervalName AS VARCHAR(MAX)),
               'IntervalName' +
                CAST(ROW_NUMBER() OVER
                    (PARTITION BY patientname
                         ORDER BY patientname) AS VARCHAR(10)) AS ColumnSequence
          FROM vwPatientPEIOutcomes
         WHERE [ vwPatientPEIOutcomes.DueDate = daterange ]
         GROUP BY patientname, IntervalName
         ORDER BY patientname, ColumnSequence) Temp
PIVOT(
      MAX(patientname) FOR
         ColumnSequence IN ( IntervalName1, IntervalName2, IntervalName3 )
     ) tb2

Here are my second set of edits below in regards to your answer. I'm new to this so took my some time to figure out what was needed:
Thank you for the answer. I was using the group by because the row_number was creating duplicates and I could not figure out how else to not have that happen.
Both the patient name and interval name are strings in the database. Intervalname is a field that signifies if they have been administered a questionnaire in a given timeframe. I'm trying to create a single row per patient.
Here is the dataset:
CREATE TABLE vwPatientPEIOutcomes (
  patientname varchar(max) NOT NULL,
  intervalname varchar(max) NOT NULL,
  ) ;
   INSERT INTO vwpatientPEIOutcomes (patientname,intervalname)
  VALUES
  ('Patient 1','End'),
  ('Patient 2','Start'),
  ('Patient 3','Start'),
  ('Patient 4','End'),
  ('Patient 4','6-Month'),
  ('Patient 4','Start'),
  ('Patient 5','6-Month'),
  ('Patient 6','Start'),
  ('Patient 6','End'),
  ('Patient 7','6-Month');

And I'm trying to get this result:

patientname
Intervalname1
Intervalname2
Intervalname3

Patient 1
End

Patient 2
Start

Patient 3
Start

Patient 4
End
6-Month
Start

Patient 5
6-Month

Patient 6
End
Start

Patient 7
6-Month
Comment: Thanks for the welcome. I updated my answer based on (new information, new requests, clarifications)
Answer: The SQL engine is probably complaining about the reference in the GROUP BY clause.  Change that to
GROUP BY patientname, CAST(IntervalName as varchar(max))

although, it's odd that you're using GROUP BY when there is no aggregation.
And I'm not sure the widow function you're using is in the correct context.  The ORDER BY doesn't seem meaningful.
I could be sure if you had posted code to produce the table and sample data.
Comment: Question was edited to provide with more information
Comment: I don't see CREATE TABLE and INSERT statements
Comment: I have provided the statements
Answer: You can use Conditional Aggregation after deriving ordinal values for each interval through use of ROW_NUMBER() window function within a subquery such as
SELECT patientname,
       MAX(CASE WHEN rn = 1 THEN intervalname END) AS intervalname1,
       MAX(CASE WHEN rn = 2 THEN intervalname END) AS intervalname2,
       MAX(CASE WHEN rn = 3 THEN intervalname END) AS intervalname3
  FROM
  ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY patientname
                                      ORDER BY patientname) AS rn
      FROM vwPatientPEIOutcomes ) AS p
 GROUP BY patientname
 ORDER BY patientname

Demo


Right click on JButton to lock it and change its colour Java

Question: I am a beginner at java so am attempting to create a minesweeper game. I have a grid full of JButtons that when clicked reveal numbers or mines.
I want to add "flags" so when I right click on any button it changes colour - showing it has been flagged and is 'locked' so it cannot be clicked on unless right clicked.
Here are my buttons
public void buttons()
{
    // Creating the grid with buttons
    grid.setLayout(new GridLayout(20,20));
    // Button grid
    for (int x = 0; x < buttons.length; x++)
    {
        for (int y = 0; y < buttons.length; y++)
        {
            buttons[x][y] = new JButton();
            buttons[x][y].addActionListener(this);
            grid.add(buttons[x][y]);
        }
    }

I attempted to create this right click functionality but I am currently stuck and would like some help.
public void flag()
{
    buttons.addMouseListener(new MouseAdapter()
    {
        public void mousePressed(MouseEvent e)
        {
            JButton rightClick = new JButton("Right Click");
            rightClick.addActionListener(this);
        }
    });
}

Comment: and by being 'stuck' you mean what exactly?
Comment: I'm not sure how to go about doing this (right-clicking a button and when you do it changes colour). I am aware that I need MouseListeners and MouseAdapters but I'm not sure how
Comment: check out `MouseEvent` http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseEvent.html - you will need to detect clicking of button 2
Answer: Typically, you would process user events on a button via the button's ActionListener, what you want to try and do is stop the user from trigger the buttons ActionListener, the easiest way that you can do this is disable the button...
Normally, I don't like using MouseListeners on buttons as this is not normally the best way to ascertain user interaction, but in this case, it's the requirement
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JButton btn;

        public TestPane() {

            setBorder(new EmptyBorder(8, 8, 8, 8));

            setLayout(new GridBagLayout());
            btn = new JButton("O");
            btn.setMargin(new Insets(8, 8, 8, 8));
            add(btn);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("You clicked me");
                }
            });

            btn.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (SwingUtilities.isRightMouseButton(e)) {
                        btn.setEnabled(!btn.isEnabled());
                        if (btn.isEnabled()) {
                            btn.setText("O");
                        } else {
                            btn.setText("X");
                        }
                    }
                }
            });

        }

    }

}


What is values of exponential in complex plane

Question: I have a doubt about value of $e^{z}$ at $\infty$ in one of my book they are mentioning that as $\lim_{z \to \infty} e^z  \to \infty $
But in another book they are saying it doesn't exist.I am confused now
As we can see $e^{z}$ is entire function then as $z \to \infty $ then $e^{z}$ must go to $\infty$
Please help.
Comment: In general if a limit tends to $\infty$ it's said to not exist, since $\infty$ is not a number!
Comment: @edm I thought the question was more simple, thanks for clarifying that to me!
Comment: @RScrlli There is such thing as meromorphic functions. It is ok to ask whether the limit $\lim\limits_{z\to\infty}f(z)=\infty$ holds for a meromorphic function. Exponential function is not meromorphic at $\infty$ anyway.
Answer: $|e^{i2\pi n}|=1$  for all $n$  and $|i2\pi n| \to \infty$. So it is not true that $|e^{z}| \to \infty$ as $|z| \to \infty$. Of course the limit is $\infty$ when you take limit through $\{1,2,..\}$ so the limit of $e^{z}$ as $|z| \to \infty$ does not exist.
Answer: $e^z$ has an essential singularity at $z=\infty$ so we would not say $\lim\limits_{z\to\infty}e^z=\infty$, but instead we say the limit does not exist.
Answer: In real analysis,
$$
\lim\limits_{x\to\infty}e^x=\infty
$$
because the limit is taken along the positive real axis. Similarly,
$$
\lim\limits_{x\to-\infty}e^x=0
$$
because the limit is taken along the negative real axis.
However, in complex analysis, $\infty$ is taken to be the point added to make the one-point compactification of the complex plane (the Riemann Sphere). $e^z$ takes on all non-zero complex values in any neighborhood of $\infty$. Therefore, $\lim\limits_{z\to\infty}e^z$ does not exist.
Answer: I think $e^x$ goes to infinity, while $e^z$ or $(e^i)^x$ spins around the unit circle at the rate of the distance around a unit circle.
The letter 'z' could mean Real Integer or Complex number:
z = integers = ( -inf, ..., -2,-1,0,1,2....inf)
z = complex = x + iy
Which are you referring to?
Answer: Unless you are working on extended complex plane i.e. $\mathbb C\cup$ {$\infty$}, you can use the substitution $z=\frac{1}{w}$ and investigate the behaviour at $w=0$.
$e^{1/w}$ has essential singularity at $w=0$ and Big Picard's theorem says that it will take all values on $\mathbb C$ in the neighborhood of $w=0$ with atmost one exception.


SSH Script with encrypted passwords

Question: I have the following script to SSH into a server with wheel user. It is a test script that I want to use in many servers and applications. But rather than giving the passwords as plain text inside the script I want it to be hidden or encrypted and then decrypted when the script is run.
<code>#!/usr/bin/expect -f

set timeout 2

set ip 78.47.1xx.xx
set port 22
set rootpwd adgajfgjagf
set wuser winner
set wpwd winner#@!

spawn ssh -l $wuser $ip -p $port
            expect -re "connecting (yes/no)?" {
            send -- "yes\r"
            }
            expect -nocase -re "password:" {
            send "$wpwd\r"
           }

        expect "# " {
        send  -- "su - root\r"
            expect "Password: "
            send -- "$rootpwd\r"
            interact
        } ## Heading ##
</code>
Answer: Why dont you use ssh key login instead?
For every machine you want to be able to connect, you have to ask for their public ssh-key and add them to autorized_keys. Then when connectig via ssh, those machines do not need to enter a password.
source: http://sshkeychain.sourceforge.net/mirrors/SSH-with-Keys-HOWTO/SSH-with-Keys-HOWTO-4.html
Comment: Yeah.. I know I can do that but I need for some other purpose where I am not privileged to use ssh keys.
Answer: In the past, I've had to make do with obfuscation (yencode) and file permissions.

SSH Script with encrypted passwords


Server Deployment of Economist.com

Question: As documented here, it seems the Economist is using Drupal for most of it's site.  I am just curious if anyone has information on the number of servers and their config.  Any idea?
Comment: What are you trying to learn from this question? Knowing about their configuration won't help you with yours if you don't know WHY they used that configuration. i think you'd get a better answer if you revised to question to include what you're specifically looking to learn about.
Comment: This question appears to be off-topic because it is about particular website and it will not help any future visitors.
Answer: They have 2 Varnish servers, 10 web servers and 4 database nodes (2 master, 2 slave)
Their workflow is Trunk -> Stage -> Live, from bzr.
They are fully Drupal for a month or so, now.
See The Economist: An Informal Technical Case Study session video from DrupalCon London for more information on their processes.

Server Deployment of Economist.com


Non-Parametric statistical test for non independent repeated measure discrete data

Question: I am working with a dataset the table form of which is as follows
                           Y
                     -----------------
  X                  y1             y2
  -------------------------------------
  1                  68             138
  2                  10              30
  3 or More          11              14

Both Y and X are discrete. Y has two levels y1, y2. X has three levels 1, 2, 3 or more
The data is non-independent.
What is the most appropriate statistical test if my goal is to simply determine if X and Y are related or not ? Thanks.

This is what I mean by data is non-independent.
A person could respond twice or be counted twice. The person's response can be counted once under X=2, Y1 -> 10 and his second response can be counted under X=1, Y2 -> 138 cell.
Answer: Just from what you say, I would suggest a chi-squared test
of independence. I assume you have 271 independently chosen
subjects sorted into row and column categories as shown.
TBL = cbind(c(68,10,11),c(138,30,14));  TBL
     [,1] [,2]
[1,]   68  138
[2,]   10   30
[3,]   11   14

A chi-squared test of independence is computed in R statistical
software as shown below. The P-value is $0.2824 > 0.05,$ so the null hypothesis (independence) cannot be rejected at the 5% level.
chi.out = chisq.test(TBL);  chi.out

        Pearson's Chi-squared test

data:  TBL
X-squared = 2.5291, df = 2, p-value = 0.2824

Observed counts are the counts in the six cells of TBL.
chi.out$obs
     [,1] [,2]
[1,]   68  138
[2,]   10   30
[3,]   11   14

Expected counts are computed under the assumption of independence. Look in your textbook or online to see the rationale for how this is done. Briefly, the expected count
in the upper-left cell is found as row total times column total
divided by grand total. That is. $\frac{206 \cdot 89}{271}\approx  67.65.$ All six, expected counts are shown below:
chi.out$exp
          [,1]      [,2]
[1,] 67.653137 138.34686
[2,] 13.136531  26.86347
[3,]  8.210332  16.78967

The Pearson residuals are of the form $R_{ij}=\frac{X_{ij} - E_{ij}}{\sqrt{E_{ij}}}.$ Roughly speaking they measure how
well the observed counts $X_{ij}$ and the expected counts
$E_{ij}$ agree in each of the six cells. The chi-squared
statistic $Q = \sum_{i=1}^3\sum_{j=1}^2 R_{ij}^2 \approx 2.53.$
 (Denoted X-squared in the output.)
In particular, $R_{11} = (68 - 67.653)/\sqrt{67.653}
 \approx 0.042.$
chi.out$resi
            [,1]        [,2]
[1,]  0.04217107 -0.02948994
[2,] -0.86538484  0.60515774
[3,]  0.97358112 -0.68081866

If the null hypothesis is true, then $Q \stackrel{aprx}{\sim} \mathsf{Chisq}(\nu = 2),$ where the degrees of freedom is $\nu = (r-1)(c-1) = (3-1)(2-1) = 2,$ (provided that there is enough data for all expected counts to exceed 5). In order to be significant at
the 5% level, the test statistic $Q$ must exceed the critical value $c = 5.99.$
qchisq(.95, 2)
[1] 5.991465

If the null hypothesis were rejected (with $Q \ge 5.99),$
it would be worthwhile to look at the individual residuals. Residuals larger than about 2 in absolute value indicate
cells in which there is especially poor agreement between observed and expected counts.
Comment: @BruceET, i apologies the data is not independent. There are 267 unique subjects in this study. Some subjects responded twice. So their response is double counted and I have provided an example by updating my question above. Sorry for not making this obvious.
Comment: Is it possible to use a Cochran–Mantel–Haenszel chi-square test here?
Comment: Suggest you count the 271 - 267 = 4 double-counted subjects only once: Perhaps in the cell with only 10 observed counts, perhaps reduce the cell with 10 and the cell with 128 to 8 and 126 respectively. // Formally, that might make the chi-squared test 'legal', but results still would not be significant. (And in any formal presentation of the data, say what you did.) // In the future, try to plan so such double-counting can't occur. // The time to think about data analysis is before you start taking data.
Comment: @BruceET, I agree. Thanks Bruce.


Can browse the URL in IE but unable to ping

Question: <code>public static string GetAccessErrorString(string uri)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }
        catch (Exception e)
        {
            return e.Message;
        }

        return null;
    }
</code>
I am just trying to check the accesibility of a website in above code. I get below error when GetResponse method is invoked.

at System.Net.HttpWebRequest.GetResponse()
    at WebStuff.WebsiteReachable.GetAccessErrorString(String uri, WebProxy proxy)
  in WebsiteReachable.cs:line 22
Error : The remote name could not be resolved: 'www.microsoft.com'

I added this in host file and tried but it did not work too.
Actually I am able to browse the site in IE. When I give ping www.microsoft.com I get below message

*Ping request could not find host microsoft.com. Please check the name and try
  again. *

Could you please help me figuring out the issue?.. If you could point out different possibilities that will be great.
Comment: Have you tried using the full URI "http://www.microsoft.com"? And I believe MS have blocked ping to their servers so that wouldn't work regardless.
Comment: You are right. When I tried pinging microsoft.com I don't get response but I get response when I run the code in my local machine. I face this issue in the VM.
Answer: You are probably running this code behind a proxy server which needs authentication and Internet Explorer is configured to use this proxy while your code isn't.
Answer: Just to add on to Darin's answer. You can use the Proxy property to set the proxy server if proxy server is the issue.
By default your code should use the proxy settings of your Internet Explorer.


When can a goalkeeper take the ball into their hands?

Question: A goalkeeper cannot handle the ball if a teammate passes ball to them.
But can the goalkeeper take the ball into their hands if it is deflected from the leg? Also, can they take the ball in their hands from a teammate's throw-in?
Comment: The IFAB Laws of the Game uses *singular they* - in fact, this was one of the changes in the recent rewrite. I believe we've [had this discussion before in meta](https://sports.meta.stackexchange.com/questions/607/should-gender-neutral-pronouns-be-replaced-with-male-ones). I think the consensus was that it didn't really matter - I just have the habit of using *singular they* and must have unconsciously made the change when originally editing the question.
Comment: @gdrt I've rolled back your edit here - "goalkeeper" rather than "goalkeepers" is correct, and the rules apply equally to female players.
Comment: @Philipp Kendall, shouldn't it then at least be *goalkeepers* instead of *a goalkeeper* when *their* is used? I think *singular they* is acceptable in informal speech, but not that much in formal writing.
Answer: Law 12 - Fouls and Misconduct, Section 2 - Indirect Free Kick outlines when a goalkeeper may not deliberately handle the ball1 in their own penalty area.

An indirect free kick is awarded if a goalkeeper, inside their penalty area, commits any of the following offences:
...

touches the ball with the hands after:

releasing it and before it has touched another player
it has been deliberately kicked to the goalkeeper by a team-mate
receiving it directly from a throw-in taken by a team-mate

Your question begins with the assumption that the goalkeeper may not deliberately handle the ball after it is passed to them by a teammate.
This is not entirely correct, as the goalkeeper may in fact deliberately handle the ball after it is passed to them by a teammate. The only time they may not do so is when that pass is a kick (i.e. played with the foot). Headed passes, and passes with the chest, knee, thigh etc. are able to be handled legally.
A deflection from the leg is legal for the goalkeeper to handle for two reasons:

Firstly, if it is a deflection, it has not been deliberately kicked to the goalkeeper. (This is also the case for deflections off the foot.)
Secondly, if it is played with leg there can be no offence. Only deliberate kicks to the goalkeeper are illegal to handle, and kicks are made with the foot, not the leg2.

Finally, as seen above, deliberately handling the ball after receiving it directly from a throw-in taken by a teammate is also an indirect free kick offence.
It is also worth noting that the goalkeeper can never be cautioned or sent-off for handling the ball in their own penalty area - an indirect free kick is the maximum punishment. Law 12 - Fouls and Misconduct, Section 1 - Direct Free Kick:

Inside their penalty area, the goalkeeper cannot be guilty of a handling offence incurring a direct free kick or any related sanction but can be guilty of handling offences that incur an indirect free kick.

For completeness, when the ball is wholly outside the penalty area, the goalkeeper, like any other player, may not deliberately handle the ball as also noted in 12.1:

The goalkeeper has the same restrictions on handling the ball as any other player outside the penalty area.

1 - although the Law says "touches the ball with hands", not "deliberately handles", it is understood that to breach this Law, it must be a deliberate handling as implied in both the first sentence and final paragraph of Law 12, Section 1.
2 - the goalkeeper is taking a big risk by handling a ball that has been deliberately played to them from a teammate's lower leg, as the referee may (wrongly) believe it has come off the foot and award an indirect free kick to the opposing team.
Comment: What's the definition of "handling"? Touching with one's hand? Grabbing it?
Comment: @Santropedro A player handles the ball when their arm or hand makes contact with the ball. This would including grabbing the ball, parrying it away with the hands, or blocking the ball with their arm. Only deliberate handling should be punished (like the direct free kick offence for outfield players and goalkeeper outside of their penalty area in Law 12, Section 1).
Answer: Your two questions will be answered by the IFAB laws of the game Law 12 - Fouls and Misconduct.

Can he take the ball if the ball is deflected from the leg?

Concerned rule:
  Goalkeeper touches the ball with his hands after it has been deliberately kicked to him by a team-mate.

Deliberate being the key word. Since, the ball deflected from the leg is not deliberate. He can take the ball.

Can he take the ball if a team mate does the throw in to the goalkeeper?

Concerned rule:
  Goalkeeper touches the ball with his hands after he has received it directly from a throw-in taken by a team-mate.

In this case he can't take the ball.
Doing the things mentioned in rules will result in an indirect free kick for opposite team, when goalkeeper is inside his own penalty area.
Other sources: Quora
Answer: The goalkeeper cannot pick the ball up when it has been intentionally passed back to them, except via the head or chest. They also cannot drop the ball from their hands and then handle it again before anyone else has touched it.
Reference: Fouls and misconduct (thefa.com)
Comment: Please verify 2nd part of answer because keeper can drop the hard struck ball into ground to dissipate force and then handle the bounced ball immediately.
Comment: Deflecting a hard shot to the ground, then catching it, is not dropping it! The laws also explicitly make this clear, in Law 12.2: *"A goalkeeper is considered to be in control of the ball when:

the ball is between the hands or between the hand and any surface (e.g. ground, own body) or by touching it with any part of the hands or arms **except if** the ball rebounds accidentally from the goalkeeper or **the goalkeeper has made a save**"*.
Comment: @Nij is right that an accidental rebound / save is not the same as dropping it. However, the goalkeeper also can drop the ball and rehandle it - as long as they recatch it after a bounce. The goalkeeper may bounce the ball as much as they like and maintain control (but the six seconds is ticking the entire time). Also in [12.2](http://theifab.com/laws/fouls-and-misconduct/chapters/indirect-free-kick): *A goalkeeper is considered to be in control of the ball when: ... **bouncing it on the ground or throwing it in the air***
Comment: I'd argue that the distinction between head/chest and any other part of the body is not entirely correct. Passes from knee and thigh can also be handled. In fact, the goalkeeper can handle the ball when it is deliberately played to them from any part of a teammate's body except the foot.
Comment: There is a caveat to this law, if an outfield player attempts to circumvent the law by trickery - eg heading the ball by kneeling down whilst its on the floor - its also an indirect free kick if the keeper handles it. Outfield player cautioned.
Answer: If the ball is deflected from the leg truly accidentally (and is seen as so by the official) then it is okay for the keeper to use his/her hands. A keeper can only use his/her hands to pick up the ball if the the ball has been passed by a teammate via their head or chest.
The keeper cannot pick up the ball directly off of a friendly throw in.
Comment: *"A keeper can only use his/her hands to pick up the ball if the the ball has been passed by a teammate via their head or chest."* This is certainly not true. What about the knee or thigh? What about the shin?


Finding a vector normal to the plane with position point and parallel to two vectors

Question: A cross product of the two parallel vectors will get the vector normal to the plane. But I'm looking for a specific normal vector.
The plane with point $A(3,2,1)$ and parallel to $u = 5i+2k$ and $v= 3i+j+2k$
The normal vector will need to be of the form $n = (a,4,b)$ so we will need to find the value of $a$ and $b$.
Comment: Well, you could find a normal vector via the cross product and then scale it so that the second component is 4.
Answer: Exactly what StrangerLoop recommends you to do. As any scalar multiple of the normal vector will still be normal, you can multiply it with any constant (that is called scaling) and still have a normal vector. You wrote the cross product was (4,10,-1) ,without checking if that is correct you can now say that also the vectors (4/10,1,-1/10) and therefore (1.6,4,-0.4) are orthogonal to the plane
Answer: Use the cross product to find a vector  $v$ normal to the plane.  Any scalar multiple of this vector is also normal to the plane.  So solve $c v = n$ for the scalar $c$, and you're done.
Comment: Sorry I don't know how to scale. The cross product of $u$ and $v$ is (4,10,-1) and then what?
Comment: Solve $(4c,10c,-c)=(a,4,b)$ for $c$.  You get $c=4/10=2/5$.
Answer: Since $\vec{n}$ will have to be orthogonal to both $\vec{u}$ and $\vec{v}$, you'll need $5a+2b=0$ and $3a+4+2b=0$.  Those two equations will have a unique solution, allowing you to find $a$ and $b$.
An alternative would be to take $\vec{u}\times\vec{v}$ and scale it so that the resulting middle component is $4$.


Why are vectors $X_2$ and $X_3$ bivariate normally distributed?

Question: I have a stochastic vector $\mu = \begin{bmatrix}1 \\ 0 \\ 1\end{bmatrix}$ and $\Sigma= \begin{bmatrix}1 & 0 & -1\\0 & 2 & 0 \\ -1 & 0 & 3\end{bmatrix}$.
I have to proof that $X_2$ and $X_3$ are independent. I can tell from the covariance matrix that $\operatorname{Cov}(X_2,X_3) = 0$, but the solution manual also states that $X_2$ and $X_3$ have the property of being bivariate normally distributed.
How can I tell this is the case? The proof for this seems way more complicated than these simple matrices suggest.
Comment: Maybe this is just me not understanding the field, but it seems like some information is missing - how are $\mu$ and $\Sigma$ related to $X_2$ and $X_3$?
Comment: The first sentence is absurd: neither $\mu$ nor $\Sigma$ are stochastic.
Answer: What is the definition of the 'stochastic vector' $\mu$? It looks like the stochastic vector is supposed to have normally distributed components. If this is the case, then any linear combination of its components (eg a component of $\Sigma \mu$) is also normally distributed.
Answer: The definition of $X=(X_1,\ldots,X_n)$ following a multivariate normal distribution is that
$$
\sum_{i=1}^n a_iX_i
$$
follows a (one-dimensional) normal distribution for all choices of $a_1,\ldots,a_n\in\mathbb{R}$.
Now, assume that $(X_1,X_2,X_3)$ is multivariate normal distributed, which by definition means that
$$
a_1X_1+a_2X_2+a_3X_3
$$
is (one-dimensional) normal distributed for all choices of $a_1,a_2,a_3\in\mathbb{R}$. Let's show that $(X_1,X_2)$ indeed follows a multivariate normal distribution as well. To that end, let $a_1,a_2\in\mathbb{R}$ be arbitrary. Then
$$
a_1X_1+a_2X_2=a_1X_1+a_2X_2+a_3X_3
$$
with $a_3=0$ and since the right-hand side is normal distributed then so is the left-hand side. Since $a_1$ and $a_2$ were arbitrary, we are done.


Receive Android GCM messages so slow?

Question: Google Cloud Messaging (Push message) problem.
I have two smartphones(HTC Sensation XE, Desire HD) and a tablet(Samsung Galaxy Note 10.1 Wifi).
Sometimes I need to wait for almost 15 minutes to receive the GCM push messages. Sometimes I receive the GCM push messages immediately(within 30 secs).
Is it normal? Or just because I'm under Wifi connected?
If it is normal, are there any other services like "long-polling" I can use for retrieving messages from server?
I'm currently using GCM+Polling(AlarmManager) to retrieve messages from remote server.
Any suggestions or better ideas?

Below is my test result:
The left side is server send time, while the right side is client mobile receive time.
All the test results are under Wifi connected environment.
==========================
HD
23:10:18, 23:24:XX
XE
23:11:21, 23:22:44
Note
23:10:20, 23:14:54
==========================
HD
00:08:12, 00:08:27
XE
00:07:55, 00:07:58
Note
00:08:04, 00:13:35
==========================
HD
00:40:21, 00:55:22
XE
00:39:56, 00:40:14
Note
00:40:13, 00:40:59
Thanks!!
Comment: Have you tried setting the `time_to_live` parameters to 0? As outlined in the docs it will work hardest to send asap: https://developer.android.com/google/gcm/adv.html#ttl
Answer: GCM uses throttling when there's excessive use, see the following document for more details:
http://developer.android.com/google/gcm/adv.html#throttling
Answer: Please read my answer here:
Google Cloud Messaging - messages either received instantly or with long delay
It's basically a tcp timeout problem
Answer: You can manually trigger the heartbeat to keep the connection alive by the following code. Some network routers will automatically kill the idle socket connections if it is idle for a particular time period (sometimes 5 minutes). Execute the code in every 5 minute so that the connection will be re-established if it is closed. But, obviously reducing the interval will consume bit more battery (I don't know how much it is relevant here because nowadays the smart phones come up with high mAh battery).
<code>getApplicationContext().sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
getApplicationContext().sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
</code>

Receive Android GCM messages so slow?


How to get y_hat using predict() when both response variable and explanatory variables are log transformed?

Question: I have a log-log linear function as:
lom1 = lm(log(y)~log(x1)+log(x2),data=mod_dt)

I want to get y_hat using the same data set and I did
yhat = exp(predict(lom1))

Result seems off a lot (from comparing with the y-hat I calculated manually in R).
Any reason?
The second related question is, I first added three more columns in the original data set mod_dt for the log transformations of y, x1 and x2. Say, they are named as logy, logx1 and logx2, and then I ran lm:
lom2 = lm(logy ~ logx1 + logx2, data=mod_dt)

This gives a different set of coefficients.
Can this give a correct y-hat by doing
exp(predict(lom2))

Many thanks in advance.
Comment: Taking the exponential should give you correct forecasts, and the two procedures you describe should give the same coefficients and forecasts. But without reproducible code (with data), we cannot tell what went wrong.
Answer: When a model such as your formula is estimated, it translates to Y ~ X1 * X2 on the untransformed scale. You will need to provide data for examination if you want to get more specific review of your results.
Answer: It's not an answer exactly. Just want to share some of my opinions. A linear regression model assumes E(y) = x * beta. If y is transformed by log, it becomes E(log(y)) = x * beta. However when we try to predict y, usually we don't have exp(E(log(y))) = E(y)
Comment: Agreed, the log-log regression gives you elasticities as coefficients, what is fitting is a function of the form y = x^b which is different from y = bx


How to select distinct values for two and return all columns?

Question: I want to select distinct values from two columns.
Example data:
ID TITLE SOURCE TARGET
1  asd   12      2
2  asd1  123     125
3  asd1  123     56
4  asd2  123     125
5  asd3  164     146

I want to get distinct data for source and target columns ID - 2 and ID - 4 are duplicates.
ID TITLE SOURCE TARGET
1  asd   12      2
2  asd1  123     125
3  asd1  123     56
5  asd3  164     146

Comment: Edit your question and show the results you want.
Answer: If you just want the distinct values, use select distinct:
select distinct source, target
from example t;

If you want the rows where the source/target only appears on one row, then one method uses window functions:
select t.*
from (select t.*,
             count(*) over (partition by source, target) as cnt
      from example t
     ) t
where cnt = 1;

Comment: @Goku . . . I have no idea.  There seem to be plenty of Stack Overflow users who like to downvote without specifying why.  Just consider it a badge of honor.
Comment: Thank you for prompt response, I want to select all column where the source/target only appears on one row. I change "from t" to my real table name but, I got: ORA-00904: "T": invalid identifier
Comment: Don't change `t` to your real name, but `example`.
Comment: @Goku . . . I edited the answer using `example` as the name of your table.
Comment: Why I got two negative votes on this question?