Proving $\lim_{x \to 0} \frac{1}{x}$ does not exist by contradiction - the case where we assume the limit L < 0.

Question: I'm looking at a proof in a textbook that shows that $ \lim_{x \to 0}\frac{1}{x} $ does not exist. This is a paraphrase of the proof:
So, we want to show that there exists an $\epsilon>0$, such that for each $\delta >0$, there
is some $x \in \mathbb{R}-{0}$, such that $|x-0| < \delta$, but $|\frac{1}{x}-L|\geq \epsilon.$ There are three cases, depending upon whether $L > 0$, $L = 0$, or $L < 0$. Suppose $L>0$.
Then we have $\frac{1}{x} - L\geq \epsilon$, which is the same as $\frac{1}{x} \geq L + \epsilon$, and so we need $x \leq \frac{1}{L+\epsilon}$. Since $L >0$, the last step
works with any choice of $\epsilon$. We also need to have $|x-0| < \delta$, and so
we will choose $x = min\left\{\frac{\delta}{2},\frac{1}{L+\epsilon}\right\}$.
We will not give the full details of the cases where $L < 0$ and where $L = 0$, except to note that when $L < 0$ we need to choose some $\epsilon > 0$ so that $L+ \epsilon < 0$, for example we could choose $\epsilon = \frac{|L|}{2}$.
For the life of me I can't understand why for the case of $L<0$, we must have $L+\epsilon <0$. I've tried playing around with the inequality and plugging in real numbers, and nothing is clicking. I'm sure it's something simple, but I just can't see it. Please know that I have looked at other proofs for this specific limit (or lack thereof) on here, and it still doesn't make sense.
This is the proof they did for $L>0$:
Suppose that $\lim_{x\to 0} \frac{1}{x} = L$ for some $L \in \mathbb{R}.$ Let $\epsilon = \frac{|L|}{2}$ if $L \neq 0$, and let $\epsilon = 1$ if $L = 0.$ We consider the case when L > 0; the other cases are similar,and the details are left to the reader. Let $\delta > 0.$ Because $L > 0$, then $L+\epsilon > 0$. Let $x = min\left\{\frac{\delta}{2},\frac{1}{L+\epsilon}\right\}.$ Then $x \in (0,\infty)$ and $|x-0| \leq \frac{\delta}{2} < \delta.$ On the other hand, because $x\leq \frac{1}{L+\epsilon}$, it follows that $L + \epsilon \leq \frac{1}{x}$, and hence $\frac{1}{x} - L \geq \epsilon.$
Okay, so this makes sense to me. But could anyone help me with the proof for the case of $L<0$. I know there are probably better ways, but I want to understand within the context of the book. This is not homework, but self-study.
Thank you!
Comment: It's not that *all* $\epsilon$ are such that we have $L +\epsilon <0$.  It's that of all the $\epsilon$ we can choose (and we can choose *any* $\epsilon \in (0, \infty)$. There are *some* we *could* choose where $L + \epsilon < 0$.  For example why don't we just choose $\epsilon =\frac {|L|}2$.  That $>0$ and less than $|L$ so $L +\epsilon -L + \frac {|L|}2 = \frac {L}{2} < 2$, isn't it.  Or we could choose $\epsilon = 10^{-100}\cdot |L|$. Then $L +\epsilon =L +10^{-100}|L| = (1-10^{100})L < 0$.
Comment: Thank you, fleabood. The textbook's insistence on the constraint $L + \epsilon <0$ really threw me off. These $\epsilon-\delta$ proofs get confusing because the $\epsilon$ sometimes seem to appear out of nowhere.
Answer: Since you are interested in a $\epsilon, \delta$ proof, when $L < 0$, this is how I would approach it.
Suppose that $L < 0$.  Then I have to find some fixed value of $\epsilon > 0$, so that no matter what value of $\delta > 0$ is chosen, I will always be able to find at least one value of $x$ such that both of the following are true:
$0 < |x - 0| < \delta$ and $|L - (1/x)| > \epsilon$.
I will arbitrarily choose $\epsilon = 2|L| = -2L,$ since $L < 0.$
Since I want the normal constraint against $\epsilon$ violated:
I want $|L - (1/x)| > -2L$.
Here, to simplify matters, I will arbitrarily decide that I will find a value of $x$ that is positive and such that
$0 < |x - 0| < \delta \implies 0 < x < \delta.$
Also, since $x$ is positive, $|L - (1/x)| = (1/x) - L.$
Therefore, I have to prove that no matter how small (positive) $\delta$ is taken, I can find $x$ such that
$0 < x < \delta$ and $(1/x) - L > -2L \implies 1/x > -L \implies
x < -1/L$.
Take $x = \min[(\delta/2), (-1/2L)]$, and you have found a satisfactory $x$.  Since you will always be able to find such a satisfactory $x$, regardless of how small positive $\delta$ is taken, the normal constraint on the specific value of $\epsilon = -2L$ will be violated.
This refutes the assumption that as $x \to 0, (1/x) \to L$.

This is probably the opportune moment to mention that I pulled a fast one.  My analysis started with a constraint to be violated, and then said that if it is violated, then
$x = \min[(\delta/2), (-1/2L)]$ appears to work.
To be rigorous, you need to manually check that the chosen value of $x$ is satisfactory.  This step is usually skipped in continuity proofs, but is still a good idea.
Take $x = \min[(\delta/2), (-1/2L)].$
Then, $0 < x \leq (\delta/2) \implies 0 < |x - 0| < \delta.$
Also $0 < x \implies |L - (1/x)| = (1/x) - L.$
$0 < x \leq (-1/2L) \implies 0 < x < -(1/L) \implies
(1/x) > -L \implies 1/x - L > -2L$, as required.

An explanation of my overall thinking is called for.  In a general demonstration of this type, the logic usually goes:
Constraints $\implies$
Step 1 $\implies$
Step 2 $\implies$
Step 3 $\implies$
Step 4 $\implies$
Step 5 $\implies$
Specification.
This means that if the Constraint is satisfied, the Specification is implied.  However, you normally want the reverse implication that if the Specification is followed, the Constraint will be satisfied.
This is normally handled in one of three ways.

blithely assume that all implications were two way implications (i.e. $\iff$ instead of $\implies$).  This is in fact almost always true.

Actually go to the trouble of checking each step to manually verify that the two way (i.e. $\iff$) implication held from the previous step to this step.

Take the very unusual approach that I took of treating the specification as a candidate specification and manually verifying that it works.

Addendum
Responding to the Paramanand Singh's comments following this answer.
If I understand your strategy  for showing/disproving continuity,
it may be represented by:
Constraint : $~\impliedby$
Step 1 : $~\impliedby$
Step 2 : $~\impliedby$
Step 3 : $~\impliedby$
Step 4 : $~\impliedby$
Step 5 : $~\impliedby$
...
Specification
I agree that your strategy for showing/disproving continuity is valid.
However, I disagree that it is the only valid approach or that it is the easiest
valid approach.
My approach is as follows:
Constraint : $~\implies$ or suggests
Step 1 : $~\implies~$ or suggests
Step 2 : $~\implies$ or suggests
Step 3 : $~\implies$ or suggests
Step 4 : $~\implies$ or suggests
Step 5 : $~\implies$ or suggests
...
Candidate Specification.
Then, I manually verify that Candidate Specification $~\implies~$ Constraint.
This approach is also valid, because of the trailing manual verification.
The mathSE query that you linked to involved showing that
$~\lim_{x \to 3} x^2 = 9.$
I will illustrate my alternative approach with this particular problem.
Constraint:
$~0 < |x -3 | < \delta \implies |x^2 - 9| < \epsilon$.
Derived (i.e. suggested or implied) steps:
$- \delta < x -3 < \delta.$
$3 - \delta < x < 3 + \delta. $
$9 - 6\delta + \delta^2 < x^2 < 9 + 6\delta + \delta^2.$
$ - 6\delta + \delta^2 < (x^2 - 9) < 6\delta + \delta^2.$
To simplify the above suggested (i.e. derived) step, I will
introduce the artificial contrivance that $\delta \leq 1.$
This will allow me to assume that $\delta^2 < \delta.$
This leads to the derived step:
$-6 \delta < -6\delta + \delta^2 < (x^2 - 9) < 6\delta + \delta^2 < 7\delta.$
What I want is that
$-\epsilon < (x^2 - 9) < \epsilon$.
The above analysis suggests that this is achieved by having
$\delta \leq 1$ and $\delta < (\epsilon/7)$.
This is achieved by the Candidate Specification of
$\delta = \min(1, \epsilon/10)$.
It now remains to manually verify that the Candidate Specification does in fact imply that
$0 < |x-3| < \delta \implies |x^2 - 9| < \epsilon$.
This is equivalent to verifying that when $x \neq 3$ and
$- \delta < (x-3) < \delta$, then $-\epsilon < (x^2 - 9) < \epsilon.$
Test the Candidate Specification:
$\delta = \min(1, \epsilon/10)$.
This specification, along with the presumption that $0 < |x-3| < \delta$
implies the following:
$\delta \leq 1~~$ and $~~\delta \leq (\epsilon/10).$
$x \neq 3~~$ and
$~~ [-\delta < (x-3) < \delta] ~~\implies~~
[3 - \delta < x < 3 + \delta].$
Therefore
$9 - 6\delta + \delta^2 < x^2 < 9 + 6\delta + \delta^2 \implies $
$- 6\delta + \delta^2 < (x^2 - 9) < 6\delta + \delta^2 \implies$
[because $\delta \leq 1$]
$-6 \delta < (x^2 - 9) < 7\delta \implies$
[because $\delta \leq (\epsilon/10)$]
$-\epsilon < (x^2 - 9) < \epsilon,~~$ as required.
Notice that very little thought was involved in the manual verification of the Candidate Specification.  This is because the path from the Specification to the Constraint very closely followed the original derived analysis.  Further, because of this trailing manual verification, there was no need to be concerned whether the reverse implication (i.e. $\impliedby$) held in each step in the derived chain of steps.
This means that I was free to ignore any consideration of the validity of going from one derived step to the next derived step.  Establishing the validity was deferred until a Candidate Specification was computed.
Comment: Why are you trying to think limit definition as a two way implication? This is one of the biggest problems students face by assuming two way implication.
Comment: @ParamanandSingh Yes, it is a common mistake, which was the whole point of my *rant*, at the tail end of my answer.  But the fact is, normal algebraic manipulations are generally two way implications; the *typical* non-2-way implication is something like $x = 2 \implies x^2 = 4$.  Further, the OP needs to know **why** this common mistake is so often committed; in fact, the OP needs to know that there is a potential mistake there.  My answer indicated that.
Comment: @ParamanandSingh Actually, I'm not sure that my last comment was on point to your comment.  You do normally have a Constraint, and you have to derive a specification that satisfies the constraint.  The normal derivation strategy does involve something like if the Constraint is satisfied, then Step 1 is implied, which implies Step2, which implies ...
Comment: @ParamanandSingh Do you disagree?
Comment: I view the overall $\epsilon, \delta$ proof to be written as "$q$ holds if $p$ holds" instead of "if $p$ then $q$". Both these are mathematically same but the first approach is what allows us to write the chain of logical implications in reverse manner. Starting with a target inequality $|f(x) - L|<\epsilon $ (or $|f(x) - L|\geq \epsilon$ for disproving limit) we can form a chain of logical implications in reverse order to arrive at our $\delta $ (or an $x$ for every $\delta$ in case of disproof). Noting that each step is a one way implication (in reverse) gives us a lot of freedom.
Comment: A two way implication on the other hand makes our job tough (essentially solution to certain inequalities via algebraic manipulation). Thus for one way we have "$x^2<4$ if $-1<x<1$" but for two way implication we must have "$x^2<4$ iff $-2<x<2$".
Comment: You may have a look at [this answer](https://math.stackexchange.com/a/3659232/72031) especially the part at the end.
Comment: @ParamanandSingh Please see the Addendum to my answer, which I just added in response to your comments.
Comment: +1 there. I don't see any disagreement here.
Answer: If $L < 0$ and $\epsilon = \frac{|L|}{2}$ then
\begin{align*}
L + \epsilon &= L + \frac{|L|}{2} \\
    &= L + \frac{-L}{2} \qquad\text{(because $L<0$)} \\
    &= \frac{2L-L}{2} \\
    &= \frac{L}{2} \\
    &= \frac{1}{2} L \\
    &< 0 \qquad\text{(because a positive times a negative is negative)}
\end{align*}
If that's not intuitive enough, here's a more geometrical viewpoint.
$L$ is negative, i.e. it lies to the left of $0$. The distance between $L$ and $0$ equals $|L|$. If you add only half that distance to $L$ then what you get still lies to the left of zero. That is, $L + \frac{|L|}{2} < 0$.
Comment: @dorkichar: your textbook authors perhaps wants to say that if you want to have a proof for $L<0$ similar to the case $L>0$ then you **must** use $\epsilon$ such that $L+\epsilon<0$.
Comment: It's not that you *must* choose and $\epsilon$ so that $L + \epsilon < 0$.  It's that you *could* choose such.  And if you *do* choose one the you *will*have $f(x) < 0$.  Which could make things easier.  If you want to show that $|L - \frac 1x|> \epsilon$ and you can have $x$ go all the way to $0$ and past it's not lickly you can say anything. But if have it guarenteened that $x < 0$ then $L -\frac 1x$ is positive and manipuliably large.
Comment: Thank you for sharing your answer, Lee. I understand why $L + \epsilon <0$ if $\epsilon = \frac{|L|}{2}$, but why do they insist that you must pick an $\epsilon$ such that $L + \epsilon <0$? How is that related to the inequality? Sorry if I'm not explaining my confusion well.
Comment: Your use of "must" is indeed not well chosen. There is no "must". One chooses $\epsilon = \frac{|L|}{2}$ because it works. What it means to "work" is that using that value of $\epsilon$ one can prove what one is supposed to prove, namely: for each $\delta > 0$ there exists $x \in \mathbb R - \{0\}$ such that $|x-0| < \delta$ but $|\frac{1}{x} - L| > \epsilon$.
Comment: @fleablood you addressed exactly where my confusion was. Thank you!
Answer: The proof in your book seems to be unnecessarily complicated: as $x \to 0$, $|\frac{1}{x}|$ increases without bound, so $\frac{1}{x}$ cannot have a limit in $\Bbb{R}$.
You can extract an $\varepsilon$-$\delta$ proof from the above. Given any $L \in \Bbb{R}$, if $\epsilon = 1$ and $\delta = \frac{1}{|L| + 1}$, then $|\frac{1}{x} - L| > \epsilon$ for all $x$ with $-\delta < x < \delta$. This means that $\frac{1}{x} \not\to L$ as $x \to 0$


Same as i++ but for more complex operation

Question: I'm not facing any problem. This question is just about C language
Let's say I have a function like:
int func()
{
    static int i = 1;
    return(i++);
}

Now, instead of doing i++ (i+=1) I'd like to do i *= 42; but still return the value before the multiplication.
I'm wondering if there is a way to do it the same way that i++ works (in one expression, take value of i and then do i *= 42).
Comment: Does: `return (i *= 42) / 42;` count? It is neither elegant nor efficient, but does meet the letter of your requirements.
Comment: @JonathanLeffler: If `i * 42` is of a signed type (as it is in the question) and it overflows, then the behavior is undefined -- in practice dividing the result by `42` is unlikely to yield the original value. If `i` is of unsigned type and `i * 42` wraps around, the behavior is well defined, but the result of dividing by `42` definitely won't be the original value.
Comment: @KeithThompson: if `i *= 42` overflows on signed types, all bets are off before you start dividing.  You're right that with unsigned arithmetic, multiply can overflow and it is defined and division will not yield the original answer.  The only way to achieve it fully accurately is with a variable of some sort to preserve the before value, as in BLUEPIXY's answer.
Answer: int func()
{
    static int i = 1;
    int tmp = i;
    i *= 42;
    return tmp;
}

Comment: @IggY There is no such thing as that.
Comment: I'm searching for a different way to do it, without intermediate value, replicating the idea of i++
Comment: @IggY: I second BLUEPIXY in that conclusion.  What he's shown is as near as you can get in C.  By all means go and design and implement your own language with the 'post-multiply' feature, but C dropped the `=*` operator many years ago because it leads to syntactic ambiguity.  Note that the old `=*` operator was identical in function to the modern `*=` operator.
Comment: Hasn't BLUEPIXY posted the answer?  It might need a little bit of explanation, but the answer is here.
Comment: You could wrap it up in a function that does `*=` and returns the previous value
Comment: It seems that it is not the desire of the OP probably.
Answer: Postfix ++ and -- are the only C operators that modify an object and yield that object's previous value. If you want to do that for anything other than incrementing or decrementing by 1, you'll have to store the previous value in a temporary.
If you wanted to design your own language, you could implement a "reverse comma" operator that yields its left operand rather than its right operand. (The existing comma operator evaluates its left operand, then evaluates its right operand, then yields the value of the right operand.)
For example, if the "reverse comma" were spelled ,,, you could do:
return i ,, i *= 42; /* THIS IS NOT C */

Answer: An assignment is an expression is C. So you could code
int func() {
 static int i = 1;
 return(i *= 42);
}

Of course if you wanted to return i before multiplying it you need another variable.
Comment: It would then start at 42, not at 1
Comment: That gives the result of the multiplication, but the increment is a post-increment so the returned value is the value before the operation.  I think that is what is wanted.
Comment: no, foe example return i+=1; instead of return i++; would cause the first value to be 2 instead of 1
Comment: OP: *in one expression, take value of `i` **and then do `i *= 42`***
Comment: @ta.speot.is: how would you do that?


Discretization of probability array in Python

Question: I have a numpy array (actually imported from a GIS raster map) which contains
probability values of occurrence of a species like following example:
a = random.randint(1.0,20.0,1200).reshape(40,30)
b = (a*1.0)/sum(a)

Now I want to get a discrete version for that array again. Like if I have
e.g. 100 individuals which are located on the area of that array (1200 cells) how are they
distributed? Of course they should be distributed according to their probability,
meaning lower values indicated lower probability of occurrence. However, as everything is statistics there is still the chance that a individual is located at a low probability
cell. It should be possible that multiple individuals can occupy on cell...
It is like transforming a continuous distribution curve into a histogram again. Like many different histograms may result in a certain distribution curve it should also be the other way round. Accordingly applying the algorithm I am looking for will produce different discrete values each time.
...is there any algorithm in python which can do that? As I am not that familiar with discretization maybe someone can help.
Comment: "*there is still the chance that a individual is located at a low probability cell.*" - this means you want another random function. How random should it be? Without random function you get always the same result for the same given input.
Answer: Use random.choice with bincount:
np.bincount(np.random.choice(b.size, 100, p=b.flat),
            minlength=b.size).reshape(b.shape)

If you don't have NumPy 1.7, you can replace random.choice with:
np.searchsorted(np.cumsum(b), np.random.random(100))

giving:
np.bincount(np.searchsorted(np.cumsum(b), np.random.random(100)),
            minlength=b.size).reshape(b.shape)

Comment: I am not that familiar with python yet, but I can't get the module (random.choice) working: >>> import numpy
>>> numpy.version.version
'1.6.2'
>>> numpy.random.choice()

Traceback (most recent call last):
  File "", line 1, in
    numpy.random.choice()
AttributeError: 'module' object has no attribute 'choice'
Comment: @Johannes `random.choice` was added in NumPy 1.7; which version do you have? Try my alternative solution if you have 1.6 (check `np.version.version`).
Answer: So far I think ecatmur's answer seems quite reasonable and simple.
I just want to add may a more "applied" example. Considering a dice
with 6 faces (6 numbers). Each number/result has a probability of 1/6.
Displaying the dice in form of an array could look like:
b = np.array([[1,1,1],[1,1,1]])/6.0

Thus rolling the dice 100 times (n=100) results in following simulation:
np.bincount(np.searchsorted(np.cumsum(b), np.random.random(n)),minlength=b.size).reshape(b.shape)

I think that can be an appropriate approach for such an application.
Thus thank you ecatmur for your help!
/Johannes
Comment: I am still not sure if it is correct to use that procedure to simulate e.g. 100 dice rolls?
Answer: this is similar to my question i had earlier this month.
import random
def RandFloats(Size):
    Scalar = 1.0
    VectorSize = Size
    RandomVector = [random.random() for i in range(VectorSize)]
    RandomVectorSum = sum(RandomVector)
    RandomVector = [Scalar*i/RandomVectorSum for i in RandomVector]
    return RandomVector

from numpy.random import multinomial
import math
def RandIntVec(ListSize, ListSumValue, Distribution='Normal'):
    """
    Inputs:
    ListSize = the size of the list to return
    ListSumValue = The sum of list values
    Distribution = can be 'uniform' for uniform distribution, 'normal' for a normal distribution ~ N(0,1) with +/- 5 sigma  (default), or a list of size 'ListSize' or 'ListSize - 1' for an empirical (arbitrary) distribution. Probabilities of each of the p different outcomes. These should sum to 1 (however, the last element is always assumed to account for the remaining probability, as long as sum(pvals[:-1]) <= 1).
    Output:
    A list of random integers of length 'ListSize' whose sum is 'ListSumValue'.
    """
    if type(Distribution) == list:
        DistributionSize = len(Distribution)
        if ListSize == DistributionSize or (ListSize-1) == DistributionSize:
            Values = multinomial(ListSumValue,Distribution,size=1)
            OutputValue = Values[0]
    elif Distribution.lower() == 'uniform': #I do not recommend this!!!! I see that it is not as random (at least on my computer) as I had hoped
        UniformDistro = [1/ListSize for i in range(ListSize)]
        Values = multinomial(ListSumValue,UniformDistro,size=1)
        OutputValue = Values[0]
    elif Distribution.lower() == 'normal':
        """
            Normal Distribution Construction....It's very flexible and hideous
            Assume a +-3 sigma range.  Warning, this may or may not be a suitable range for your implementation!
            If one wishes to explore a different range, then changes the LowSigma and HighSigma values
            """
            LowSigma    = -3#-3 sigma
            HighSigma   = 3#+3 sigma
            StepSize    = 1/(float(ListSize) - 1)
            ZValues     = [(LowSigma * (1-i*StepSize) +(i*StepSize)*HighSigma) for i in range(int(ListSize))]
            #Construction parameters for N(Mean,Variance) - Default is N(0,1)
            Mean        = 0
            Var         = 1
            #NormalDistro= [self.NormalDistributionFunction(Mean, Var, x) for x in ZValues]
            NormalDistro= list()
            for i in range(len(ZValues)):
                if i==0:
                    ERFCVAL = 0.5 * math.erfc(-ZValues[i]/math.sqrt(2))
                    NormalDistro.append(ERFCVAL)
                elif i ==  len(ZValues) - 1:
                    ERFCVAL = NormalDistro[0]
                    NormalDistro.append(ERFCVAL)
                else:
                    ERFCVAL1 = 0.5 * math.erfc(-ZValues[i]/math.sqrt(2))
                    ERFCVAL2 = 0.5 * math.erfc(-ZValues[i-1]/math.sqrt(2))
                    ERFCVAL = ERFCVAL1 - ERFCVAL2
                    NormalDistro.append(ERFCVAL)
            #print "Normal Distribution sum = %f"%sum(NormalDistro)
            Values = multinomial(ListSumValue,NormalDistro,size=1)
            OutputValue = Values[0]
        else:
            raise ValueError ('Cannot create desired vector')
        return OutputValue
    else:
        raise ValueError ('Cannot create desired vector')
    return OutputValue

ProbabilityDistibution = RandFloats(1200)#This is your probability distribution for your 1200 cell array
SizeDistribution = RandIntVec(1200,100,Distribution=ProbabilityDistribution)#for a 1200 cell array, whose sum is 100 with given probability distribution

The two main lines that are important are the last two lines in the code above


NSTimer perfomance of device

Question: I want to run a timer that watches my game for some events that occur during the gameplay.
I would include the timer in the did load function. So the Timer is checking permanently if event1 happened or not.
[NSTimer scheduledTimerWithTimeInterval:0.001
    target:self
    selector:@selector(check_status_event1:)
    userInfo:nil
    repeats:YES];

I also try to set a pointer to the Timer to invalidate when needed.
- (IBAction)check_status_event1:(id)sender
{
    //_stepper_event1_status_check.value (0 = no / 1 = yes)
    if (_stepper_event1_status_check.value == 1) {
        _stepper_event1_status_check.value = 0;  //reset stepper again
        [self event1_go:0];
    }else{}
}

Question:
Is the interval of 0.001 o.k?
Is there a big influence to the device performance? Because there is permanently running an if statement (or more). Does it maybe also make the iPhone or iPad slower, when the game is sent to background via home button?
Can I use more of this timer at the same time? for example when I run 10 or 20 of them.
Is this the normal way to catch an event that occur during the game? For example a colidation of 2 objects. I also set some code with a timer after 1 sec (step1). after 2 sec (step2). after 3 sec (step3).... when I use such a timer, I can start the next step exactly at this time, when the step before has done. Maybe one step needs more then 1 sec. And I don't want to use animateWithDuration and Delay. And maybe an iPad 2 is slower in processing and reading the whole code as an iPad 4. And I don't want to start with step 2 when step 1 has not finished.
But what is about the performance of the iOS device. Is this a problem?
thank you
Philipp
Answer: Is the interval of 0.001 o.k?

Probably not. "The effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds". You may set it to 0.001 but you are unlikely to get your timer on time.
Does it maybe also make the iPhone or iPad slower, when the game is sent to background

No it won't slow down the device when in background. iOS stops timers when app is in background.
Can I use more of this timer at the same time? for example when I run 10 or 20 of them.

Yes you can, but you may find a better solution.
I don't want to use animateWithDuration and Delay.

That will make your life easier. iOS goes into extends to make your animation smooth even if the device is under load.
Is this the normal way to catch an event that occur during the game?

No, unless your game doesn't update much, e.g. a turn-base game with no animation. Delivery time of timer event is not guaranteed. It may slip significantly. You would want to update you game state smoothly on every iteration, which is normally a frame. Do you have a frame update loop in your game? That would be the place to check for collisions and count time if needs be.
You are talking about noticing an event. A better design would be to use "push" rather than "pull". When an event happens it notifies all parties interested, not vice versa.

NSTimer perfomance of device


set de um caminho de acordo com o usuário para uma pasta

Question: Tenho um script que estou setando um caminho onde estão os datasets que vou trabalhar, porém agora os scripts começarão a ser rodados por outras pessoas da equipe, como faço para deixar o a pasta com valor dinâmico de acordo com o usuário que utiliza o script.
setwd("C:/Users/PedroAugusto/Database")

Estou até criando uma variável para receber o usuário da máquina, mas não sei como adicionar isso no setwd
u <- Sys.info()["user"]

Tentei fazer isso mas não tive sucesso.
 setwd("C:/Users/u/Database")

Complementando a pergunta, será usado um Rscript que é armazenado em um DevOps, as bases estão em uma pasta compartilhada, quando utilizo o script seto a pasta com os datasets, que no caso quando outro usuário rodar só mudará o usuário que esta utilizando.
Answer: u é o objeto que está armazenado a string de texto, não é a string em si. Pode usar paste para compor o nome do caminho. Ou melhor ainda, como apontado por @rui-barradas, file.path:
file.path("C:/Users", u, "Database")

Mas se algum usuário usar alguma estrutura de diretórios diferente, o script vai gerar erro. Pode incluir a opção de um caminho diferente ser passado como argumento para o Rscript, usando o caminho padrão caso nenhum seja fornecido:
# Captura argumentos da linha de comando
args <- commandArgs(trailingOnly = TRUE)

# Gera caminho padrão se nenhum for fornecido
if (!length(args)) {
  wd <- file.path("C:/Users", Sys.info()["user"], "Database")
  message("Caminho do Database não especificado. Usando ", wd)
} else {
  wd <- args[1]
}

# Tenta estabelecer o diretório de trabalho; emite mensagem de erro se o caminho não existir
tryCatch(setwd(wd), error = function(...) message("Erro: Diretório não encontrado"))

Passe o nome do diretório como argumento para o Rscript quando for necessário:
Rscript script.R /caminho/do/diretorio

Windows / *nix
Em sistemas *nix, til indica a raiz do usuário atual. Pode expandir a condicional para criar o caminho de acordo com o tipo de sistema:
if (!length(args)) {
  if (.Platform$OS.type == "windows") {
    wd <- file.path("C:/Users", Sys.info()["user"], "Database")
  } else if (.Platform$OS.type == "unix") {
    wd <- "~/Database"
  } else {
    stop("Indicar caminho do Database")
  }
  message("Caminho do Database não especificado. Usando ", wd)
} else {
  wd <- args[1]
}

Só confirme se o valor de .Platform$OS.type é mesmo "windows", não uso Windows para poder verificar.
Comment: Em vez de `paste`, `file.path("C:/Users", u, "Database")` é independente da plataforma. +1, já agora.
Comment: Obrigado pela sugestão, vou atualizar a resposta. Mas a independência de plataforma é quanto ao uso da barra invertida, não à estrutura de diretório dos usuários. Tinha pensado em usar `path.expand("~")`, mas não sei (nem tenho como verificar) o quão consistente se comporta em Windows. Até onde vi, pode direcionar para a pasta de Documentos do usuário dependendo da configuração.


git-tf tells me "Could not lock" when checking in; how can I fix it?

Question: I'm using git-tf to push to a TFS project.  Sometimes, when I try to check one or more commits into TFS, I get a message like this:

Connecting to TFS...
  Checking in to $/MyProject: 0%
  git-tf: Could not lock $/MyProject

What does this mean?  What's keeping me from locking?  And how can I fix this?
Answer: Why it happens
With standard TFS usage, you're only checking in one commit at a time.  But with Git, you could have a series of commits that you push all at once.
Because of that, git-tf strives to keep your set of commits atomic.  If someone checks in while you're checking in, the history can get mixed up; it won't be merged properly.
To prevent this, git-tf temporarily locks the entire source tree while it checks in.  It can't do this, though, if somebody else has parts of the source tree locked already.
How not to fix it
You'll see the --no-lock argument recommended in some places:
<code>git tf checkin --no-lock
</code>
This is not a good solution.  It ignores the potential scrambled-history problem instead of solving it.
How to fix it

Based on the version of TFS you're using, download and install the appropriate version of TFS Sidekicks.
Run TFS Sidekicks.
Navigate to Tools > Status Sidekick.
Clear the User name field.
Set a date range sufficiently wide to encompass the whole history of your project.  You can filter the Project name field if you like.
Click Search.  You'll get a list of all checked-out files in the project.
Click on the Lock type column header to sort by that column.  Most files will probably have "None" in that column.  You're looking for any files that have "Locked" instead.  This is most common with binary files, because they can't be merged.  By default, TFS will exclusively lock them when they're checked out.
Once you find out which files are locked, go talk to the person who has them locked and negotiate getting them unlocked.  If the person no longer works there, you may want to have a TFS admin just remove the locks.
Once all the locks are removed, hit Search again in TFS Sidekicks and you should see that all files have a lock type of "None".  Now try your git tf checkin again, and it should work correctly this time.
Comment: I had local pending changes that I had to "Undo", then it worked just fine. Here is a [good reference on git tf locking](http://blogs.msdn.com/b/ethomson/archive/2012/08/28/locking-and-git-tf.aspx)


Why does Covariance measure only Linear dependence?

Question: 1) What is meant by linear dependence?
2) How can I convince myself that covariance measures linear dependence?
3) How I can convince myself that non-linear dependence is not measured by covariance?
Comment: I realize we avoid links but this seemed relevant...a **visual depiction** of the limitations: https://www.autodeskresearch.com/publications/samestats
Comment: I agree. It does not answer your question which is why I left it as a comment. I trust others with more talent than myself will answer your question. Cheers.
Comment: A while ago I answered these questions geometrically in a post at https://stats.stackexchange.com/a/71303/919.  To see whether it might be of any interest to you, skip to the conclusions at the bottom.
Comment: Might be of intetest: https://stats.stackexchange.com/q/229667/3277. (My own opinion expressed there too, is that covariance coefficient is _not_ a measure of the amount of just linear relationship in the sense correlation coefficient is. It is improper to say "linear covariance coefficient".)
Comment: @SecretAgentMan: Thank you for the link. It offers good insights related to my questions. However, it does not answer them.
Comment: @whuber: Thank you for the link. Wow, that is one long, thorough answer. However, having read most of it, I am not sure that I've seen there direct answers to my questions above.
Comment: what do you mean precisely by "measuring linear dependence"?
Answer: Before moving to the interesting stuff, let's dispose of two of the questions. Covariance is too complicated for our purposes because it depends on three things: the magnitude of variable $X,$ the magnitude of variable $Y,$ and their correlation.  (See the discussion at the end of https://stats.stackexchange.com/a/18200/919 for the details.)
The individual magnitudes tell us nothing about the relationship between the variables.  Therefore we take them out of the picture by turning the covariance into the correlation: this is the quantity we need to pay attention to.  Thus, questions (2) and (3) are meaningless because they are misguided: covariance does not measure linear dependence, nor does it tell us anything (by itself) about "non-linear" dependence.
Question (1) remains, though: what really is "linear dependence"?
This answer adduces five simple general principles (highlighted below) to identify a class of possible ways to quantify departures from linear dependence (between two variables $X$ and $Y$).  Within that class, the correlation coefficient $\rho(X,Y)$ and its square $R^2$ emerge as being among the mathematically simplest choices.
In effect, I am proposing that the concept of "linear dependence" is deeply and inextricably associated with these five principles: to understand one is to understand the other.

It may be insightful to ground an answer in fundamental, widely general principles.  How would we want to characterize "linear"?  Let's hold that in abeyance and first consider the kinds of simplifications we might permit ourselves to make in such situations.  I propose beginning with the concept of invariance to changes of units.
This means that

any relationship between two variables $X$ and $Y$ that is considered to have some degree of "linearity," no matter what that might be, must have exactly the same degree of linearity when these variables are expressed in other units.

For instance, if $X$ is a temperature and $Y$ is a mass, the linearity of their relationship ought to be the same no matter whether we express $X$ in degrees C, F, R, or K; and no matter whether we express $Y$ in g, Kg, lb, oz, metric tons, or whatever.
This form of invariance permits us freely to adopt initial "normalizations" of the variables.  One possible normalization chooses units in which (a) the average of each variable is zero and (b) the variance of each variable is $1.$  In effect, this uses the standard deviation as a natural measure of the "size" of a variable: a metric.  It's not the only possibility, but it's an extremely useful one (as suggested by the Central Limit Theorem: see my discussion at https://stats.stackexchange.com/a/3904/919).

At this point I can suggest two avenues of investigation.  One is to view all variables as random variables and to analyze their joint distributions by means of the joint cumulant generating function (which always exists and provides full information about the distribution).  After these preliminary normalizations, the c.g.f. (which is a function of two variables $(s,t)$) takes the form
$$\psi_{X,Y}(s,t) = -\frac{1}{2}t^2 - \frac{1}{2}s^2 - \kappa_{11} s t + o(|(s,t)|^2).$$
See, for instance, Stuart & Ord, Kendall's Advanced Theory of Statistics Vol. I (5th Ed.), sections 3.28 and 3.29. From this perspective, the first, simplest, and most dominant scalar indicator of any bivariate distribution is its standardized bivariate cumulant $\kappa_{11} = \operatorname{Cor}(X,Y)=\rho_{XY}$ (the correlation coefficient).  We might then define the concept we are pursuing as

"linearity" of an association (between either random variables or data vectors) is the degree to which their bivariate distribution is well approximated by the terms in their c.g.f. through second order.

In particular, the Bivariate Normal distribution equals the foregoing expression, and therefore is the "most linear" of all possible distributions; consequently its "degree of linearity" must be solely a function of the correlation coefficient $\rho.$
However, to those not well accustomed to thinking (rather physically) in terms of moments and (rather abstractly) in terms of cumulants, this characterization might be of little help.  Let's therefore return to the program at hand, of exploring where basic invariance principles might lead.

No matter whether your "variable" is a finite dataset or a random variable, it "lives" in a natural vector space (wherein variables may be rescaled and added to each other).  Normalization places all variables on the unit sphere in this vector space.  When two variables (before normalization) differ by an affine function (one is a scaled, shifted version of the other), then after normalization they will either coincide or be diametrically opposite points on this sphere. We may therefore conceive of the amount of nonlinearity as being some function of distances on this sphere.
A "nice" distance will vary smoothly.  Such distances are given by Riemann metrics..  Although that tells us little in general, it has an interesting implication for "very nearly linear" relations: that is, when the distance between $X$ and $Y$ is small.  A basic (and elementary) result of Riemannian geometry is that locally (that is, to a very good approximation for nearby points), the squared distance between $X$ and $Y,$ written $\delta(X,Y)^2,$ is a quadratic function of the vector difference $X-Y.$  When things are written out in coordinates with $X=(x_1,x_2,\ldots,x_n)$ and $Y=(y_1,y_2,\ldots,y_n),$ this means there exist numbers $g_{i}$ which may vary with $X$ for which
$$\delta(X,Y)^2 \approx \sum_{i=1}^n g_i(X) (x_i - y_i)^2.$$
There are many possible candidates for such a distance.  But we may exploit another form of invariance.  Because (in this context) "linear" refers to some general relationship holding among matched pairs of data, the order in which we list those pairs should not matter.  Mathematically this means

the degree of linearity between $X$ and $Y$ must be the same when the components of $X$ and $Y$ are permuted (in parallel).

This implies all the $g_i(X)$ must be equal and permits us to drop the subscript "$i.$"
There remains one more almost trivial form of invariance it seems natural to demand of any linear relationship:

the degree of linearity between $X$ and $Y$ is the same as the degree of linearity between $Y$ and $X.$

Thus, $X$ is not privileged as the "base point" in the distance calculation, so we may equally well think of the Riemannian metric elements as varying with $Y:$
$$\delta(X,Y)^2 \approx \sum_{i=1}^n g(Y) (x_i - y_i)^2.$$
Now, because this is an approximation, it does not follow that $g(X) = g(Y).$  But it does indicate that $g$ itself ought to vary smoothly and slowly over the sphere.
Since everything is relative--we are discussing relative degrees of "linearity," not any absolute sense of it--we may rescale the function $g$ to make it equal $1/2$ at some point $X.$  Near this point, simple algebra (and our preliminary normalizations) show
$$\delta(X,Y)^2 \approx g(X) \sum_{i=1}^n (x_i-y_i)^2 = \frac{1}{2}\left[\sum_i x_i^2 + \sum_i y_i^2 - 2 \sum_i x_i y_i\right] = 1 - \rho_{XY}.$$
Generally, then, at least for "nearby" vectors $X$ and $Y,$ linearity must be measured as some multiple of $1-\rho_{XY}$ (where the multiple itself could depend on $X$).  This often is called the "cosine distance" or "cosine similarity".
Obviously the simplest such multiple is the constant function $1,$ because it just disappears from the formula.  But I wish to re-emphasize the point that this is not a unique solution: it's a convention.  Maybe it could be useful in some applications to break it.  This would amount to weighting $\delta$ according to some relevant pattern of variation among the components of the (standardized!) vectors $X$ and $Y.$  However, as a general proposition, any such weighting would appear arbitrary: it could be suitable only in particular circumstances.  As such it doesn't seem to qualify as any part of the concept of linear dependence.
Finally, remember that this characterization of $\delta$ is appropriate only for "nearly linear" associations, where already $X\approx Y.$ It pays to remember that $\rho$ therefore is truly justified in characterizing "linear dependence" only in cases where that dependence is clear and strong--that is, $X$ and $Y$ approximate each other--and in all other cases, $\rho$ may be of little value.  Be prepared for $\rho$ to fool you when the relationship between $X$ and $Y$ gets really complicated!  Visit our posts on Anscombe's quartet for a well-known set of examples.
On the Riemannian sphere there will be points that get as far from $X$ as possible and, if our distance is any good, those points ought to be close to $-X,$ which is diametrically opposite (at a cosine distance of $1-(-1)=2.$ Because we want to view $X$ as being closely linearly related to vectors near $-X$ (as well as near $X$), we may invoke one more invariance principle:

The degree of linearity between $X$ and $Y$ must be the same as the degree of linearity between $X$ and $-Y.$

Since $\rho(X,-Y) = -\rho(X,Y),$ this last principle implies the degree of linearity--whatever it might mean or be--should be measured by some decreasing function of $|\rho(X,Y)|.$  This explains why $R^2(X,Y) = \rho(X,Y)^2$ is commonly compared to its maximum possible value of $1:$ we are really using $1-R^2$ as a measure of departure from linearity.  Clearly this is one of the simplest possible formulas (and the presence of the square simplifies its mathematical analysis).
Answer: A1) Say two variables X and Y are linearly dependent, then $X = \alpha Y + c$ for some $\alpha,c \in \mathbb{R}$.
A2) The formula for covariance is:
$$COV(X,Y) = E([X-E(X)][Y-E(Y)]) = E(XY)-E(X)E(Y)$$
From A1, consider some linear relationship $X = \alpha Y + c$, but all we have is the data from individual points in each variable. How do we get the value of $\alpha$? Well, it turns out we can instead ask the question, "how do we draw a line between these points so as to minimise the sum of squared differences between each point and the line?". And when we do this analysis for two variables, we get a closed form equation that looks like this:
$$\alpha = \dfrac{E(XY) -E(Y)E(X)}{E(X^2) - E(X)^2}$$
Please note that the numerator is the covariance. I.e.
$$ \alpha = \dfrac{COV(X,Y)}{E(X^2) - E(X)^2}$$
Correlation (e.g. Pearson) is often a measure of the covariance normalised against something to give it a comparable value. So you see the entire measure precedes from the analysis of how to fit a line to some data.
A3) Covariance doesn't measure non-linear relationships for the exact same reason it measures linear ones. Namely, that you can basically think of it as the slope in a linear equation (e.g. $X=\alpha Y + c$), so when you try and fit a line to a curve, the sum of square differences between the points and the line may be large. Here is a good diagram illustrating the implications. The numbers indicate Pearson's correlation coefficient, whilst the diagrams show the corresponding scatter plots.
Comment: Could you point to a particular definition that makes your assertion in (2) apparent?  This is key to the entire answer, because the rest of it merely establishes a *qualitative* relationship between $\rho$ and apparent linearity.
Comment: @usgroup: note that the phrase you use "linearly correlated" is precisely the tautology this question explores :) It is not clear to me from your answer why covariance measures linear dependence only. Why is "dividing the product of the difference of each variable from it's mean (i.e. the covariance) by the product of the standard deviations of each variable" a measure of linear dependence only?
Comment: @whuber how my edits have made it better :)
Comment: @colorstatistics you're right . i'll edit the answer to address covariance.
Comment: @usgroup: thank you, this is much improved and quite insightful. I was with you until in A3, where you write "you can basically think of it [covariance] as the slope in a linear equation". Row 2 of your graphical depiction shows sets of very differently looking x and y variables that have correlation=1, and the magnitude of the slope doesn't seem to matter. I am hoping we can close in on this difference between slope and covariance/correlation to understand it better.
Comment: Here is similar post https://stats.stackexchange.com/questions/180777/pearson-correlation-coefficient-is-a-measure-of-linear-correlation-proof/332214#comment716791_332214 I believe the answer provided by A-Sus may help us get there, but I haven't been able to figure out how he gets the expression for the square of correlation.
Comment: Michael Chernick in his answer to https://stats.stackexchange.com/questions/31270/what-is-the-difference-between-linearly-dependent-and-linearly-correlated/76851#76851 says "Two variables are linearly dependent if one can be written as a linear function of the other." A linear function Y=aX+b has a deterministic as opposed to stochastic term b. We use covariance to express linear dependence in X and Y, especially for X and Y pairs that do not fall neatly on the same line, rendering b stochastic. Is it correct/insightful to think of covariance as how close the term b is to being deterministic?
Comment: @ColorStatistics please study A2 above. The covariance part is about the "a" component not the "b" component.
Comment: Clarification: What I mean by stochastic term b is a constant + error term, where the error term renders b stochastic. @usgroup: That is understood.
Comment: How do you derive that value of $\alpha$? I don't understand how your answer shows that correlation only measures linear relationships. Perhaps provide a concise explanation that goes to the heart of the main idea.
Answer: Covariance only measures linear relationship and it classifies the slope of the linear relationship into one of three cases: 1)positive, 2)negative, 3) no trend.
If two random variables, X and Y, are not linearly correlated, we can still calculated their covariance. However, the result is not valid, meaning that we cannot explain a positive covariance as that bigger X are associated with bigger Y. Similarly, a negative covariance doesn't necessarily mean that bigger X are associated with smaller Y; nor can we say that if the covariance is 0, then there is no trend between X and Y.
Why is it? Think about this case: Y = X^2. There is a clear trend/pattern between the two variables, but if you calculate their covariance, it is 0. Here is how I got cov(X, Y) = 0: Take four data points from this graph that are symmetric, say (-2, 4), (-1, 1), (1, 1), and (2, 4). Then calculate the covariance using its formula, you get it equals to 0.
To summarize, if two variables doesn't show linear trends, then it is not valid to use covariance to characterize their relationship. That's why we say that covariance only measure linear relationships.


How can I restore the state of a tab when switching between them?

Question: Switching between tabs with the implementation of ion-router-outlet loads main page instead of latest page.
If understood it right tab pages should be restored instead of loading their main page and if using the android hardware button they are all contained in the navigation stack. (Did still not understand why I had to add navController.back() to achieve going back with the android hardware button when it should be done automatically as stated here)
Could be same problem as this issue and the related implementation.
I implemented it with ion-router-outlet but also tried it with ion-nav and ion-nav-link but this broke the navigation stacks between the tabs.
Current implementation:
tabs-routing.module.ts
const routes: Routes = [
  {
    path: '',
    component: TabsPage,
    children: [
      {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
      },
      {
        path: 'calibration',
        loadChildren: () => import('../tab1/tab1.module').then(m => m.Tab1PageModule)
      },
      {
        path: 'home',
        loadChildren: () => import('../tab2/tab2.module').then(m => m.Tab2PageModule)
      },
      {
        path: 'survey',
        loadChildren: () => import('../tab3/tab3.module').then(m => m.Tab3PageModule)
      }
    ]
  },
];

tabs.page.html
<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="calibration">
      <ion-icon aria-hidden="true" name="eye"></ion-icon>
    </ion-tab-button>

    <ion-tab-button tab="home">
      <ion-icon aria-hidden="true" name="home"></ion-icon>
    </ion-tab-button>

    <ion-tab-button tab="survey">
      <ion-icon aria-hidden="true" name="reader"></ion-icon>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

tab1-routing.module.ts
const routes: Routes = [
  {
    path: '',
    component: Tab1Page,
    children: [
      {
        path: '',
        redirectTo: 'menu',
        pathMatch: 'full'
      },
      {
        path: 'calibration',
        loadChildren: () => import('./calibration/calibration.module').then(m => m.CalibrationPageModule)
      },
      {
        path: 'menu',
        loadChildren: () => import('./menu/menu.module').then(m => m.MenuPageModule)
      }

    ]
  }
];

tab1.page.html
<ion-content>
  <ion-router-outlet></ion-router-outlet>
</ion-content>

tab1.page.ts
  constructor(private platform: Platform, private navController: NavController) {
    this.platform.backButton.subscribeWithPriority(10, ()=> {
      console.log("Handler called!");
      navController.back();
    });
  }

menu.page.html
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Calibration
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-grid class="ion-align-items-center">
    <ion-row class="ion-justify-content-center">
      <ion-col class="ion-text-center">
          <ion-button routerLink="/calibration/calibration" shape="round">
            Start calibration
            <ion-icon slot="start" name="play"></ion-icon>
          </ion-button>
      </ion-col>
    </ion-row>
    <ion-row class="ion-justify-content-center">
      <ion-col class="ion-text-center">
        <ion-button shape="round">
          Delete calibration
          <ion-icon slot="start" name="trash"></ion-icon>
        </ion-button>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

I hope someone can help me here. Maybe it is just a quick fix or a misunderstanding in using the wrong things here.
Answer: So I fixed it myself by removing the separate files of menu completely and put its content directly in the tab1 files. This seems to fix the issue and is working now on my Android Device.
I then added this code to my calibration.html to correctly navigate because the normal  would brake the navigation st:
<ion-buttons slot="start" (click)="goBack()">
  <ion-icon slot="icon-only" name="arrow-back"></ion-icon>
</ion-buttons>

Also this code of tab1.page.ts has to be in app.component.ts:
constructor(private platform: Platform, private navController: NavController) {
  this.platform.backButton.subscribeWithPriority(10, ()=> {
  console.log("Handler called!");
  navController.back();
});

}
And tab1-routing.module.ts now looks like this:
const routes: Routes = [
  {
    path: '',
    component: Tab1Page,
  },
  {
    path: 'start',
    loadChildren: () => import('../tab1/calibration/calibration.module').then(m => m.CalibrationPageModule)
  }
];

The routerlink in tab1.page.html changed to /calibration/start
Note: My /calibration is the tab1 (I know bit of a bad naming of files, which I will improve in the future)


Error: interface not supported. Delphi 10.2 Tókio

Question: Erro ao tentar salvar a janela de tools=> options do Delphi 10.2
Já tentei reinstalar a imagem da IDE para ver ser reselveria.
Só consigo fechar a janela se "Cancelar" a operação.
Alguém tem uma dica ou solução para o erro?
ERROR: interface not supported.
Answer: amigo...
creio que você resolveria isso reparando o seu delphi. Porém, se fizer isso creio que terá que instalar os componentes novamente..
mas dá uma olhada nisso aqui, acho que te ajudará:
Using the -r command line switch to fix start up errors in the IDE
Comment: Obrigado @Cleyton Alves, já foi de grande ajuda, desinstalou os componentes, mas é melhor do que precisar reinstalar e ou modificar pelo Instalador. Vou ver melhor a documentação para ver as possibilidades.
Comment: ahh... que legal que te ajudou!


How to display bootstrap modal using anchor tag

Question: I'm trying to call modal using anchor tag...
Here's the HTML code

      <?php echo $_SESSION['name']; ?>

     Delete Account

Above code is inside the navbar and when I click on the Delete Account I want to pop over my modal and here is my modal code

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Anyone can please help me to call the modal class when I click on Delete Account link.
Thankyou in advance
Comment: I can't see any problems in your code, it should work. [ref](https://www.w3schools.com/bootstrap4/bootstrap_modal.asp)
Comment: But it's not working when I click on the link Mr @AhmedTagAmer
Answer: With the HTML you supplied the dropdown was not appearing at all for me. I had to add a toggle in order to make it work:
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown
</button>

From then on I didn't have problem opening the modal, check this fiddle. I'm not familiar with PHP though and how it would play with href attribute you added for the delete button. This is from bootstrap's dropdown docs.
Answer: Check this

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>

     Action
     Another action
     Delete Account

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>


Showing that the given critical value (?) gives a test with significance level 0.05

Question: So I have a maths problem that I'm struggling to understand... The original language isn't English, but I have done my best to translate the necessary background information into English.
Assume that we have observed the following values:
0.50, -0.15, 2.82, 0.68, 0.19, 1.23, -1.65, 2.38, -0.49, 1.59, 0.66, -0.12, 1.20, 1.08, 0.82
from a sample $X_1, X_2,...,X_{15}$ where $X\sim N(\mu,1)$ for $i=1,2,...,15$ and $\mu$ is an unknown parameter. We are interested in the following two hypotheses:
$H_0:\mu=0\\
H_1:\mu=0.5$
Let $W=\frac{1}{15}(X_1,X_2,...,X_{15})$ be the average of the sample, and for $c>0$ observe the test that accepts the null hypothesis if $W\leq c$. For the following, we will test the null hypothesis $H_0$ at a significance level $\alpha=0.05$.
What I need help with: How do I show that $c=0.4247$ gives a test with a significance level of $\alpha=0.05$?
My initial thought was to check if the area under the graph for the normal distribution with mean 0 and variance 1 was 0.05 to the right of the critical value, but I got 0.34 instead (thought the critical value looked a bit off when I drew the graph...). I don't know what I've overlooked. My best guess is that my "critical value" isn't actually the critical value.
Comment: Where did you get your $0.34$?
Comment: Your formula for W is wrong. Presumably you intend W to be the average of the X's.  Now consider - what is the distribution of W under $H_0$
Answer: The traditional approach would be to do a right-sided
z test at the 5% level of $H_0: \mu = 0$ vs.
$H_a: \mu = 0.5.$
The test statistic is
$$Z = \frac{\bar X - \mu_0}{\sigma/\sqrt{n}} = \frac{0.716 - 0}{1/\sqrt{15}} = 2.773.$$
Then, $Z \sim\mathsf{Norm}(0,1),$
which has 5% of its probability above $1.645.$
Thus, the critical value for test statistic $Z$ is
$c^\prime = 1.645,$ from a CDF table of the
standard normal distribution. Because $Z > c^\prime = 1.645$
you reject $H_0$ in favor of the alternative $H_a.$
The figure below shows the standard normal distribution. The solid vertical line shows
the observed value of the test statistic $Z$ and
the vertical dotted line shows the critical value.
(See end note for R code.)

However, you are asked to use test statistic
$W = \bar X = 0.716.$ The statistic $W$ is normally
distributed, but not standard normal.
Accordingly, it seems you are told to use critical value $c = 0.4247 \approx 1.645/\sqrt{15}.$
Because this is a self-study problem, I will leave it to
you to explain why the 5% critical value in terms of
test statistic $W$ should be $c=0.4247.$
Note: R code for figure.
<code>hdr = "Standard Normal Density"
curve(dnorm(x), -3, 3,
      lwd=2, ylab="Density", xlab="z", main=hdr)
abline(h=0, col="green2")
abline(v=0, col="green2")
abline(v=2.773, lwd=2)
abline(v=1.645, lwd=2, col="orange", lty="dotted")
</code>


Apache server is very slow taking minutes to respond

Question: I have Ubuntu 12.04 64-bit and Apache 2.2.22 installed on my machine used for development. Anyway, it seems from one day to the next that it would serve the pages in milliseconds to now 5 minutes 1 second every time. I believe that this is because the timeout value is 300 in the apache.conf. What I don't understand is why it is timing out.
I have xdebug installed but I am not triggering it and it is not on autostart so I really think this would have made no difference and they were working together fine before.
I am a complete noob at Apache and not sure how to start debugging the issue. I have checked the logs but they don't seem to give me anything interesting. The Apache error.log is not changing and only producing a notice log when it boots.
The actual app log is a bit more interesting as in it does update the app-access.log and the app-error.log, however the access log just says the GET requests and the error log is all info. The make no sense to me so here is an example of one from a request.
[Mon Jan 20 12:01:39 2014] [info] [client 127.0.0.1] (32)Broken pipe: core_output_filter: writing data to the network
[Mon Jan 20 12:01:43 2014] [info] [client ::1] Connection to child 6 established (server app:443)
[Mon Jan 20 12:01:43 2014] [info] Seeding PRNG with 656 bytes of entropy
[Mon Jan 20 12:01:43 2014] [info] [client ::1] SSL library error 1 in handshake (server app:443)
[Mon Jan 20 12:01:43 2014] [info] SSL Library Error: 336027900 error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol speaking not SSL to HTTPS port!?
[Mon Jan 20 12:01:43 2014] [info] [client ::1] Connection closed to child 6 with abortive shutdown (server app:443)

The thing is that it only produces a log when the page is served which is minutes later (after the apparent 5 min timeout). It seems that it takes ages for the request to actually hit the app. I am not sure what is the best way to go about finding why this is the case. I have made no changes recently to my configuration so I really don't see why it has suddenly gone awry.
Comment: You have to find the bottleneck. Configure apache to disable dns lookup and enable debug loglevel, try to use http first, look at your system's network connections (netstat), list open files (lsof), check server load including cpu, i/o and ram usage (top).
Answer: Well if the config didn't change, you have no choice but to limit the timeout to 2 seconds, then you have 3 second load time.. ;) Okey, let's try something helpful..
You say you use it for local development testing?
Can you remember what the very last change was to any of the following:

Your web application, any changes between when it was working and when it wasn't?

Is there a for .. loop that runs infinitely?
Or is your application making a request to a another server that is not responding?

Any other logs to check? PHP's error log or any other scripting language's that you may be using.
Database settings, table structures? Constraints? Procedures?

Are you using a database that has some locks that your application is waiting for?

Scripting language settings (PHP, Perl, Python, Ruby which are you running?)
Apache settings

Modules
Virtual Hosts
.htaccess files?

Any updates to any other services on the server?
Any firewall changes?
Any updates of database, scripting language or Apache?

Other things to check:

If that does not help, you should increase the verbosity of Apache's logging up to debug in steps and see what is going on during the 5 minutes..
You may also see which process is using the cpu while the request is running (if any at all), e.g. PHP taking up an entire CPU core? Or maybe mysqld (or any other database daemon)..

[EDIT]
See this too:
https://web.archive.org/web/20170225085205/http://servertune.com/kbase/?View=entry&EntryID=109
Comment: Sugar! Cheers I found it. I was so stupid. The for loop jogged my memory. I was in a wrong branch and I on my dev machine I dont have Alternative PHP Cache (APC) enabled and this caused the issue. Thanks Chris it was so stupid of me but you hit it on the nail
Comment: Welcome, it's only my stupidity that I need these checklists for problem solving ;) ..
Comment: Nobody's stupid here ;)
Answer: Edit /etc/apache2/ports.conf
Make sure the Listen 80 line comes last. [1]
If that doesn't resolve the issue, replace Listen *:443 or Listen 443 with Listen *:443 http [2]
Also, apparently, apache2ctl graceful isn't sufficient for this change to take effect, be brutal:
apache2ctl restart
Good Luck.
1: http://wiki.apache.org/httpd/InternalDummyConnection
2: https://netfuture.ch/2013/07/ubuntu-apache-update-broke-listen-command/


Sample rate for iPhone audio recording

Question: What's the lowest optimal sample rate for audio recording on iPhone while still yielding good file size?  Currently I am using 44.1kHz but it produces file that's way too big.
Answer: On the iPhone with the built-in microphone, you're going to get a maximum of 8 kHz. If you use a headset, you can get 44.1 kHz. If you're using the built-in mic and setting your recording sample rate to 44.1 kHz, you're upsampling the audio, which is unnecessary and generates the big files you mention. Also, make sure you record in mono. That cuts the file size in half.
If you always want to record at the best rate, you should ask the hardware:
<code>size = sizeof(sampleRate);
err = AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate,
    &size, &sampleRate);
</code>
For voice, you can just always record at 8 kHz. For music, you want the best quality so use the sample rate that the hardware is running.
Comment: @bubakazouba The original iPhone's microphone had an 8 kHz sample rate but newer devices support higher https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/OptimizingForDeviceHardware/OptimizingForDeviceHardware.html
Comment: source for the sampling rates please?
Answer: It depends on what you mean by "optimal".  22.05kHz would still be good enough for most music.  11.025kHz would be more than adequate for recording speech.  It all depends on what you're doing with the audio.  I recommend using your ear to determine the best rate.
Answer: I think you want 8 kHz, as others have said.  This is the rate that land-line telephones use.  If you are doing speech recognition, though, you might want to increase the frequency to 16 kHz, which is what IBM's speech recognition requires for "high quality" (see their API docs).
Wikipedia's article on sample rates gives a good chart of sampling rates and their uses:
<code> 8000  Land-line telephones
11025  One-quarter of CD quality
16000  Voice-over-IP
22050  Half of CD quality, could be used for older audio (e.g. 78 RPM records)
32000  Camcorder audio
44100  CD quality
48000  Professional audio equipment
</code>

Sample rate for iPhone audio recording


Using HERE positioning without Wifi or SIM

Question: I have set up a simple app to get position from HERE (with some help graciously given by HERE Developer Support) that question is answered here
This code works fine on my phone to produce a GeoPosition once per minute in my log.
I am now trying to run this code on my target tablet. The tablet is old (runs Android 5.1), does not have GPS and does not have a SIM or an phone connectivity. The only possible location method is to use Wifi. I have tested the HERE test app on the tablet and it found a good approximate location based on Wifi connections - this is what I am trying to duplicate.
When I try to initialize the PositionManager with LocationMethod of GPS, or GPS_NETWORK or NETWORK I get the same error
for these lines:
    PositioningManager pm = PositioningManager.getInstance();
    PositioningManager.LocationStatus  ls = pm.getLocationStatus(PositioningManager.LocationMethod.GPS);
    Log.i("Position", "Setting up positioning");
    if (ls ==  PositioningManager.LocationStatus.AVAILABLE) {
        Log.i("Position", "Positioning is available");
    } else {
        Log.w("Position", "Positioning not available right now: " + ls.toString());
    }
    boolean ret = pm.start(PositioningManager.LocationMethod.GPS);
    Log.i("Position", "Positioning start returns " + ret);

I get these logs:
01-27 06:00:21.656 16636-16636/? I/Position: Setting up positioning
01-27 06:00:21.657 16636-16636/? W/Position: Positioning not available right now: OUT_OF_SERVICE
01-27 06:00:21.660 16636-16636/? W/System.err: java.lang.IllegalArgumentException: provider doesn't exist: network
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.os.Parcel.readException(Parcel.java:1550)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.os.Parcel.readException(Parcel.java:1499)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:582)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:899)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:500)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.here.android.mpa.internal.v.a(DeviceLocation.java:117)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.here.android.mpa.internal.ea.a(PositioningManagerImpl.java:224)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.here.android.mpa.common.PositioningManager.start(PositioningManager.java:153)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.company.app.MainActivity.setUpPositioning(MainActivity.java:63)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.company.app.MainActivity.onRequestPermissionsResult(MainActivity.java:137)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.company.app.MainActivity.checkPermissions(MainActivity.java:108)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.company.app.MainActivity.onCreate(MainActivity.java:39)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.Activity.performCreate(Activity.java:5990)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.ActivityThread.access$800(ActivityThread.java:151)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.os.Looper.loop(Looper.java:135)
01-27 06:00:21.661 16636-16636/? W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5258)
01-27 06:00:21.661 16636-16636/? W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-27 06:00:21.661 16636-16636/? W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
01-27 06:00:21.661 16636-16636/? W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
01-27 06:00:21.666 16636-16636/? I/Position: Positioning start returns true

and every minute I check the position
            GeoPosition pos = PositioningManager.getInstance().getPosition();

and it is null. If I set the LocationMethod to NULL i don't get an exception, but I still don't get any GeoPosition.
how do HERE manage it in their test app, to get a position from Wifi alone?
Answer: Assuming the Test app being referred is the one available in github (https://github.com/heremaps/here-android-sdk-examples/tree/master/positioning) , the recommendation would be to use the LocationDataSourceHERE and use the GPS_NETWORK_INDOOR mode for starting positioning.
mHereLocation = LocationDataSourceHERE.getInstance( new StatusListener() {
// implement the callbacks
..
});
mPositioningManager.setDataSource(mHereLocation);
..
// start position updates, accepting GPS, network or indoor positions
if (mPositioningManager.start(PositioningManager.LocationMethod.GPS_NETWORK_INDOOR)) {
     // positioning started sucessfully
} else {
      T// error
}

There might be some special permissions required if you also want to use the indoor positioning feature using indoor radio map (documentation)


Frobenius automorphism of a quadratic extension

Question: I'd like to calculate the Frobenius automorphism of the quadratic field $K=\mathbb{Q}(\sqrt{d})$ where $d\in\mathbb{Z}$ is squarefree.
As the prime $p$ should be umramified, we have $p\mathcal{O}_K=R_1R_2$ or $p\mathcal{O}_K=R$ with $f(R|p)=2$.
The first case implies $\big(\frac{d}{p}\big)=1$, i.e. $\sqrt{d}\in\mathbb{F}_p$ and $\sqrt{d}^p\equiv \sqrt{d}\mod p$. Thus the identity is the Frobenius automorphism.
What do we get in the second case?
Answer: In the second case $\mathcal O_K/p\mathcal O_K$ is a finite field of order $p^2$, it follows that the reduction map $\operatorname{Gal}(K) \to \operatorname{Gal}(\mathcal O_K/p\mathcal O_K)$ is an isomorphism and the Frobenius element is the only non-trivial element in $\operatorname{Gal}(K)$, namely the conjugation $\sqrt{n} \to -\sqrt{n}$.
Ur to put it differently, because $O_K/p\mathcal O_K$ has order $p^2$, the Frobenius $O_K/p\mathcal O_K \to O_K/p\mathcal O_K, \overline{x} \mapsto \overline{x}^p$ is not the identity map, as in a field with $p^2$ elements, there is an element $a$ with $a^p \neq a$, thus the frobenius automorphism of $K$ can't be the identity map, but since $\operatorname{Gal}(K)$ has only two elements, this leaves only one possibility.
Comment: Why do we consider the restriction map to find the Frobenius automorphism?
Comment: @math78 because of the way that the Frobenius automorphism is defined. Which definition of Frobenius automorphism are you using?
Comment: We defined  the Frobenius automorphism $\sigma$ as the unique element of $\text{Gal}(K)$, which satisfies $\sigma(x)\equiv x^p\mod R$ for all $x\in \mathcal{O}_K$
Comment: @math78 I have edited the post, I hope it's clear now.
Answer: I wanted to answer to your comment in the previous answer, but I realized that it was too long to be a comment. So I will write it as an answer. But this is just an addition to the previous answer, and therefore I would ask you not to verify this as the valid answer! The answer of the previous user looks perfect to me.
As you said in the comment, the Frobenius automorphism $\sigma \in G := \text{Gal}(K \mid \mathbb{Q})$ is the unique element in the decomposition group $D:=D(R\mid p) \subseteq G$ (in this case $D=G$) with that property. But I think that the nicer conceptual definition is the following:
In any field $F$ of characteristic $p>0$, the Frobenius endomorphism is given by $x\mapsto x^{p}$. In our context, the residue field of $\mathcal{O}_{K}$ at $R$ is a finite separable field extension of the field $\mathbb{F}_{p}$, hence is itself a field of characteristic $p>0$. The Frobenius endomorphism of $\mathcal{O}_{K}/R$ is then a generator of the corresponding Galois group $G':=G(\mathcal{O}_{K}/R \mid \mathbb{F}_{p})$.
On the other hand, the fundamental exact sequence of Galois theory tells us that $D\cong G'$, because $p$ being unramified implies that the inertia subgroup is trivial. Under this isomorphism, the Frobenius endomorphism on $\mathcal{O}_{K}/R$ corresponds to a generator of the decomposition group $D$. And this is the Frobenius element of $R$ over $p$.
In our particular case, since we are looking at $R=p\mathcal{O}_{K}$, we have $D=G$, so the Frobenius element must be a generator of $G$. And there is only one generator, so we are done.
Answer: In the particular case  of an abelian field $K$, given a prime $P$ of $O_K$ over a prime number $p$ unramified in $K$, the Frobenius automorphism $\phi_{p,K}$ of $K$ (it depends only on $p$) is the unique automorphism of $K$ s.t. $\phi_{p,K} (x) \equiv x^p$ mod $P$ for any $x \in O_K$. In other words, $\phi_{p,K}$ is a lift to $O_K$ of the usual Frobenius automorphism relative to the extension of finite fields $(O_K/P)/\mathbf F_p$. Let us now consider a quadratic field $K=\mathbf Q(\sqrt d)$. The prime $p$ is unramified iff $p $ does not divide the discriminant of $K$, which is $d$ or $4d$. If $p$ splits in $K$, obviously $(O_K/P)=\mathbf F_p$ and the two Frobenius are the identity. If $p$ is inert in $K$, obviously  $(O_K/P)=\mathbf F_{p^2}=\mathbf F_p (\sqrt {\bar d})$, where $\bar d$ is the class of $d$, and the two Frobenius send resp. $\sqrt d$ and $\sqrt {\bar d}$ to their opposites.
This is so plain that I guess that your question is actually about some precise relationship between the Frobenius automorphism $\phi_{p,K}$ and the Legendre symbol $(\frac dp)$. This is a natural question : $(\frac dp)$ can obviously be viewed as a generator of $Gal(\mathbf F_p (\sqrt {\bar d})/\mathbf F_p)\cong (\pm 1)$, $\phi_{p,K}$ is generator of $Gal(\mathbf Q(\sqrt d)/\mathbf Q)\cong (\pm 1)$, and what we saw above amounts to $\phi_{p,K}=(\frac dp)$. But that's not all. Take two distinct odd primes $p,q$ , and consider the cyclotomic field $F=\mathbf Q_{\zeta_q}$ (in which $p$ is necessarily unramified). It is classically known that $F/\mathbf Q$ is a cyclic extension of degree $(q-1)$, hence it contains a unique quadratic subfield $K$, and the usual calculation of the discriminant of $F$ implies that $K=\mathbf Q(\sqrt {q^*})$, where $q^*=(-1)^{\frac {q-1}2}$. The same argument as before shows that $\phi_{p,K}=(\frac {q^*}p)$. Moreover, the restriction to $K$ of $\phi_{p,F}\in Gal(F/\mathbf Q)\cong \mathbf F^*_{q}$  coincides naturally with $\phi_{p,K}\in Gal(K/\mathbf Q)\cong (\pm 1)$, so that $\phi_{p,K}=1$ iff $\phi_{p,F}\in Gal(F/K)\cong {\mathbf F^*_{q}}^2$ (= the unique subgroup of index $2$ of $\mathbf F^*_{q}$. This means  that $\phi_{p,K}=(\frac pq)$. Transforming the equality $(\frac pq)=(\frac {q^*}p)$ using Euler's criterion, one gets   $(\frac pq)(\frac qp)=(-1)^\frac{(p-1)(q-1)}4$. Among the numerous proof of the quadratic reciprocity law, this one stands out as the very first embryo of the so called reciprocity for "power residue symbols" which appeared later in class field theory.


Bash IFS, getting zapped in function call

Question: Platform CentOS Linux release 7.6.1810, working in bash.
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
This is an idiom I've seen recommended for parsing text in bash in general and in particular for returning multiple values from a function.
IFS=":" read A B <<< $(echo ONE:TWO)

I'm getting unexpected behaviour when I call a function, yyy in the example here
IFS=":" read Y1 Y2 <<< $(yyy)

where yyy itself also wants to do a similar call.
The effect is that that within yyy() even though I explicitly specify the IFS
 IFS=":" read C1 C2 <<< $( echo "A:B" )

The fields are parsed, but both values are assigned to C1, it gets the value "A B". If the function is called in isolation it works as expected.
This is a test case, distilled down from a much larger script. I want to know what is happening with IFS here. In the failure case (the second example below) setting IFS=":" in the caller somehow cause the result fields to be aggregated. The first and third calls to yyy() below work as expected, output shown after the code.
#!/bin/bash

debug() { echo "$1" 1>&2 ; }

yyy() {
    debug "in yyy"
    # why are the two values assigned to A here if the caller specified IFS?
    IFS=":" read A B <<< $(echo ONE:TWO)
    debug "A=$A"
    debug "B=$B"

    echo "$A:$B"
}

    # this works as expected
    read Y1 Y2 <<< $(yyy)
    echo -e "===\n"

    # this cause the read in yyy() to aggregate
    IFS=":" read Y1 Y2 <<< $(yyy)
    echo -e "===\n"

    # This is a workaround that enables yyy() to work correctly
    # But why do I need to do this?
    OUT="$(yyy)"
    IFS=":" read Y1 Y2 <<< $(echo $OUT)

This is the output
in yyy
A=ONE B=TWO

===

in yyy
A=ONE TWO B=

===

in yyy
A=ONE B=TWO

Note that in the second case A gets the value ONE TWO
Comment: [Can't reproduce repl link](https://repl.it/@kamilcukrowski/AwfulEasyRuntimes). I get `A=ONE B=TWO` on separate lines for second case. Note that `<<< $(echo )` is strange use of `echo`, just `<<<"ONE:TWO"`. What bash version are you using? `yyy` is executed in a subshell - it shouldn't have any influence on the parent shell.
Comment: The echo syntax is because in real life I'm calling something else. I agree that the behaviour is unexpected - however it's the behaviour **in** yyy that's unexpected, the parent seems to be affecting yyy. Very interesting that your shell works as expected.
Comment: I note that you are using GNU bash, version 4.4.12 whereas I'm back a few versions 4.2.46
Answer: This seems to be a bug in bash-4.2 as discussed here, IFS incorrectly splitting herestrings in bash 4.2. Should work on the versions above that.
These are the results on the same version as you have -  GNU bash, version 4.2.46(2). When I ran the function yyy in debug mode ( by setting set -x in prompt ).
++ IFS=:
++ read A B
+++ echo ONE:TWO
++ debug 'A=ONE TWO'
++ echo 'A=ONE TWO'
A=ONE TWO
++ debug B=
++ echo B=
B=
++ echo 'ONE TWO:'

The above is snippet of the output from the debug mode output. As you can see when the echo ONE:TWO is printed as a result of the command substitution, no word splitting is expected to happen because the line doesn't contain any character of the default IFS value (space/tab or a newline)
So you would expect reading the the whole string with IFS=: expected to split the string and put the values in the constituent variables A and B, but somehow the : character is lost and a string ONE TWO is stored as the first variable value.
Look at the output of the function execution in GNU bash, version 4.4.12(1) which exhibits the right behavior.
++ IFS=:
++ read A B
+++ echo ONE:TWO
++ debug A=ONE
++ echo A=ONE
A=ONE
++ debug B=TWO
++ echo B=TWO
B=TWO
++ echo ONE:TWO

There have been lot of IFS related bugs up to version 4.4.0 bash/CHANGES. So a personal recommendation is to upgrade your bash version to a more recent stable one. Also see Trying to split a string into two variables
Similar bug on version 4.4.0(1)-release
You would expect the ONE:TWO to be unmodified when the $(..) is expanded because for reasons mentioned earlier. But here too the delimit character is lost and the variable A is set to ONE TWO
IFS=":" read A B <<< $(echo ONE:TWO)
echo "$A"
ONE TWO

Surprisingly the above code works on 4.2.46(2), which means the 4.4.0(1) broke a functionality which used to work in the earlier releases.
Comment: Thanks for the investigation. It's reassuring to know that this should work.


Is Dell's server software bundle necessary? (Poweredge 2950 in my case)

Question: Dell includes a fair amount of software with its servers, but I'm having a hard time determining from the documentation what each of them does, and whether or not I should install it. Dell's support site (unless I'm doing it wrong) seems fairly opaque to me and its offerings fairly unstandardized in terms of their usage, so if possible I'd like to stray away from them. Specifically, I'm curious if any of the features offered are duplicated in something like Microsoft System Center.
For additional background information, I'm working with a Poweredge 2950 that was just rebuilt with an expanded raid-6, but initially I just installed Server 2008 R2 directly instead of using the Build and Update utility. There's nothing of use on it at the moment so I'm totally open to wiping it again.
Answer: From my experience it is not necessary.  I have a couple dozen Dell servers and all of them have a base windows install.  Occasionally, there there may be a driver or tool (RAID monitor/managment) that you need to install, but as far as I know nothing is strictly necessary.  Pretty much everything in the bundle can be separately downloaded from support.dell.com and be installed as required.
Comment: +1 and on a 2950, the online software is guaranteed to be more up to date, too
Comment: @Matt +1, Just download the latest. Contacting Dell support usually results in: *"Which version firmware/OMSA are you running? Oh, will you update it please?"*
Comment: It's funny that you mention that--it was actually raid monitoring that got me thinking about it in the first place. Incidentally, do you know which application it is that does said raid monitoring? Again this isn't terribly apparent when looking through dell's support, even when filtered by 2950 and Server 2008 R2.
Comment: @bwerks: openmanage (as mentioned by EK) is what you're looking for. It not only does RAID monitoring, but all pretty much all hardware
Answer: openmanage is most useful for seeing the status of your raid, temps, etc that arn't available directly to the OS
Several of the drivers will improve performance/functionality over the default windows ones.  Usually you want at least chipset, networking and graphics
Comment: sounds like openmanage is the way to go. Now to attempt installing it from the report site, heh. Thanks!
Comment: After putting in about as much time as I can stand, I'm about ready to swear off altogether any software written by Dell. The installation process for OpenManage is a total mess, and the documentation is more full of holes than the maginot line.

Is there any way to accomplish the same simple raid monitoring with System Center stuff? I'd really rather learn that product if there's any comparable feature...I'm not terribly impressed with the value prospect of learning anything Dell at the moment.
Answer: From a driver persective yes you should install the ones you require. Openmanage will add drivers and software to interact with the management controller.  Everything else is either gravy or garbage depending on your point of view. Either way you certainly don't need it


How to prove that there exist exactly two non-similar isosceles triangles ABC such that tanA+tanB+tanC=100?

Question: I actually have a doubt about the solution of this question given in my book. It uses the equations tan 2A = - tan C (from A=B, A+B+C = 180 degrees) and 2 tan A + tan C = 100, thereby formulating the cubic equation $x^3 - 50x^2 + 50=0$. The discriminant is $3x^2- 100x$. Since $f(0) f(100/3) <0 $, it is found there are three distinct real roots. After this my book simply states that one of these roots is obtuse so the other two values are taken. Why is one of the values of A obtuse when we have used 2A + C = 180 degrees and an obtuse value of A would not satisfy this equation? Would someone please help?
Comment: that''s because equation $\tan x=a$ always has two solutions on the interval $[0, 2\pi)$. If $a>0$, one angle will be between $0$ and $\pi/2$ and the other one will be between $\pi$ and $3 \pi /2$. Solving cubic equation gives you value for $\tan A$. You need to check if the solution fits other parameters.
Answer: Since $A$ is the repeated angle, $A$ is acute so $x:=\tan A>0$. We must thus count the positive roots of $x^3-50x^2+50=0$. The roots have a negative product, $-50$, so there's one negative root plus two positive ones**. (They can't all be negative because their sum is $50$).
** Or a conjugate pair of non-real complex roots, which would result in no solutions to the original problem. But we can verify from a sign change on $[1, 2]$ that $x^3-50x^2+50$ has at least one positive root, so in fact it has two.
Answer: Because $$2\alpha+\gamma=180^{\circ}$$ or
$$\alpha=90^{\circ}-\frac{\gamma}{2}<90^{\circ},$$ which says that $\alpha$ is an acute angle and we need to take $x>0$ only.
Easy to see that the equation, which you got has two positive roots.
One on $(1,2)$ and the second on $(49,50)$.
There is also a negative root, which is not valid.


Has anyone ever taken pole position without setting any fastest sector times?

Question: During qualifying for the 2018 Mexican Grand Prix, Max Verstappen very nearly took pole position despite not setting the fastest time in any of the three sectors. (Other drivers had gone faster than him in individual sectors, but lost time in the other sectors.) Ultimately, Daniel Ricciardo pipped him to pole position by about 0.03s.
If Max had managed to take pole without "going purple" in any one sector, would that have been the first time it had happened? Or has anyone managed that before?
Comment: Not sure if there's a deleted answer mentioning this (the question is 'modified yesterday' as I write this), but this very weekend George Russell managed to do so. He also didn't reach the top speed.
Answer: It's hard finding the data for previous years, but the scenario you described actually happened in that same year, 2018, during the Azerbaijan Grand Prix.
According to the FIA, these were the best sector times in qualifying:

Sector 1: Kimi Raikkonen, 35.283
Sector 2: Kimi Raikkonen, 40.704
Sector 3: Esteban Ocon, 25.044

It gives us the combined "perfect lap": 1:41.031
However, the pole sitter was Vettel, with 1:41.498, who, as you can see, had no fastest (purple) sector.
As you may remember, the only reason Raikkonen didn't make the fastest lap that day was his oversteering at T16: https://youtu.be/xMnNQOgeWJ0?t=345. By the way, you can see in the video that Raikkonen has 2 purple sectors already, the third one belonging to Ocon.
Comment: I must have not noticed that at the time. Thanks!


What measure of training error to report for Random Forests?

Question: I'm currently fitting random forests for a classification problem using the randomForest package in R, and am unsure about how to report training error for these models.
My training error is close to 0% when I compute it using predictions that I get with the command:
predict(model, data=X_train)

where X_train is the training data.
In an answer to a related question, I read that one should use the out-of-bag (OOB) training error as the training error metric for random forests. This quantity is computed from predictions obtained with the command:
predict(model)

In this case, the OOB training error is much closer to the mean 10-CV test error, which is 11%.
I am wondering:

Is it generally accepted to report OOB training error as the training error measure for random forests?
Is it true that the traditional measure of training error is artificially low?
If the traditional measure of training error is artificially low, then what two measures can I compare to check if the RF is overfitting?
Answer: To add to @Soren H. Welling's answer.
1. Is it generally accepted to report OOB training error as the training error measure for random forests?
No. OOB error on the trained model is not the same as training error. It can, however, serve as a measure of predictive accuracy.
2. Is it true that the traditional measure of training error is artificially low?
This is true if we are running a classification problem using default settings. The exact process is described in a forum post by Andy Liaw, who maintains the randomForest package in R, as follows:
For the most part, performance on training set is meaningless.  (That's
the case for most algorithms, but especially so for RF.)  In the default
(and recommended) setting, the trees are grown to the maximum size,
which means that quite likely there's only one data point in most
terminal nodes, and the prediction at the terminal nodes are determined
by the majority class in the node, or the lone data point.  Suppose that
is the case all the time; i.e., in all trees all terminal nodes have
only one data point.  A particular data point would be "in-bag" in about
64% of the trees in the forest, and every one of those trees has the
correct prediction for that data point.  Even if all the trees where
that data points are out-of-bag gave the wrong prediction, by majority
vote of all trees, you still get the right answer in the end.  Thus
basically the perfect prediction on train set for RF is "by design".
To avoid this behavior, one can set nodesize > 1 (so that the trees are not grown to maximum size) and/or set sampsize < 0.5N (so that fewer than 50% of trees are likely to contain a given point $(x_i,y_i)$.
3. If the traditional measure of training error is artificially low, then what two measures can I compare to check if the RF is overfitting?
If we run RF with nodesize = 1 and sampsize > 0.5, then the training error of the RF will always be near 0. In this case, the only way to tell if the model is overfitting is to keep some data as an independent validation set. We can then compare the 10-CV test error (or the OOB test error) to the error on the independent validation set. If the 10-CV test error is much lower than the error on the independent validation set, then the model may be overfitting.
Answer: [edited 21.7.15 8:31 AM CEST]
I suppose you used RF for classification. Because in this case, the algorithm produces fully grown trees with pure terminal nodes of only one target class.
predict(model, data=X_train)

This line of coding is like a dog chasing [~66% of] its own tail. The prediction of any training sample is the class of the training sample itself. For regression RF stops if node has 5 or less samples in it or if node is pure. Here prediction error will be small but not 0%.
In machine learning we often work with large hypothesis spaces. This means there will always be many not yet falsified hypothesis/explanations/models to data structure of our training set. In classical statistics is the hypothesis space often small and therefore the direct model-fit is informative accordingly to some assumed probability theory. In machine learning does the direct lack-of-fit relate to the bias of the model. Bias is the "inflexibility" of the model. It does not in anyway provide a approximation of generalization power(the ability to predict new events). For algorithmic models cross-validation is the best tool to approximate generalization power, as no theory is formulated. However, if model assumptions of independent sampling fail, the model may be useless anyhow, even when a well performed cross-validation suggested otherwise. In the end, the strongest proof is to satisfyingly predict a number external test-sets of various origin.
Back to CV: Out-of-bag is often a accepted type of CV. I would personally hold that OOB-CV provides similar results as 5-fold-CV, but this is a very small nuisance. If to compare let's say RF to SVM, then OOB-CV is not usefull as we would normally avoid to bag SVM. Instead then both SVM and RF would be embedded in the exact same cross-validation scheme e.g. 10-fold 10-repeats with matching partitions for each repeat. Any feature engineering steps would often also be needed to be cross-validated. If to keep things clean the entire data pipe-line could be embedded in the CV.
If you tune your model with your test-set(or cross-validation) you're again inflating your hypothesis space and the validated prediction performance is likely over-optimistic. Instead you will need a calibration-set(or calibration CV-loop) to tune and a test validation set(or validation CV-loop) to assess your final optimal model.
In the extreme sense, your validation score will only be unbiased if your never act on this result, when you see it.  This is the paradox of validation, as why would we obtain a knowledge which is only true if you do not act on it. In practice the community willingly accepts some publication bias, where those researchers who got a over-optimistic validation at random are more likely to publish, than those who unluckily good a over-pessimistic validation. Therefore sometimes why can't reproduce others models.
Comment: Thank you for this. Two questions: (1) How is the prediction of any training sample the class of the training sample itself? There must be trees that do not use the training sample that are used in the majority vote procedure no? (2) So how would you assess if an RF measure is overfitting?
Comment: (1) well yes I was a little fast there, I edited the answer. Any sample will be inbag in ~66% of the trees. If a sample in a tree was inbag during training, it will end up in that same node during prediction in ~66%, and that is enough to win majority vote every time. Confirm this by lowering sampsize to e.g. 30% of train samples, and notice a rise from 0% classification error.

(2)  I think I answered that. RF does not per se overfit, but you can create a context during e.g. tuning where you will get a over-optimistic OOB-CV result. Embed your entire process in a new CV to know for sure.
Comment: Imagine that we train a RF with a training dataset and we saved the model, and we forgot to save the training dataset. So we lost the training dataset.... But one day we meet it again without knowing that it is the training dataset, what should we do to evaluate the this dataset?
Comment: the learner might store some information e.g. the target vector or accuracy metrics. Given you have some prior on where your datasets come from and understand the process of random forest, then you can compare the old trained RF-model with a new model trained on the candidate dataset. If the new and old model share enough similarities you may argue it is unlikely the models has not been trained on the same or almost same data. If you're being very nerdy about it, you realize RF models segmentize the feature space into hypercubes and each observation must fall into a set of  cubes.


Display content from mymodule_page in two regions

Question: Is the way, to put mymodule page content in region content, and sidebar programmatically without using blocks?
ex.
<code>function mymodule_page(){
    $page['content']['my'] = array(
         '#type' => 'markup',
         '#markup' => 'Test',
          ),
    $page['sidebar']['item'] = array(
          '#type' => 'markup',
          '#markup' => 'Test'
       );

 return $page;
}
</code>
Answer: No, not really, that's exactly what blocks are for. Without blocks, your module would need to send it's content to a region. And module should never need to know what theme you are using. If you would use a theme that doe snot have region you need, you would encounter an error.
Having that said, yes, you theoretically can do it. You would need to replicate what core module Block is doing, so it is way too broad to reliably cover in an answer. You can see Block's code if you want. You will use tens or hundreds times more man-hours to get this done than if you will just create a block with default region, or you will end up with significantly less stable and reliable code, but if it is something you really, really want to try, it is not impossible.
Comment: I have a three page that should generate content for regions ex. gallery. I'm using data supplied by the api. I thought I was able to close it in one function, not in 10 blocks
Comment: @Agrest if your question is not general in nature, but about specific code you are using, post the code, or at least the part that is relevant to the question. In question, of course, not in comments.