Extended limit laws for step by step evaluation of limits

Question: Most textbooks of calculus / real analysis present a version of limit laws which help us to infer about limit of sum or product of functions provided the limits of individual functions are known to exist. Such rules also go by the name algebra of limits.
In this post and my answer to it I provide an extended version of these laws which are more helpful in step by step evaluation of a limit. Before I state those laws it is better to give some introductory remarks.
If $f$ is a real valued function defined in certain deleted neighborhood of point $a$ then the limiting behavior of $f(x) $ as $x\to a$ can be of one of the following types:

$\lim_{x\to a} f(x) $ exists. Although it is redundant to state, to avoid confusion / ambiguity this means that the limit exists as a finite real number. We also say that $f(x) $ converges to a real number as $x\to a$. Example $\lim_{x\to 0}x$.
$f(x) \to \infty $ as $x\to a$. We say that $f(x) $ diverges to $\infty $ as $x\to a$ and some prefer to write this in symbols as $\lim_{x\to a} f(x) =\infty$. Example $\lim_{x\to 0} (1/x^2)$.
$f(x) \to - \infty $ as $x\to a$. We say that $f(x) $ diverges to $-\infty $ as $x\to a $ and some prefer to write this in symbols as $\lim_{x\to a} f(x) =-\infty$. Example $\lim_{x\to 0} (-1/x^2)$.
$f(x) $ oscillates finitely as $x\to a$. More formally this means that $f$ is bounded in some deleted neighborhood of $a$ and there exist at least two distinct real numbers $A$ and $B$ and two sequences $\{a_n\}, \{b_n\} $ of numbers in the deleted neighborhood of $a$ such that $$\lim_{n\to\infty} a_n=a=\lim_{n\to\infty} b_n$$ and $$\lim_{n\to\infty} f(a_n) =A, \lim_{n\to\infty} f(b_n) =B$$ Example $\lim_{x\to 0}(1/x)-\lfloor 1/x\rfloor$.
$f(x) $ oscillates infinitely as $x\to a$. This means that there is a sequence $\{a_n\} $ of numbers in deleted neighborhood of $a$ such that $$\lim_{n\to\infty} a_n=a, \lim_{n\to \infty} |f(a_n) |=\infty$$ and yet neither $f(x) \to\infty $ nor $f(x) \to-\infty $ as $x\to a$. Example $\lim_{x\to 0}(1/x)\sin(1/x)$.

The above list is exhaustive and consists of mutually exclusive possibilities. Sometimes the second and third options are combined together and one says that $f(x) $ diverges as $x\to a$. Similarly the fourth and fifth options can be combined to say that $f(x) $ oscillates as $x\to a$.
Now we come to extended limit laws.

Theorem 1: Let $f, g$ be functions defined in a certain deleted neighborhood of $a$ and let $\lim_{x\to a} f(x) $ exist and be equal to $L$. Then the limiting behavior of $f(x) \pm g(x) $ as $x\to a$ is of exactly the same type  as that of $g(x) $ and we can write $$\lim_{x\to a} \{f(x) \pm g(x) \}=\lim_{x\to a} f(x) \pm\lim_{x\to a} g(x) =L\pm\lim_{x\to a} g(x) $$ The case of divergence can be same or opposite (as regards to sign of $\infty$) depending on the sign $\pm$ which combines $f, g$.
Theorem 2: Let $f, g$ be defined in a certain deleted neighborhood of $a$ and let $\lim_{x\to a} f(x) =L\neq 0$. Then the limiting behavior of $f(x) g(x) $ as $x\to a$ is of exactly the same type as that of $g(x) $ and we can write $$\lim_{x\to a} f(x) g(x) =\lim_{x\to a} f(x) \cdot \lim_{x\to a} g(x) =L\lim_{x\to a} g(x) $$ The case of divergence can be same or opposite according as $L>0$ or $L<0$. Also the case of convergence holds when $L=0$ but other cases can't be guaranteed when $L=0$.

Both these theorems can be used to evaluate the limit of a complicated expression in a step by step manner by handling one term or one factor at a time whose limit is known thereby reducing the expression to a simpler form at each step. Each step is justified on the basis of the term/factor whose limit is known irrespective of the behavior of other terms/factors.
Moreover the theorems indicate that each step is reversible and hence holds unconditionally. This is better than using the standard limit laws which basically say that the limit has to be applied simultaneously on each part of the expression on the condition that each part has a limit and parts occurring as denominator have non-zero limit.

I will provide proof of one of the theorems as an answer (to be marked community wiki). I expect users to provide other point of views regarding these theorems and any improvements in my question and answer are also welcome.

Note: The above is a more formal and detailed version of the rules presented in this answer and it is based on a request in a comment to another question.
Comment: @DaveL.Renfro: you are right, but the concepts of limsup, liminf, are bit tricky to grasp. Also The post is already long (sorry :)) so I don't want to add them. Best would be that you add the equivalent formulation based on limsup /liminf as an answer if time permits.
Comment: I was searching for something I'd written and I came across something ELSE I'd written, and it occurred to me that this other thing I'd written might be of interest to you, at least if you wind up extending your formulations (or use another answer to extend your formulations) to limsup/liminf descriptions. (Presently, I'm not sufficiently interested or have time to do this myself.) See my answer to [Sufficient condition for equality of limsups](https://math.stackexchange.com/questions/2834649/sufficient-condition-for-equality-of-limsups/2834830#2834830).
Comment: @VerkhovtsevaKatya : also don't generalize a term to a linear combination.
Comment: @VerkhovtsevaKatya: I recommend only one book for those who read my answers (on calculus) and blog: *A Course of Pure Mathematics* by G H Hardy, 10th edition.
Comment: @Koro: you can also see that $fg$ won't converge because if it did converge to $L $ then $g=fg/f$ converges to $L/\infty=0$ (I hope you can do this rigorously). In short all your claims are correct and do try to give a rigorous proof. If you face any issue you can ask as a separate question. This will also help future readers of this site.
Comment: I use the terms "exists finitely" for case $1$ (or "converges"), "exists infinite" for case $2$ and $3$ (or "diverges") and doesn't exist otherwise. Your definitions are more detailed!
Comment: @gimusi: yes "exist finitely" is common in my country.
Comment: Thanks for that contribution, I'll take a closer look to that!
Comment: I'm just stopping by briefly, so I haven't absorbed everything you've written, but for me at least, once one is at this level of detail, you may as well use the properties of $\liminf$ and $\limsup,$ which not only reproduces all these results, but gives more general versions of them. For example, if one of the assumptions is that a limit exists finitely, then the assumption is really $\limsup = \liminf < \infty,$ which can then be incorporated into the conclusion.
Comment: Thanks @DaveL.Renfro. I will add a reference to your answer in my post after some time. Not everyone pays attention to fine details in comments.
Comment: @Andrew: It would be best if you can ask your problem as a question here. Nothing beats mathematics stack exchange when you want any help on solving a maths problem.
Comment: @ParamanandSingh, I was thinking of the term reversible (I ask just to understand it deeper), when we have e.g.: $\displaystyle\lim_{x\to 2}\frac{x^2-4}{x-2}$, is the canceling of $x-2$ reversible since it doesn't equal $0$? I would be thankful if you would include every further and past mistakes of mine to help others because I'm quite creative when it comes to making mistakes. Also, can I interpret the $\text{additive manner}$ in which replacing a term by its limit is allowed, as a linear combination?
Comment: @VerkhovtsevaKatya: cancelling is an algebraic manipulation which has nothing to do with calculus. You can and should apply such manipulation to simplify your expression. See [this answer](https://math.stackexchange.com/a/1822706/72031) for more details.
Comment: @ParamanandSingh, I read the question/answer carefully and see the point. Actually, many of my former teachers mixed the terms $\text{not defined at a certain point}$ and $\text{discontinuous}$ which is not the synonym, for example $f(x)=\frac{1}{x}$. I really admire your work and hope my colleagues will look for already answered questions here because they rely on assistants and a few of us who speak English. If you have time, here is a link to a math site of my colleague, teacher and best friend: http://halapa.com/
Comment: The only problem is the language, but students from all around the world send him tasks and I started helping him recently with English and formatting. I mentioned him beacuse he always talks about Indian mathematicians and their approach to problems. If you have any advice on the literature, I'll be glad to send him an e-mail.
Comment: @ParamanandSingh: I have seen this post before also when you had shared it in one of the comments.My only Qn. here is:if $f\to \infty$ and $g$ oscillates finitely when $x\to a$, say, can we say something about $\lim_{x\to a} f(x)g(x)$? More specifically, will it converge on $\mathbb R$? If $g$ oscillates between say $p$ and $q$  it follows that if $p$ and $q$ have the same sign then $fg\to \infty $ or $-\infty$ but the problem comes when $p$ and $q$ have opposite signs. In this case, my claim is $fg$ will oscillate infinitely and that is based on intuition. Can you help with the proof? Thanks.
Comment: @Koro:in this case $fg$ oscillates infinitely.
Comment: Thanks a lot @ParamanandSingh :). Sure. I'll ask as a separate question in case any  issue arises.
Answer: This is a proof of theorem 2 and is presented more as an outline and the details can be easily filled by anyone familiar with proofs of usual limit laws.
The case of convergence is the one usually presented in common textbooks and for this case it can be written explicitly as

Let $\lim_{x\to a} f(x) = L\neq 0$. The limit of $f(x) g(x) $ as $x\to a$ exists if and only the limit of $g(x) $ as $x\to a$ exists.

The "if" part is a direct application of usual product rule of limits. The "only if" part is also a consequence of the usual algebra of limits (mainly the quotient rule). Just write $h(x)=f(x) g(x)$ and then since $\lim_{x\to a} f(x) =L\neq 0$ by quotient rule we have $$\lim_{x\to a} g(x) =\lim_{x\to a} \frac{h(x)} {f(x)} =\frac{1}{L}\lim_{x\to a} h(x) $$
If $L=0$ then the "if" part holds but not the "only if" and thus the process of splitting the limits is not reversible.
Next we deal with the case of divergence and here we assume $L>0$. We then show that $f(x) g(x) $ diverges to $\infty$ as $x\to a$ if and only if $g(x) $ does so. First we deal with "if" part and thus let $g(x) \to \infty $ as $x\to a$. And consider any arbitrary $M>0$. By existence of limit of $f$ there is a $\delta_1>0$ such that $f(x) >L/2$ whenever $0<|x-a|<\delta_1$ (this is done by choosing $\epsilon=L/2>0$ in definition of limit). Again since $g(x) \to\infty $ there is a $\delta_2>0$ such that $g(x) > 2M/L$ (note the $L\neq 0$) whenever $0<|x-a|<\delta_2$. If $\delta=\min(\delta_1,\delta_2)$ then for $0<|x-a|<\delta$ we have $f(x) g(x) >(L/2)(2M/L)=M$ so that $f(x) g(x) \to\infty $ as $x\to a $. The case when $g(x) \to - \infty $ is similar. For $L<0$ the conclusion is same apart from a reversal of sign of infinity.
The "only if" part for divergence can be proved using the "if" part itself. Consider $G(x) =f(x) g(x), F(x) =1/f(x)$. Then by quotient rule $F(x) \to 1/L$ and $1/L$ has same sign as $L$. Thus by the proof in last paragraph $g(x) =F(x) G(x) $ diverges if $G(x) =f(x) g(x) $ diverges.
The case of oscillation presents no significant difficulty. Let's handle the case of  finite oscillation here. We show that $f(x) g(x) $ oscillates finitely as $x\to a$ if and only if $g(x) $ does so. We prove the "if" part and the "only if" part can be deduced from the "if" part as done in case of divergence. Since $f(x) \to L$ therefore $f$ is bounded in some deleted neighborhood of $a$. And since $g(x) $ oscillates finitely it is also bounded. The product $f(x) g(x) $ is thus bounded in some deleted neighborhood of $a$. There exist numbers $A, B, A\neq B$ and sequences $a_n, b_n$ such that $a_n\to a, b_n\to a$ and $g(a_n) \to A, g(b_n) \to B$. Since $f(x) \to L$ we have $f(a_n) \to L, f(b_n) \to L$ and by product rule for sequences we have $$f(a_n) g(a_n) \to LA, f(b_n) g(b_n)\to LB$$ Since $L\neq 0$ and $A\neq B$ we have $LA\neq LB$ and thus $f(x) g(x) $ also oscillates finitely as $x\to a$.
The crucial part to note here is that in each case the condition $L\neq 0$ makes the whole process reversible ie it changes "if" (one way implication) to "if and only if" (two way implication). This is important to validate the step by step application of the rule unconditionally.
A proof of theorem 1 is similar and one should try to understand why we don't need the requirement $L\neq 0$.


Python problem I only got 1 output every user input and not combined with the previous input

Question: How I can achieve this
enter image description here
Comment: Please provide the expected see [MRE - Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example).
Show where the intermediate results deviate from the ones you expect.  We should be able to paste a single block of your code into file, run it, and reproduce your problem.  This also lets us test any suggestions in your context.
Off-site links and images of text are not acceptable; your posting must be self-contained, in keeping with the purpose of this site.
Comment: while True:
 ask = (input("Enter a number: "))
 l = ask.split()
 print(sorted(l))
Comment: Critical updates must be edited into your question, not relegated to comments.
Comment: Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask)  to see how this site works and to help you improve your current and future questions, which can help you get better answers.
Answer: Create a List variable and append each Input in the variable. Something like that
a = []
a.append(int(input("Enter Message")))
print(a)

Comment: I've only getting this output.
 Enter a number: 12
[12]
Enter a number: 54
[54]
Enter a number: 76
[76]
Comment: Have you initialize a with list? like a= [] .For me it is working fine. I am on python 3.8

>>> a
[12, 13]
>>> a.append(int(input("Enter Message")))
Enter Message11
>>> a.append(int(input("Enter Message")))
Enter Message15
>>> a
[12, 13, 11, 15]
>>>
Comment: to clarify, the list must be initialized outside of the loop
Answer: inputs = []  # create an empty list
while True:  # loop forever
    inp = input("Enter a number or...")  # take user input
    if inp == "":  # if the user simply pressed enter the input would be empty
        break  # exit the loop
    inputs.append(int(inp))  # add the input to the list of inputs
    print(inputs)  # display the current list of inputs
print("Exiting")  # after the loop


Why does error rate of kNN increase when k approaches size of training set?

Question: I've been experimenting with the effect that different values of k have on the generalisation error of kNN classifier, and I've gotten some unexpected results towards the end when k approaches the size of the dataset.
The result that I get is the following:

How experiment was run:
The dataset is based on sklearn's make_circles method, set up with the following parameters n_samples=500, factor=0.5 and noise=0.3.
The generalisation error was calculated as follows:
For each k in k = np.linspace(1, train_size - 1, 100)
   {
      generate data
      `train_test_split` with `test_size=0.2`
      fit model
      predict model
      calculate error
   } repeat 100 times and get average error

My interpretation:
For k up 150 I'm happy with the results. For low values of k, the total error is dominated by variance, for higher values of k, the total error is dominated by bias. So we get the classic u-shaped plot.
As k gets larger, the error rate converges to 50%. This also makes sense, since as you increase the value of k, you start considering a large enough portion of your dataset such that your predictor will just give you the class that appears more frequently in the training set. Since the classes are split equally, and it's a binary classification problem, we expect our model to get the right answer 50% of the time.
What I don't understand is why there seems to be an increase in the error rate for values of k> 370. I would have expected it to stay as is, getting right 50% of the time? Does anyone know why this would be the case?
I've tried running the experiment multiple times, and have also looked at the range form 370 to 399 more closely. Here is a plot:
Comment: Is this something you get repeatedly every time when running the same experiment?
Comment: Yes, I will update the post with some more plots
Comment: I'd suggest doing a sort of leave one out validation scheme rather than having a test set equal to 20% of your data. KNN works a little different than the typical ML workflow in that there is no model being trained. For your 100 records in the test set you need to calculate a new set of K for each so removinng the other 99 records from the possibility of being in K hampers them needlessly
Answer: Adding my guess as an answer.
When splitting the data into train/test sets you do a 0.8/0.2 split. Which, with the sample size of 500, should be 400/100. Then you train kNN on 400 and test the accuracy on the remaining 100.
If the split is random, then the class balance will not be equal. Hence, the classifier will learn to predict the more frequent class on the training set, but due to the split the same class will be less frequent in the remaining (test) set. As a result, after the point the classifier starts to always return the more frequent class, your error, will be less than 50% on the training data but more than 50% on the testing data.
Your error (close to 55%) is also consistent with this interpretation. Here is a quick R simulation (ran 10000 times) to check the average error we expect on the testing set with such a strategy:
mean(replicate(10000, max(table(sample(rep(letters[1:2], each=250), 100)))))
[1] 53.5586

NOTE: for the simulation I didn't do any classification but simply simulated drawing random 100 samples out of equally balanced set of 500 samples and checking the frequency of higher class (the class your method would misclassify at k = 400).
For why this starts to happen at around k=385 - my guess is that this is the breaking point when the classifier starts to simply predict the most frequent class. Or in other words - within your training data there is about 15 samples worth of imbalance between the classes. And up to that point the classifier fluctuates between one class and another, but after this point each additional neighbour will be of the majority class.


Prove that the directrix-focus and focus-focus definitions are equivalent

Question: (NOTE: This is my attempt at answering this question and  this question, but I rewrote it in order to make it easier for me to solve. Also, I've made a YouTube video explaining this whole proof. Note that @Blue has a proof for this question with Dandelin spheres.)
We have two definitions of an ellipse and a hyperbola.

An ellipse is the locus of points that has a constant ratio of distance between a focus (point) and a directrix (line), where that constant ratio is between 0 and 1.

Here, the eccentricity is $\frac C A$, which, by this definition, must be a constant less than 1 for every point on the ellipse.

A hyperbola is the locus of points that has a constant ratio of distance between a focus (point) and a directrix (line), where that constant ratio is greater than 1.

Here, the eccentricity is $\frac{C_1}{A_1}=\frac{C_2}{A_2}$, which, by this definition, must be a constant greater than 1 for each point on the hyperbola.

An ellipse is the locus of points which has a constant sum of distances between two foci.

Here, the eccentricity is $\frac{F}{D_1+D_2}$. According to this definition, $D_1+D_2$ is a constant for every point on the ellipse, so we'll just call it $D$. Obviously, $F$ is constant since it is just the distance between the foci, which doesn't change.

The hyperbola is the locus of points which has a constant difference of distances between two foci.

Here, the eccentricity is $\frac{F}{D_2-D_1}$. According to this definition, $D_2-D_1$ is a constant for every point on the hyperbola, so again, we'll just call it $D$. Obviously, $F$ is constant since it is just the distance between the foci, which doesn't change.
My question is:
$$\text{How do I prove these definitions are equivalent?}$$
Comment: This is essentially a duplicate of ["Eccentricity of an ellipse"](http://math.stackexchange.com/q/137374/409). [My answer](http://math.stackexchange.com/a/137462/409) gives a geometric/trigonometric proof of the connection between the definitions of eccentricity.
Comment: @Blue Thanks for the trig proof! Your question did not come up I Googled this issue or when Math StackExchange suggested similar questions, but I just added your proof to the top of my question. However, I don't think this is a duplicate because this is a completely different proof. Also, I made the question this way in order to explain it in my YouTube video. I needed to post this on Math StackExchange so I could easily mix images with Markdown and MathJax.
Comment: You should look up dandelin spheres
Comment: @Hrhm Yeah, I read Blue's solution and it was a lot nicer than mine.
Comment: I'll also post the proof of the "focus focus" property using Dandelion Spheres
Comment: Sorry, I should have read the question more carefully before I commented. I didn't see that you already read Blue's solution.
Answer: Now, to prove these definitions are equivalent, we're going to take the first definition and make an equation out of it. We will then manipulate it a little. Then, we'll do the same for the second definition and we'll get the second equation into the form of the first equation. Once we've done that, we will prove that the eccentricities are equal for both definitions of the eccentricity.
For the first definition, let's say the focus is $(a, b)$ and the directrix is $Ax+By+C=0$ (this is not the same $A$ and $C$ as discussed in the first definition). The distance to the focus is:
$$\sqrt{(x-a)^2+(y-b)^2}$$
The distance to the line is:
$$\frac{\lvert Ax+By+C \rvert}{\sqrt{A^2+B^2}}$$
However, by dividing $Ax+By+C=0$ by some factor, we can make $\sqrt{A^2+B^2}$ equal to 1, so we can get rid of the denominator.
The ratio of the distance to the point to the distance to the line is the eccentricity, which we will call $e$, so we have:
$$\frac{\sqrt{(x-a)^2+(y-b)^2}}{\lvert Ax+By+C \rvert}=e$$
Now, take the first equation and multiply both sides by the denominator to get rid of the fraction:
$$\sqrt{(x-a)^2+(y-b)^2}=e\lvert Ax+By+C \rvert$$
Square both sides to simplify things:
$$(x-a)^2+(y-b)^2=(eAx+eBy+eC)^2$$
Note that since $\sqrt{A^2+B^2}=1$, we have that:
$$e=e\sqrt{A^2+B^2}=\sqrt{(eA)^2+(eB)^2}$$
Thus, the eccentricity is the square root of the sum of the squares of the coefficients of $x$ and $y$ on the right side. This will become relevant later.

For the second definition, let's say one focus is $(a, b)$ and the other is $(c, d)$. The sum/difference of the distances is $D$, so we have:
$$\sqrt{(x-a)^2+(y-b)^2}\pm\sqrt{(x-c)^2+(y-d)^2}=D$$
Again, $+$ is for ellipses, $-$ is for hyperbola.

Also, since $F$ is the distances between the foci, we know that:
$$F=\sqrt{(a-c)^2+(b-d)^2}$$
Square both sides:
$$F^2=(a-c)^2+(b-d)^2$$
Divide both sides by $D^2$:
$$\left(\frac F D\right)^2=\left(\frac{a-c}{D}\right)^2+\left(\frac{b-d}{D}\right)^2$$
Take the square root of both sides and substitute $e=\frac F D$:
$$e=\sqrt{\left(\frac{a-c}{D}\right)^2+\left(\frac{b-d}{D}\right)^2}$$
This will come up again later on.

Now, back to where we were before this tangent. Square both sides:
$$\left(x-a\right)^2+\left(y-b\right)^2+\left(x-c\right)^2+\left(y-d\right)^2\pm2\sqrt{\left(\left(x-a\right)^2+\left(y-b\right)^2\right)\left(\left(x-c\right)^2+\left(y-d\right)^2\right)}=D^2$$
Get the radicand alone on the right side:
$$\left(x-a\right)^2+\left(y-b\right)^2+\left(x-c\right)^2+\left(y-d\right)^2-D^2=\mp2\sqrt{\left(\left(x-a\right)^2+\left(y-b\right)^2\right)\left(\left(x-c\right)^2+\left(y-d\right)^2\right)}$$
Square both sides:
$$\left(\left(x-a\right)^2+\left(y-b\right)^2\right)^2+\left(\left(x-c\right)^2+\left(y-d\right)^2\right)^2+2\left(\left(x-a\right)^2+\left(y-b\right)^2\right)\left(\left(x-c\right)^2+\left(y-d\right)^2\right)+D^4-2D^2\left(\left(x-a\right)^2+\left(y-b\right)^2+\left(x-c\right)^2+\left(y-d\right)^2\right)=4\left(\left(x-a\right)^2+\left(y-b\right)^2\right)\left(\left(x-c\right)^2+\left(y-d\right)^2\right)$$
Note that the $\mp$ has been removed by squaring. Now, subtract both sides by the expression on the right side:
$$\left(\left(x-a\right)^2+\left(y-b\right)^2\right)^2+\left(\left(x-c\right)^2+\left(y-d\right)^2\right)^2-2\left(\left(x-a\right)^2+\left(y-b\right)^2\right)\left(\left(x-c\right)^2+\left(y-d\right)^2\right)+D^4-2D^2\left(\left(x-a\right)^2+\left(y-b\right)^2+\left(x-c\right)^2+\left(y-d\right)^2\right)=0$$
Use the $a^2+b^2-2ab=(b-a)^2$ identity to simplify and rearrange the terms so it looks more like a quadratic in terms of $D^2$:
$$D^4-2D^2\left(\left(x-a\right)^2+\left(y-b\right)^2+\left(x-c\right)^2+\left(y-d\right)^2\right)+\left(\left(x-c\right)^2+\left(y-d\right)^2-\left(x-a\right)^2-\left(y-b\right)^2\right)^2=0$$
Fix the $D^2$ term so that it has the $(x-c)^2+(y-d)^2-(x-a)^2-(y-b)^2$ that's in the constant term:
$$D^4-2D^2\left(\left(x-c\right)^2+\left(y-d\right)^2-\left(x-a\right)^2-\left(y-b\right)^2\right)-2D^2\left(2\left(x-a\right)^2+2\left(y-b\right)^2\right)+\left(\left(x-c\right)^2+\left(y-d\right)^2-\left(x-a\right)^2-\left(y-b\right)^2\right)^2=0$$
Add both sides by the new term that is not part of the quadratic:
$$D^4-2D^2\left(\left(x-c\right)^2+\left(y-d\right)^2-\left(x-a\right)^2-\left(y-b\right)^2\right)+\left(\left(x-c\right)^2+\left(y-d\right)^2-\left(x-a\right)^2-\left(y-b\right)^2\right)^2=2D^2\left(2\left(x-a\right)^2+2\left(y-b\right)^2\right)$$
Use the $a^2-2ab+b^2=(a-b)^2$ identity to simplify the left side. Also, factor out the $2$ from the right side:
$$\left(\left(x-c\right)^2+\left(y-d\right)^2-\left(x-a\right)^2-\left(y-b\right)^2-D^2\right)^2=4D^2\left(\left(x-a\right)^2+\left(y-b\right)^2\right)$$
Simplify the left side more by expanding the quadratics and subtracting like terms. Also, write $(2D)^2$ on the right side:
$$\left(2\left(a-c\right)x+c^2-a^2+2\left(b-d\right)y+d^2-b^2-D^2\right)^2=\left(2D\right)^2\left(\left(x-a\right)^2+\left(y-b\right)^2\right)$$
Now, divide both sides by $(2D)^2$:
$$\left(\frac{a-c}{D}x+\frac{b-d}{D}y+\frac{c^2-a^2+d^2-b^2-D^2}{2D}\right)^2=\left(x-a\right)^2+\left(y-b\right)^2$$
Switch both sides of the equation:
$$\left(x-a\right)^2+\left(y-b\right)^2=\left(\frac{a-c}{D}x+\frac{b-d}{D}y+\frac{c^2-a^2+d^2-b^2-D^2}{2D}\right)^2$$
Now, we have the equation in the same form as the first equation. However, we still need to check that the definition of eccentricity from the first equation is equal to the definition of eccentricity from this equation. As we said above from the first equation, $e$ is the square root of the sum of the squares of the coefficients of $x$ and $y$ on the right side, which means that here, according to the first equation, the eccentricity is:
$$e=\sqrt{\left(\frac{a-c}{D}\right)^2+\left(\frac{b-d}{D}\right)^2}$$
However, this is the exact same eccentricity we derived for the second equation, so the eccentricities are equal.
Thus, we are done and both definitions are equivalent with equivalent eccentricities for both ellipses and hyperbolas.
Comment: The algebra in your question can be simplified a lot by choosing the coordinate axes properly. If $e$ is the eccentricity then it is possible to choose coordinate axes such that $(ae, 0)$ is focus and $x = a/e$ is the directrix of the ellipse where $a$ is some specific constant depending on the given focus and diectrix.
Comment: @ParamanandSingh Oh...I didn't even think of that at all! Thanks for the tip!
Comment: @ParamanandSingh when you say "it is possible to choose coordinate axes such that (,0)
 is focus and =/
 is the directrix of the ellipse", how do you know to set the equation of the directrix as a vertical line? ie x=something, as opposed to a more general y=mx+c. is it trivial that the directrices are prependicular to the focal axis?
Comment: @NicolasSamanez: well, it is a property of ellipse that the focal axis is perpendicular to the directrix.
Answer: Proof of Focus Focus:

Sphere $G_1$ is tangent to the plane the ellipse is contained on at point $F_1$. It is also tangent to the cone at circle $k_1$
Sphere $G_2$ is tangent to the same plane at point $F_2$. It is also tangent to the cone at $k_2$.
Connect the apex of the cone, $S$, to any point on the ellipse, $P$, with a line. Mark the intersection points of this line with circles $k_1$ and $k_2$ $P_1$ and $P_2$ respectively.
Since segments $PP_1$ and $PF_1$ are both tangent to sphere $G_1$, they are the same length.
Similarly $PP_2$ and $PF_2$ are both the same length.
So $PF_1+PF_2=PP_1+PP_2=P_1P_2$. Since $P_1P_2$ remains constant as $P$ moves around the ellipse, $PF_1+PF_2$ is also constant.
Comment: This proof establishes the equivalence of two definitions of ellipse: 1) they are sections of cone by a plane. 2) they satisfy focus-focus property. It does not deal with focus-directrix. Moreover the figure seems to indicate that the cone is right circular, the result is true even if cone is not right, but circular. The link to focus directrix is shown at http://paramanands.blogspot.com/2012/06/conics-and-the-cone-part-1.html
Comment: Wow, this is a really short and effective proof that ellipses have two foci. Thanks!
Comment: @NobleMushtak No problem, glad to help!
Answer: If it can help here is a pure geometric demonstration (rather complex but it uses plane geometry and not the Dandelin spheres) that I devised some years ago for the ellipse (reference: https://www.physicsforums.com/threads/ellipse-geometric-equivalence-of-two-definitions.247417/).
I'm not much satisfied with it (especially in the second part that is just sketched) and I'm positive it could be significantly improved.

First part
Given the locus of points for which is constant the sum of the distances from two fixed points $F_1$ and $F_2$ then for any point $P$ belonging to the locus it is $PF_1=e\cdot PH_1$, where $PH_1$ is the distance form an appropriate fixed line (directrix) perpendicular to the line joining $F_1$ and $F_2$.
Demonstration
Let it be $F_1F_2=2c; \; \; PF_1+PF_2=2a; \; \; c/a=e; \; \; PF_1=f_1; \; \; PF_2=f_2; \; \; PH_1=d_1; \; \; PH_2=d_2$;
First, consider the triangle $F_1F_2P$, and construct the circumscribed circle around it.
The perpendicular bisector of the segment $F_1F_2$ meets the circle in $V$ (and the quadrilateral $VF_1F_2P$ is a cyclic quadrilateral).
Let's call $N$ the intersection of this line with the line joining $F_1$ and $F_2$, and we'll call $NF_1=m_1$; $NF_2=m_2$;
Since $F_1V=F_2V$, it follows, for the chord properties, that the segment $PV$ bisects the angle $F_1PF_2$, so that $F_1PN=NPF_2=F_1F_2V=\alpha$
Applying the angle bisector theorem to the triangle $F_1PF_2$ we have $$f_1:m_1=f_2:m_2$$ It's also $$(f_1+f_2):f_1=(m_1+m_2):m_1 \; \; \rightarrow \; \; 2a:f_1=2c:m_1 \; \; \rightarrow \; \; m_1/f_1=c/a$$ and $$(f_1+f_2):f_2=(m_1+m_2):m_2 \; \; \rightarrow \; \; 2a:f_2=2c:m_2 \; \; \rightarrow \; \; m_2/f_2=c/a$$
The triangles $H_1PF_1$ and $F_1PN$ are similar (they have the same angle $\alpha$ and two alternate interior angles). So, also the triangles $H_2PF_2$ and $F_2PN$ are similar.
Thence it is $$m_1:f_1=f_1:d_1=c/a$$ and $$m_2:f_2=f_2:d_2=c/a$$ whence
$$f_1:d_1=f_2:d_2=c/a$$ that proves the statement.
Second part
Given the locus of points for which the ratio between the distances from a fixed point $F_1$ (focus) and a fixed line (directrix) has a constant value that is larger than $0$ and less than $1$, then
1) There exists a second focus $F_2$ and a second directrix for which the same relation applies
2) For any point $P$ belonging to the locus the sum of the distances of $P$ to the foci $F_1$ and $F_2$ has a constant value.
Demonstration of 1)
Basically, starting from the focus $F_1$, the directrix, a point $P$ belonging to the locus, and calling $H_1$ the perpendicular projection of $P$ on the directrix it's possible to build the triangle $PF_1H_1$, and the similar triangle $PF_1N$. The lines $PN$ and $H_1F_1$ meets at a point $V$. The second focus $F_2$ is such that the line $PV$ bisects the angle $F_2PF_1$.
Having built the same figure as in the demonstration of the first part, it follows that the focus $F_2$ is the second focus and the line $VF_2$ intersects the line $H_1P$ in the point $H_2$ that defines the position of the second directrix.
Demonstration of 2)
Since $$f_1:d_1=f_2:d_2=e$$ it follows that $$f_1=e\cdot d_1$$ and $$f_2=e\cdot d_2$$Summing the terms it is $$f_1+f_2=e \cdot (d_1+d_2)=e \cdot H_1H_2$$ so that the sum of the distances of $P$ to the foci $F_1$ and $F_2$ has a constant value.
Answer: This is an old question, but I found a very short proof for an ellipse (shown in Heinemann Modular Mathematics P5) which I haven't seen elsewhere on the internet. It requires both foci and directrices.
For a general ellipse (I don't have enough reputation to display it.)
The equations of the directrices upon which F and E lie are $x=-\frac ae$ and $x=\frac ae$ respectively.
From the focus-directrix property:
$$ PS = ePE, \; PT = ePF $$
Summing them gives:
$$ PS + PT = e(PE+PF) $$
But,
$$ PE+PF = EF = \frac{2a}{e} $$
So:
$$ PS + PT = e\left(\frac{2a}{e}\right) $$
Which results in the focal distances property:
$$ PS + PT = 2a $$


restriction on the domain of composition of functions

Question: In a set theory class I was taught composition of functions as a special case of composition of relations, and to think of dom $g\circ f$ as dom $f \cap f^{-1}[$dom $g]$.
Then when we speak of composition of two functions $f$ and $g$, do we allow both the cases that dom $g \subset$ im $f$ and im $f$ $\subset$ dom $g$?
Answer: In $(g \circ f)(x) = g(f(x))$, we input the output of $f$ into $g$.  The domain of $g$ should be large enough to contain the range of $f$ so that this is well defined.  (i.e. $\mathop{\rm im} f \subseteq \mathop{\rm dom} g$)
For a counterexample, take $g(y) = \sqrt{16 - y^2}$ so that $\mathop{\rm dom}g = [-4,4]$ (is small enough); and $f(x) = x$.  If $|x|>4$ (is large enough), $g(f(x))$ is undefined.

picture from UCR Math Wiki

When we speak of $g \circ f$, we don't necessarily have $\mathop{\rm dom} g \subseteq \mathop{\rm im} f$, but you can restrict $\mathop{\rm dom} g$ so that they become equal.
For exampe, take $f: \Bbb R \to [-1,1]$ as $f(x) = \sin x$, and $g: \Bbb R \to \Bbb R$ as $g(x) = x$.  $\mathop{\rm im} f = [-1,1]$ can't contain $\mathop{\rm dom} g = \Bbb R$.

Image from Wiki


Copiar uma List para outra List sem dependências

Question: Como faço para copiar dados de uma list para outra de forma que fiquem independentes uma da outra? Tenho uma list<> de uma classe que criei onde os dados nela inseridos, vão aparecendo numa listBox, e queria copiar tudo o que está nessa list para uma nova. Eu consegui copiar tudo de uma para outra, mas quando trabalho com a segunda lista, a original (primeira list) sofre alterações indesejadas.
Esta é a minha classe:
public class vao
{
    public int quantidade { get; set; }
    public double medida { get; set; }
}

Esta é a forma como estou a inserir os dados na list e a fazer com que sejam
apresentados na listbox.
    List<vao> vaos = new List<vao>();
    List<vao> ordenada = new List<vao>();

    private void button1_Click(object sender, EventArgs e)
    {
        vao A = new vao();
        A.quantidade = Convert.ToInt32(textBox1.Text);
        A.medida = Convert.ToDouble(textBox2.Text);
        vaos.Add(A);

        listBox1.Items.Clear();
        foreach (vao item in vaos)
        {
            listBox1.Items.Add(item.quantidade + " x " + item.medida);
        }

        textBox1.Text = "";
        textBox1.Focus();
        textBox2.Text = "";
    }

E esta forma é como estou a copiar tudo de uma list(vaos) para a list(Ordenada)
e a apresentar o que esta na list(ordenada) numa nova listbox da forma que desejaria.
private void button3_Click(object sender, EventArgs e)
    {
        ordenada = vaos;

        for (int i = 0; i <= ordenada.Count - 1; i++)
        {
            for (int j = i + 1; j < ordenada.Count; j++)
            {
                if (ordenada[i].medida < ordenada[j].medida)
                {
                    int aux_qt = ordenada[i].quantidade;
                    ordenada[i].quantidade = ordenada[j].quantidade;
                    ordenada[j].quantidade = aux_qt;

                    Double aux_med = ordenada[i].medida;
                    ordenada[i].medida = ordenada[j].medida;
                    ordenada[j].medida = aux_med;
                }
            }
        }

        listBox2.Items.Clear();
        foreach (var item in ordenada)
        {
            listBox2.Items.Add(item.quantidade + " x " + item.medida);
        }

    }

Neste caso inseri as quantidades e as medidas e carreguei para copiar e ordenar.

Quando selecciono um index da lista Original os valores que têm são os que estão na lista Ordenada
Answer: Faz com LINQ que é mais fácil:
using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main(string[] args) {
        var vaos = new List<Vao> {new Vao {Quantidade = 2, Medida = 2}, new Vao {Quantidade = 0, Medida = 0}, new Vao {Quantidade = 1, Medida = 1}};
        var ordenada = new List<Vao>(vaos);
        ordenada = vaos.OrderBy(p => p.Medida).Select(item => item.Clone()).ToList();
        ordenada[1].Medida = 5;
        foreach (var item in ordenada) WriteLine($"{item.Quantidade} x {item.Medida}");
        foreach (var item in vaos) WriteLine($"{item.Quantidade} x {item.Medida}");
    }
}

public class Vao {
    public int Quantidade { get; set; }
    public double Medida { get; set; }
    public Vao Clone() => (Vao)this.MemberwiseClone();
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Tem várias coisas bem inadequadas nesse código, mas o que foi perguntado está aí.
Comment: Obrigado @bigown pelo seu comentário mas não resolveu o meu problema, continua a ter dependência. Quando a List ordenada faz as alterações, os index's mudam também na primeira. Já agora o que acha que está inadequado no meu código ?
Comment: @DiogoSousa Fiz uma mudança para clonar o objeto. Recomendo você fazer um [mcve] para mostrar o problema acontecendo. Tem vários problemas, no código, tudo coisa pequena, se fosse grande não funcionaria, mas que vai deixando o código ruim. Esse não é o foco aqui.
Comment: ♦ já coloquei algumas imagens para tentar mostrar o que me está a acontecer. Vou tentar fazer o que me disse do clonar o objecto. Obrigado
Answer: Quando se atribui uma lista à outra lista da forma tradicional ex: listaA = listaB. A listaA vai referenciar o mesmo espaço de memória da listaB. Com isso qualquer mudança dos objetos de uma das listas será alterada na outra lista.
A solução seria definir um novo local na memória para a listaA.
Uma solução possível seria criar uma classe com o atributo [Serializable]. Ex:
[Serializable]
public class Carro
{
     public int Codigo { get; set; }
     public string Marca { get; set; }
     public decimal Preco { get; set; }
     public bool AirBag { get; set; }
}

Criar um método para Clonar Objetos.
public static object ClonarObjeto(object objRecebido)
{
    using (var ms = new System.IO.MemoryStream())
    {
        var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        bf.Serialize(ms, objRecebido);
        ms.Position = 0;

        object obj = bf.Deserialize(ms);
        ms.Close();

        return obj;
    }
}

Enfim clonar os objetos:
List<Carro> listaCarros = new List<Carro>();
List<Carro> listaCarrosCopia = new List<Carro>();

listaCarros.Add(carroA);
listaCarros.Add(carroB);

foreach (Carro item in listaCarros)
    listaCarrosCopia.Add((Carro)ClonarObjeto(item));

Agora teremos duas listas independentes.
Comment: Muito obrigado, resultou e me ajudou muito!


How do I order or rank a set of experts?

Question: I have a database containing a large number of experts in a field. For each of those experts i have a variety of attributes/data points like:

number of years of experience.
licenses
num of reviews
textual content of those reviews
The 5 star rating on each of those reviews, for a number of factors like speed, quality etc.
awards, assosciations, conferences etc.

I want to provide a rating to these experts say out of 10 based on their importance. Some of the data points might be missing for some of the experts. Now my question is how do i come up with such an algorithm? Can anyone point me to some relevent literature?
Also i am concerned that as with all rating/reviews the numbers might bunch up near some some values. For example most of them might end up getting an 8 or a 5. Is there a way to highlight litle differences into a larger difference in the score for only some of the attributes.
Some other discussions that i figured might be relevant:

Bayesian rating system with multiple categories for each rating
How would YOU compute IMDB movie rating?
Eliciting priors from experts
What are some of the best ranking algorithms with inputs as up and down votes?
Comment: It can't be done unless you come to some objective criterion; probably most of possible ratings can be constructed with some combination of your parameters.
Answer: People have invented numerous systems for rating things (like experts) on multiple criteria: visit the Wikipedia page on Multi-criteria decision analysis for a list.  Not well represented there, though, is one of the most defensible methods out there: Multi attribute valuation theory.    This includes a set of methods to evaluate trade-offs among sets of criteria in order to (a) determine an appropriate way to re-express values of the individual variables and (b) weight the re-expressed values to obtain a score for ranking.  The principles are simple and defensible, the mathematics is unimpeachable, and there's nothing fancy about the theory.  More people should know and practice these methods rather than inventing arbitrary scoring systems.
Comment: @user No, and I doubt there is one.  There's no magic software bullet here, by the way: almost all the work involves thinking through the issues and exploring specific trade-offs in a controlled fashion.
Comment: Do you know of R package for doing this?
Answer: Ultimately this may not be solely a statistical exercise.  PCA is a very powerful quantitative method that will allow you to generate a score or weights on its first few principal components that you can use for ranking.  However, explaining what the principal components are is very challenging.  They are quantitative constructs.  They are not dialectic ones.  Thus, to explain what they truly mean is sometimes not possible.  This is especially true if you have an audience that is not quantitative.  They will have no idea what you are talking about.  And, will think of your PCA as some cryptic black box.
Instead, I would simply line up all the relevant variables and use a weighting system based on what one thinks the weighting should be.
I think if you develop this for outsiders, customers, users, it would be great if you could embed the flexibility of deciding on the weighting to the users.
Some users may value years of experience much more than certification and vice verse.  If you can leave that decision to them.  This way your algorithm is not a black box they don't understand and they are not comfortable with.  You keep it totally transparent and up to them based on their own relative valuation of what matters.
Comment: +1 for pointing out this is not a statistical exercise.  At best, PCA can describe relationships within a particular data set and, conceivably, simplify the data by identifying near-collinearities.  It is not apparent how it can inform us about how to *rank* the experts.
Comment: @Gaetan Well, for PCA you have to find a suitable numerical coding for variable such as "textual content"...
Comment: That's not the issue I am raising.  PCA can handle dummy variables as you suggest.  PCA is incredibly powerful and flexible that way.  But, it is the interpretation of the principal components that gets really challenging.  Let's say the first principal component starts like this: 0.02 years of experience - 0.4 textual content of reviews + 0.01 associations...  Maybe you can explain it.  An expert performance is proportional to years of experience, but inversely proportional to textual content of reviews?  It seems absurd.  But, PCA often does generate counter-intuitive results.
Comment: @Gaetan Still, I reiterate my opinion that the problem lies in how you choose to represent your variables (or how you find a useful metric). I agree with you about the difficulty of interpreting a linear combination of variables when dealing with non-continuous measurements or a mix of data types. This is why I suggested in another comment to look for alternative factorial methods. Anyway, developing scoring rules based on user preferences or expert reviewing (as is done in clinical assessment) also calls for some kind of statistical validation (at least to ensure scores reliability).
Comment: @Gaetan, Yes some of your comments make a lot of sense, and you're right in saying that it is not merely a statistical exercise but involves elements that are more subjective. The reason being that the intent from a user/customers standpoint might differ. Assuming he's doing a search for an expert, then i just add filters to allow him to select experts >X number of years of experience and so on But let's say he's narrowed down to 2 experts, and wants an independent comparison. So i'm just looking for a generic method to compare any two experts.
Comment: @Gaetan, So yes i'm assuming i can somehow quantify all of the attributes, which again might be subjective. But anyhow i see some interesting points in this discussion and will think some more on that before commenting further.
Comment: @chl numerical coding for "textual content", could be as simple as some sort of sentiment analysis and giving them a binary value of good/bad?
Comment: @Sidmitra, your comments make sense.  Maybe you will derive good use out of PCA after all.  I would suggest you may run PCA several times by deriving the simplest and most explainable models that still explains most of the variance between experts.  By doing so, hopefully you may end up with a PCA model with principal components that are readily explainable to others and to yourself.
Answer: Do you think that you could quantify all those attributes?
If yes, I would suggest performing a principal component analysis. In the general case where all the correlations are positive (and if they aren't, you can easily get there using some transformation), the first principal component can be considered as a measure of the total importance of the expert, since it's a weighted average of all the attributes (and the weights would be the corresponding contributions of the variables - Under this perspective, the method itself will reveal the importance of each attribute). The score that each expert achieves in the first principal component is what you need to rank them.
Comment: It seems to me the first component will merely point out a strong direction of commonality among the experts.  How could it possibly tell us who is better and who is worse, though?  That requires additional information concerning the relationships between these variables and the quality of being a "good" or "bad" expert.  If we believe all the variables are monotonically associated with goodness or badness, then perhaps PCA can help us explore the frontier of extreme (or maybe just outlying!) experts.  Watch out though--even the monotonicity assumption is suspect.
Comment: This looks nice, but won't it just pick highest-variance attributes and biggest clusters of cross-correlated ones?
Comment: Alternatively, one can perform *multiple correspondence analysis* or *multiple factor analysis* for mixed data (if numerical recoding happens to be not realistic for some variables), and the rest of your idea (computing factor scores and looking at variable loadings on the 1st dimension) applies as well.
Comment: @whuber I see the point, thanks. Maybe you could add this in your own response (which is very welcomed)?


Combine two dictionaries and replace keys with values in powershell

Question: i have two arrays that look like this:
$ht1 = @{

"computer55" = "port33"

"computer1" = "port1"

"computer2" = "port2"

}

and
$ht2 = @{

"A1:B2:C3:D4:E5:F6" = "port1"

"A2:B3:C4:D5:E6:F7" = "port2"

"A3:B4:C5:D6:E7:F8" = "port33"

"A4:B4:C5:D6:E7:F8" = "port45"
}

The first one is one I manually hardcode into the script, I have an actual list of device names and what port they are plugged into on a switch. The second one is generated with a switch script that logs in, gets the mac address table and records it as a hashtable.
My desired outcome is this, if there is a port with an assigned name, replace the port name with the device name.
$ht3(or any name) = @{

"A1:B2:C3:D4:E5:F6" = "computer1"

"A2:B3:C4:D5:E6:F7" = "computer2"

"A3:B4:C5:D6:E7:F8" = "computer55"

"A4:B4:C5:D6:E7:F8" = "port45"
}

I've somehow spent about a day on this(... pretty much the first powershell script I've ever came up with) and my end result is always the same, I end up merging two hashtables and pair the port with the computer name and not the mac address with the computer name. any direction is appreciated
Answer: Important note, the .ContainsValue method is case sensitive, if you want a case insensitive search use one of the following:
if($val = [string]$ht1.Keys.Where({$ht1[$_] -eq $ht2[$key]}))
{
    @{$key = $val}
    continue
}

if($ht1.Values -contains $ht2[$key])
{
    ...
}

if($ht2[$key] -in $ht1.Values)
{
   ...
}

Code
$ht1 = @{
    computer55 = 'port33'
    computer1 = 'port1'
    computer2 = 'port2'
}

$ht2 = @{
    'A1:B2:C3:D4:E5:F6' = 'port1'
    'A2:B3:C4:D5:E6:F7' = 'port2'
    'A3:B4:C5:D6:E7:F8' = 'port33'
    'A4:B4:C5:D6:E7:F8' = 'port45'
}

$result = foreach($key in $ht2.Keys)
{
    if($ht1.ContainsValue($ht2[$key]))
    {
        @{$key = [string]$ht1.Keys.Where({$ht1[$_] -eq $ht2[$key]})}
        continue
    }
    @{$key = $ht2[$key]}
}

Looking at $result yields:
Name                           Value
----                           -----
A1:B2:C3:D4:E5:F6              computer1
A3:B4:C5:D6:E7:F8              computer55
A4:B4:C5:D6:E7:F8              port45
A2:B3:C4:D5:E6:F7              computer2

[string]$ht1.Keys.Where({$ht1[$_] -eq $ht2[$key]})

Could also be the following, though, I'm not sure which one would be more efficient:
$ht1.GetEnumerator().Where({$_.Value -eq $ht2[$key]}).Key

Comment: man, what a simple solution for something i spent a really long time on. thanks.
Comment: @jsss happy to help, this is a fun exercise :)


Como exibir nome do objeto no template do Django?

Question: Olá!
Estou em um processo de aprendizagem do Django, na realidade, comecei faz pouquíssimo tempo e estou encontrando dificuldades ao encontrar uma forma de exibir o nome da editora que é uma ForeignKey. Seguem os códigos abaixo:
Meu models.py
    titulo_livro = models.CharField(
        max_length = 45
        )
    subtitulo_livro = models.CharField(
        max_length = 45,
        null = True,
        blank = True
        )
sinopse_livro = models.TextField(
        max_length = 1000
        )
    avaliacao_livro = models.DecimalField(
        max_digits = 2,
        decimal_places = 2
        )
    isbn_livro = models.CharField(
        max_length = 13
    )
    publicacao_livro = models.DateField(
        auto_now = False,
        auto_now_add = False
        )
    editora_cod_editora = models.ForeignKey(
        'Editora',
        on_delete = models.CASCADE
        )
    categoria_cod_categoria = models.ForeignKey(
        'Categoria',
        on_delete = models.CASCADE
        )

    class Meta:
        db_table = 'Livros'

# CLASSE PARA A CRIAÇÃO DA TABELA DE EDITORAS
class Editora(models.Model):
    nome_editora = models.CharField(
        max_length = 45
        )
    class Meta:
        db_table = 'editora'

Meu forms.py
class LivrosFormulario(forms.ModelForm):
    class Meta:
        model = Livros
        fields = ['titulo_livro','subtitulo_livro','sinopse_livro','avaliacao_livro','isbn_livro','publicacao_livro','editora_cod_editora','categoria_cod_categoria',]

A view.py que estou penando para entender
def livro(request):
    if request.method == 'POST':
        form = LivrosFormulario(request.POST or None)
        e = Editora.objects.values('nome_editora')
        print(form.errors)
        if form.is_valid():
            print("form é válido")
            try:
                form.save()
                print("form salvo")
                return redirect('/mostrar')
            except:
                print("form não salvo")
                pass
        else:
            print("form não é válido")
    else:
        form = LivrosFormulario()
    return render(request, 'index.html', {'form':form})

E o Template index.html que deveria exibir o nome da editora, mas aparece apenas o id
<form method="POST" class="post-form" action="/livro">

      {% csrf_token %}

          Editora do Livro:

              {{ form.editora_cod_editora }}

          Categoria do Livro:

            {{ form.categoria_cod_categoria }}

            <button type="submit" class="btn btn-primary">Submit</button>

    </form>

Edit: Minha página fica assim:

Será que poderiam me dar alguma luz? Estou batendo a cabeça nisso faz um tempão kkkkk
Para informação: Estou usando a última versão estável do Django e do Python
Grata!
Answer: Faça uma def str(self): dentro da classe do model da editora depois retorne o self.nome_editora
o models ficara mais ou menos assim:
class Editora(models.Model):
    nome_editora = models.CharField(
        max_length = 45
        )
    class Meta:
        db_table = 'editora'
    def __str__(self):
        return self.nome_editora

Answer: Acrescente à classe Editora o método__str__(), algo assim:
class Editora(models.Model):
    ...
    def __str__(self):
        return self.nome_editora

Isto fará com que o Django saiba como representar corretamente este objeto.


Implicit definition of the intersection of n hypersurfaces

Question: This is a follow-up to a question I asked previously.
Let ${F_i(\vec{x}),...,F_n(\vec{x})}$, $\vec{x} \in \mathbb{R}^n$ be a set of hypersurfaces.  I'm particularly interested in the case where $F_i$ is a polynomial.  Assume all $F_i$ are defined such that $F_i(\vec{x}) = 0 \forall \vec{x} \in \mathbb{R}^n$.  Therefore, the $F_i$ are the level sets corresponding to the level 0 for some $n+1$ dimensional hypersurfaces.  I would like to implicitly define their intersection.
If I am looking for a curve that lies entirely within the intersection, then it is known that such a curve will be mutually perpendicular to the gradient of each function.  Under certain conditions, this curve can be defined implicitly as follows:
Let $M = [\bigtriangledown F_1, ..., \bigtriangledown F_n]^T$ and let $\vec{v} \in Null(M)$.  Define the curve implicitly to be:
$$\dot{\xi} = C\vec{v(t)}, \xi(0) = \xi_0$$
Where $C$ is an arbitrary constant.
Now, can I do something similar to define the hypersurface of intersection implicitly?  Something like a differential equation where I integrate the entire null space?  I apologize for the lack of rigour in that question, but I'm not 100% sure how to approach it.
Comment: In your specific case the intersection must be quite trivial, since indeed all your examples are polynomial in nature. I feel that my sequence of comments is a bit vague as an answer, so let me see whether my too little spare time will allow come up with something more elaborate - but this won't change the underlying ideas exposed above.
Comment: If $F_i(\vec{x}) = 0 \ \forall \vec{x} \in \mathbb{R}^n$ then $F_i = 0$, and I am sure that this is not what you mean.
Comment: Think of $\Bbb R^2$: if $F_1, F_2$ are polynomials (as you are most interested in), then either $\{F_1 = 0\} \cap \{F_2 = 0\}$ is a *finite* number of points (is this what you want?), or $F_1$ and $F_2$ are proportional and the intersection is $\{F_1 = 0\}$ (again, is this what you want?). Something similar happens if you slightly relax $F_1, F_2$ to be analytic: either they are proportional, or their intersection has no accumulation point (and so is discrete). At least one of the functions must be non-analytic to get something non-trivial.
Comment: In \mathbb{R}^2 you are correct, but in higher dimensions you do in fact get a hypersurface of intersection.  I'd like to know how to implicitly or explicitly define that hypersurface
Comment: In $\Bbb R^n$ take $F_i (\vec x) = x_i$ (they are hyperplanes). Then their intersection is just the point $\vec 0$. This shows that the functions must be chosen carefully; if they *all* are too rigid (analytic, it seems), then the intersection is trivial. The same is true if they are not analytic but they intersect transversally. The problem is much trickier than you believe.
Comment: Those are good points.  In my particular case I actually have a bunch of hyperspheres, hyperplanes, and multilinear functions polynomials that are intersecting, but I'm interested in the general solution.  Is there any good way to start defining the problem better? (Oh, and since your comment does technically count as an answer, if you post it as such I will accept it for the bounty, due to my posting an imprecise question)
Answer: Let us define the map $F : \mathbb{R}^n \to \mathbb{R}^m$ so that $x \mapsto F(x) = \big(F_1(x), F_2(x), ..., F_m(x)\big)$. You have written that $m=n$, but I would not assume that a priori and for me $m \leq n$. Assume these $F_i(x)$ for $i=1,..., m$ are polynomials in $x \in \mathbb{R}^n$ with real coefficients, i.e. $F_i \in \mathbb{R}[x_1,...,x_n]$ where $i=1,...,m$. Then, the differential of the map, aka the tangent map to $F$, is $$dF_x = [\nabla F_1(x)^T,..., \nabla F_m(x)^T]^T$$ where $\nabla F_i(x)$ is the gradient of $F_i$ written as a row-vector, so $\nabla F_i(x)^T$ is its transposed (it is a column-vector). Observe $dF_x$ is an $m \times n$ matrix with polynomial coefficients and so it defines the tangent map $$dF_x : T_x\mathbb{R}^n \to T_x\mathbb{R}^m$$ By convention, all tangent vectors are column-vectors and all dual vectors are row-vectors. Assume that $\text{rank}\big(dF_{x_0}\big) = m$, i.e. the rank of $dF_x$ at a point $x_0$ is maximal. Then, generically, the rank of $dF_x$ is maximal for almost all $x \in \mathbb{R}^n$. In that case,  whenever $m=n$ the inverse mapping theorem (aka the inverse function theorem) applies and then $F$ is a local diffeomorphism and so the solutions to $F(x)=0$ are going to be isolated points. So let us assume that $m < n$.
Now if the rank of $dF_x$ is not $m$ generically, but less than $m$, then you need to run some sort of reduction in the ideal $\langle F_1(x),..., F_m(x) \rangle$  which is the polynomial ideal generated by the polynomials $F_i$. In other words, you need to find a minimal set of generator  $\langle \tilde{F}_1(x),..., \tilde{F}_k(x) \rangle = \langle F_1(x),..., F_m(x) \rangle$ where $k \leq m$. These minimal set of generators is an independent set of polynomials whose matrix of gradients will have rank $k$ generically. Finding the set of of independent generators can be done by running some sort of Groebner basis method or something else of that sort. I advise you to look that up carefully if you need it as I am a bit rusty on the subject. But let us assume that we have done that beforehand, that $k=m$ and that the $F_1, ... ,F_m$ is an independent set of polynomials so that the rank of $dF_x$ is generically $m$.
Next, consider the system $$dF_x (v) = 0 \,\,\, \text{ for } \,\,\, v \in T_x\mathbb{R}^n$$ Now, the tangent field of $n-m$ planes $$\ker(dF)_x = \{v \in T_x\mathbb{R}^n \, | \, dF_x (v) = 0 \}$$ is an integrable distribution of the tangent spaces to the leaves of the foliation $$F^{-1}(y) = \{x \in \mathbb{R}^n \, | \, F(x) = y \}$$ Observe you have a system of the form $dF_x(v) = 0$ where the matrix $dF_x$ is a matrix with polynomial coefficients. Thus you can solve the system as a system with polynomial coefficients, i.e. $dF_x$  is an $m \times n$ matrix with coefficients (entries, or elements) in the ring of polynomials $\mathbb{R}[x]$. This ring is a subring of the field of rational functions $\mathbb{R}(x) = \mathbb{R}(x_1,...,x_n)$, where the elements of the latter look like $\frac{P(x)}{Q(x)}$ with $P, Q \in \mathbb{R}[x]$. Now treat the linear system $dF_x(v_x) = 0$ as a linear system in the field $\mathbb{R}(x) $, since a lot of the linear algebra works in an arbitrary field, you can find a set of $n-m\,\,\ $ $\mathbb{R}(x)$-linearly independent vector-solutions $X_1(x), X_2(x), ... X_{n-m}(x)$, so that each $X_i$ is a vector column of dimension $n$ with rational coefficients (entries that are rational functions of $n$ variables). So if we define $X(x) = [X_1(x),..,X_{n-m}(x)]$, an $n \times (n-m)$ matrix with rational coefficients from  $\mathbb{R}(x)$, then
$$dF_x \, X = 0$$ Just like in the case of equations with integer coefficients, solved in the field of rational numbers, you can even find an appropriate polynomial such that if you multiply all the $X_i$ by it, you end up with $\mathbb{R}(x)$ linearly independent vector-columns $X_1(x), ... , X_{n-m}(x)$ with polynomial coefficients. Thus you have ended up  obtaining a set of polynomial vector fields $X_1(x), ... , X_{n-m}(x)$ that span the distribution $\ker(dF_x)$, i.e. they span the tangent spaces of the leaves of the foliation $F^{-1}(y)$.
These guys $X_1(x), ... , X_{n-m}(x)$ are exactly the analog of what you are referring to in your original posting. If you take the phase flows $x(t_i) = \Phi_i^{t_i}(x)$ of the vector fields $X_i(x)$, then $$\frac{d}{dt_i} \Phi_i^{t_i}(x) = X_i\big(\Phi_i^{t_i}(x)\big), \,\,\,\,\, \Phi_i^{0}(x) = x$$ and then the map $$\Psi_{x_0} \, : \, (t_1, t_2, ..., t_{n-m}) \, \mapsto \,\Phi_1^{t_1} \circ \Phi_2^{t_2} \circ ... \circ \Phi_{n-m}^{t_{n-m}}(x_0)$$ is a local chart for the leaf $M_{x_0} = \{x \in \mathbb{R}^n  \,\,|\,\,F(x) = F(x_0)\}$ passing through the point $x_0$.
Edit. Assume you are given a smooth vector field $X(x)$ in $\mathbb{R}^n$. Then component-wise, it can be written like a vector of $n$ smooth functions (in your case, even polynomial functions), depending on the $n$ vector $x=(x_1,...,x_n)$
$$
X(x) = \begin{bmatrix} \,
    X^1(x_1, ..., x_n)\\
    X^2(x_1, ..., x_n)\\
     \vdots\\
    X^n(x_1, ..., x_n) \,
\end{bmatrix}$$
Each vector field has a family of curves that are tangent to the vector field and through each point in space, there is exactly one such curve passing through that point, which means no two such curves intersect. These are the so called integral curves, also called phase curves, of the vector field $X(x)$. They are obtained as the solutions to the system of ODEs
\begin{align}
\frac{dx_1}{dt} &= X^1(x_1, ..., x_n)\\
\frac{dx_2}{dt} &= X^2(x_1, ..., x_n)\\
\vdots\\
\frac{dx_n}{dt} &= X^n(x_1, ..., x_n)
\end{align}  which in vector form is written as
$$\frac{dx}{dt} = X(x)$$
Now pick an arbitrary point $x_0$ in $\mathbb{R}^n$ and try to solve the initial value problem
\begin{align}
\frac{dx}{dt} &= X(x)\\
x(0) &= x_0
\end{align}
which means you are trying to find a curve $x=x(t)$ in $\mathbb{R}^n$ that is tangent to the vector field $X(s)$ and passes through the point $x_0$, i.e.
$$\frac{dx}{dt}(t) = X\big(x(t)\big) \,\,\, \text{ for all } \,\, t \in (-\varepsilon, \varepsilon) $$ and $x(0) = x_0$. By the classical theorems of ODEs, there exists exactly one such curve (existence and uniqueness of solutions of systems of smooth ODEs). Now, denote by $$x(t) = \Phi^t(x_0
)$$ for $t \in (-\varepsilon, \varepsilon)$ this curve, a notation which says that the curve depends on the parameter $t$ and on the initial condition $x_0$. When I change $t$, I move along the curve, but when I change $x_0$ I move from one curve tangent to the vector field $X$ to another. So technically we have a map
$$\Phi \, : \, (-\varepsilon, \varepsilon) \times \mathbb{R}^n \, \to \, \mathbb{R}^n$$ By another result of ODE theory, this map is a smooth map (in your case it is even real analytic, because your vector field is polynomial, which means real analytic). If you fix the parameter $t$, you get a diffeomorphism (bijection, smooth in both directions)
$$\Phi^t \, : \,  \mathbb{R}^n \, \to \, \mathbb{R}^n$$ It is a bijection because of the existence and uniqueness result for ODEs. For a fixed $x_0$ what you have is that
$$\frac{d}{dt} \Phi^t(x_0) = X\big(\Phi^t(x_0)\big)$$
$$\Phi^0(x_0) = x_0$$ This map $\Phi$ is called the phase flow map (or simply the phase flow) of the vector field. Again due to the existence  and uniqueness of solutions of smooth ODEs, for any $x \in \mathbb{R}^n$ and any $t, s \in (-\varepsilon, \varepsilon)$ the phase flow has the properties
$$\Phi^t\Big(\Phi^s(x)\Big) = \Phi^{t+s}(x)$$
$$\Phi^0(x) = x$$ In your case you have a (family of) $n-m$ hypersurface $F^{-1}(y_0) = \{x \in \mathbb{R}^n \, | \, F(x) = y_0\}$ where $y_0 \in \mathbb{R}^m$, which basically says that $x = (x_1,...,x_n) \in F^{-1}(y_0)$ if and only if
\begin{align}
&F_1(x_1, ..., x_n) = y_{1,0}\\
&F_2(x_1, ..., x_n) = y_{2,0}\\
& \,\,\,\, \vdots \\
&F_m(x_1, ..., x_n) = y_{m,0}\\
\end{align}
Moreover, you have $n-m$ such vector fields $X_1, ..., X_{n-m}$ all tangent to $F^{-1}(y_0)$. This means that you have $n-m$ phase flow maps $\Phi_1^{t_1}, ...., \Phi_{n-m}^{t_{n-m}}$ for depending on $n-m$ different independent parameters $(t_1, t_2,..., t_{n-m}) \in \mathbb{R}^{n-m}$. The fact that the vector fields are tangent is equivalent to the fact that for each $j = 1,...,n-m$
$$F\big(\Phi_j^{t_j}(x)\big) = F(x)$$ or in coordinates
$$F_i\big(\Phi_j^{t_j}(x)\big) = F_i(x)$$ for $i=1,..., m$.
If you compose the maps $$\Phi^{t_j}_j \, : \, \mathbb{R}^n \, \to \, \mathbb{R}^n$$ for $j=1,...,n-m$ you get again a map
$$\Psi(t_1,...,t_{n-m},x) = \Phi^{t_1}_1\Big(...\Phi^{t_{n-m}}_{n-m}(x)\Big) = \Phi^{t_1}_1\circ ... \circ\Phi^{t_{n-m}}_{n-m}(x)$$ where $$\Psi \, : \, \mathbb{R}^{n-m} \times \mathbb{R}^n \, \to \, \mathbb{R}^n$$ with the property that $$F\Big(\Psi(t_1,...,t_{n-m},x)\Big) = F\Big(\Phi^{t_1}_1\big(...\Phi^{t_{n-m}}_{n-m}(x)\big)\Big) = F\Big(\Phi^{t_1}_1\circ ... \circ\Phi^{t_{n-m}}_{n-m}(x)\Big) = F(x)$$ so if you fix a point $x_0 \in \mathbb{R}^n$ on the surface $F(x) = y_0$, meaning $F(x_0) = y_0$, you obtain a map
$$\Psi_{x_0}(t_1,...,t_{n-m}) = \Psi(t_1,...,t_{n-m},x_0)= \Phi^{t_1}_1\Big(...\Phi^{t_{n-m}}_{n-m}(x_0)\Big) = \Phi^{t_1}_1\circ ... \circ\Phi^{t_{n-m}}_{n-m}(x_0)$$ where $$\Psi_{x_0} \, : \, \mathbb{R}^{n-m} \, \to \, \mathbb{R}^n$$
which parametrizes the $n-m$ hypersurface $F(x) = y_0$.
Comment: I hope what I wrote helps you a little bit. In general, when the functions $F_i$ are not polynomial, basically everything is the same. Whenever the rank of $dF_x$ is maximal at a point $x$, it is maximal in a neighborhood of $x$. If you check that the rank $dF_x$ is maximal for every point $x$ such taht $F(x)=0$, then the latter is a submanifold and everything I said goes through. The only thing is finding the vector fields $X_1,..,X_m$ explicitly. They are there, just I am not sure about a structured procedure on how to find them. But again, I didn't think about it enough.
Comment: In the polynomial case you have the advantage of being able to write a procedure on a computer that will be able to compute the $X$'s. Possibly the same procedure that solves a system of linear equations with integer coefficients, copied line for line, but operating with polynomials (and rational functions) instead of integers and rational numbers. In the non-polynomial case... the existence of the $X$'s is guaranteed (as long as the rank of $dF_x$ is maximal). Without a general recipe as structured as the polynomial case.
Comment: Ok, so if the polynomials are obtained by a change of variables, then that's a good thing. Then staying with the polynomials is better for computational purposes.
Comment: Since the vector fields $X_i$ are linearly independent at each point of $F^{-1}(y_0)$, then their trajectories are transverse to each other (go in  different directions) and you end up having a curvylinear coordinate net on  $F^{-1}(y_0)$ given by $F_{x_0}(t_1,..,t_{n-m}) = \Phi_1^{t_1} \circ ... \circ \Phi_{n-m}^{t_{n-m}}(x_0)$.
Comment: @MichaelStachowsky Read my edit to the original  answer. Maybe you got mixed up because I abused some notation at the end by writing the new map as $F_{x_0}$. Now I've changed its notation to $\Psi_{x_0}$ and have added explanations about phase flows and vector fields.
Comment: This is fantastic and gives me a lot to go on, thanks.  A brief question: although I'm interested in polynomials only, I wonder if there are any differences between doing this in polynomials and doing it in general?  Your solution relied on the fact that the system was a system of polynomials (which really helps me).  I assume that in general you'd need stricter requirements on, say, the gradients to ensure that they are independent?
Comment: So would it be correct to say that the procedure for finding the vector fields for polynomial systems is well known, but that in general the procedure for doing so may not be as well known? (I'm just trying to justify a step I did where I turned a non polynomial system into a polynomial one.  Of course, if there is no such justification then I guess I can always go back on that step :-) )
Comment: Great, that is very helpful.  Since I was looking at the nonlinear equations and realized that by transforming them into a better understood form would help, I'm glad that it seems that step was a good one.  It's possible that the original equations have a "nice" solution, but I was unable to find it until I turned them into polynomials
Comment: Wait, so your original problem is not polynomial in nature, you just approximate your $F$'s by polynomials, is that it? You know, do you have a specific problem in mind, because for instance in symplectic geometry, if $n=2m$ then you have a symplectic duality, which turns each differential $dF_i$ into a vector field $X_i$ tangent to the hypersurface $F_i(x)=0$. So no need to solve systems here, the vector fields come for free. And it is general, no polynomials are necessary. Is in your original system $n=2m$ by any chance?
Comment: The original equations are non polynomial, but I was able to use a change of variables to turn into a system of constrained polynomials.  The actual problem is to determine the forces and torques acting on a point due to forces and torques applied at multiple points (well, it's more complex, but it's hard to write it into a comment on stack exchange).  However, turning into the polynomials provided one other result that was, as far as I can tell, not possible with the original equations.  One day I'll look at the originals and see what can be done, perhaps...
Comment: I should also mention that moving into the system of polynomials was just intellectually more fun, since I got to learn about algebraic geometry as I went :-)
Comment: I'm not sure if you're still follow this, but I had one more question.  Why is $F_x0$, which I have assumed is the local function that encodes the object I'm looking for, made up of the composition of the $\Phi$ functions?  Or is that another operation?
Comment: Since a vector field $X_i$ is tangent to the $n-m$ submanifold $F^{-1}(y_0) = \{x \in \mathbb{R}^n \, : \, F(x) = y_0\}$ for any $y_0 \in \mathbb{R}^m$, then it is in particular tangent to each $n-1$ submanifold $\{x \in \mathbb{R}^n \, : \, F_j(x) = c_0\}$. This is equivalent to saying that $F_j\big(\Phi^{t_i}_i(x)\big) = F_j(x)$ for any $j=1,..,m$, i.e. $F_j$ is a first integral (constant of motion) of $X_j$. This means that $F\big(\Phi^{t_i}_i(x)\big) = F(x)$, i.e. each trajectory  $\Phi_i^{t_i}(x)$ starting on $F^{-1}(y_0)$ stays  on $F^{-1}(y_0)$.
Comment: I recognize that this thread is now over a month old, but I am still not clear on the composition operation.  If I understand it, $f \circ g(x)$ is a 1 dimensional function, $f(g(x))$.  However, you answer seemed to imply that we get a hypersurface.  Did I misinterpret the operation?
Comment: It's more clear now, thanks.  I think I have some studying to do :-)


Is switching a vocal melody between parts a bad thing?

Question:
I wanted to compose a song starting out by using only 4 voices in the traditional SATB way and get a mockup for the song I am producing. I am the singer and producer and just want to get a mockup of the voice leading involved so this score is just for compositional purposes. I have never done this before so I am just trying to apply what I learned in harmony class and trying out different ways of scoring for my own purposes and my own vocal range. All suggesitions are welcome.
The score here has a piano part which is just an accompaniment and not part of the voice leading. The question I have relates the the grand staff. I am a baritone but in the chorus of the song I sing a bit higher and here I decided to use the "alto" part in the arrangement (in red). I use the "tenor" as my vocal part in the rest of the score (not shown). Ranges are not an issue for the other "voices" because they will be instrumental in the arrangment.
So the issue I have is in measure 18 moving from the F3 to the C4 in the next bar. In an ideal voice leading scenario, the alto would stay on Bb but my vocal melody dips all the way to F making a unison with the tenor and both those parts move up in similar motion. my question is:
Is this a problem? If so how to fix it
Answer: If you were trying to write a chorale in Bach's style, for example, no, you wouldn't want the melody jumping between parts like a train switching tracks, certainly not in the middle of a phrase. In that style of music, you'd want each part to be able to stand alone; the voices are supposed to maintain their independence.
In that style, two parts meeting for a brief unison is fine, so long as they go in different directions following that.
But you're not writing in that style, are you? If you were, I'd say your most glaring issues are the parallel octaves between the alto and bass and the lack of movement in the bass and tenor parts.
If you're the only vocalist and this is for a recording in a popular style of music, it would be difficult to pick out separate lines of music anyway, especially since the rest of the voices are only there to form chords, not independent lines of music. There is no need to conform to the paradigms of a Bach chorale just for the sake of doing so. If it's popular music, it's safe to follow the rule: if it sounds good, it is good.
Comment: Thank you. Where are parallel 5ths? The bassline moves first to D before going to C so this makes contrary motion from a 3rd to the 5ths by using a chordal skip. My harmony book says chordal skips are used like this all the time for this very purpose.
Comment: The tenor and bass lines both remaining on C/G is a parallel fifth. It does this on B♭/F as well, and again on C/G. The point is to have movement of these lines, and for that movement to be independent of the other. You're clearly not writing in that style, though. The chords going from C to B♭ and back, presumably with an eventual resolution to F, with a harmonic rhythm of whole measures, indicate pretty clearly that this is popular music.
Comment: remaining on a 5th is not parallel 5ths
Comment: Well, OK. I updated the answer. It's still not something any composition teacher is going to allow if you're doing "traditional SATB". There would need to be movement.


Bitwise AND operation program execution issue

Question: Below is a program in which I am trying to reset a particular bit of a hexadecimal number. The bit location, number of bits to reset, and hexadecimal value all are user inputs.
Header file
#pragma once

int bit0(int i,unsigned int RegA,unsigned int RegB,int s[]);

C file
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "targetver.h"
#include "bit.h"

int bit0(int i,unsigned int RegA,unsigned int RegB,int s[])
{
    unsigned int j=0;
    unsigned int K=0;
    unsigned int L=0;

    printf("\nThe bit is at s[0] is %x\n", s[0]);

    for (j=0; j<i; j++)
    {
        K = (1 << s[j]);
        L = ~K;
        RegB = RegA & ~L;
        printf("\nThe bit is %x\n", RegB);

        if (RegB | 0)
        {
            RegB = RegB & ~ (1 << s[j]);
        }
        else
        {
            RegB;
        }
    }

    printf("\nThe new reset bit is %x\n", RegB);

    _getch();
    return 0;
}

main file
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "targetver.h"
#include "bit.h"

int main()
{
    int i=0;
    int j=0;
    int s[35]={0};
    unsigned int RegA = 0;
    unsigned int RegB = 0;

    printf("Enter the hexa decimal value to be reset ");
    scanf_s("%x", &RegA);
    printf("Entered hexa decimal value is %x ", RegA);

    printf("\nHow many decimal places needs to be reset (0-31) ?");
    scanf_s("%d", &i);

    printf("Enter the decimal places that needs to be reset ");

    for (j=0; j<i; j++)
    {
        scanf_s("%d", &s[j]);
    }

    ///// check the entered hex value on those decimals places as bit 0 or bit 1

    bit0(i,RegA,RegB,s);

    _getch();
    return 0;
}

I am compiling and running executing the above code using Visual Studio.
The problem is in the C file, on the RegB = RegA & ~L; line.  The AND operation seems not to be taking place because I am getting 0 as the RegB value.
Program input:
Enter the hexadecimal value to be reset : 0100 1111
Entered hexadecimal value is : 0100 1111
How many decimal places needs to be reset (0-31): 1
Enter the decimal places that needs to be reset : 1
Comment: Facetiously, 01001111 is an *octal* literal.
Comment: @Bathsheba Which looks like binary, which is supposed to be hexadecimal. I call it a *total mess*.
Comment: What's with `#include`ing `"iostream"`?  This appears to be an attempt to include a C++ header into a C program.  The program already includes `stdio.h`, as it should, so I don't see any point at all.
Comment: There are no decimal places in a hex number.
Comment: Anyway, I think VS has an integrated debugger.  Have you considered using it?
Comment: And clarification: "hexadecimal" is one word.  My edit fixes that (among other things) in your prose, but on principle I have not modified anything about your code except insignificant whitespace.
Comment: Check the values of RegA and ~L to be sure. Here's a quickie(gives me RegA=0x4F and ~L=0x2):
    L = ~K;
    printf("RegA: %X, ~L: %X", RegA, ~L);
    RegB = RegA & ~L;
Comment: @kundrata I checked for the register values by having a break point in most of the places.
i = 0x00000001
j = 0x00000000
k = 0x00000002
L = 0xfffffffd
RegA = 0x01001111
RegB = 0x00000000
s = 0x00effa94

what I dont understand is why is the value of L is 0x00000002 and not 0x00000010.
Comment: 0x0002 = 0b0010. It's the same value: 2 in hexa means 10 in binary.
Comment: @kundrata I am aware that 0x0002 is 0b0010. But why are that other values are represented in hexadecimal like for example L = 0xfffffffd but not the value of K. why I dont see K as 0X00000010
Comment: When you shift(<<) the computer always shifts bits. It works in binary, not hexa. We just use hexa representation to make numbers easier to read. That's why they're called bitwise operations: shift, and/or etc.
Comment: When you shift to the left, it's equivalent to multiplying by 2(to the power of how many places you shift). 0x01 << 1 = 0x02(1 * 2). And  0x01 << 4 = 0x10(1 * 16, 16 is 2 to the power 4). Hope you get it now.
Answer: Well of course you get 0, but that's because the & operations you have written are (all) being performed.  Here's the relevant section of your code:
    K = (1 << s[j]);
    L = ~K;
    RegB = RegA & ~L;
    printf("\nThe bit is %x\n", RegB);

    if (RegB | 0)
    {
        RegB = RegB & ~ (1 << s[j]);
    }
    else
    {
        RegB;
    }

Before we continue, though, there are quite a few opportunities to simplify:

variable L just complicates things for me; I'd rather just see ~K
RegB | 0 is eqivalent to simply RegB
the else block does nothing
the if block can safely be executed unconditionally, in the sense that nothing will change if it is executed when the given condition is false.
Although you have set K = (1 << s[j]) and do not afterward change it, you later repeat yourself by using the expression (1 << s[j]) instead of just saying K.
the printf() may have some utility for debugging, but it slightly obscures the details of the computation

This equivalent code will be easier to reason about:
    K = (1 << s[j]);
    RegB = RegA & K;
    RegB = RegB & ~K;

And at that point the problem should be crystal clear: no matter what the value of RegA is, as long as s[j] is between 0 and 30,* you compute RegB by first masking off some of RegA's bits, and then masking off the remaining ones.  Naturally, the result is always 0.
*Because 1 is a signed integer constant, if the implementation's ints are 32 bits wide, left-shifting by 31 places produces an out-of-range result.  As far as the standard is concerned, the resulting behavior is undefined.  It would be better to avoid this issue by using an unsigned constant, i.e. 1U.
Comment: I performed your equivalent code. Still the execution of RegB = RegA & K; and RegB = RegB & ~K; not taking place. I set a breakpoint and verified it. When the breakpoint is currently at if (RegB | 0) the register values are as follows

i = 0x00000001
J = 0x00000000
K = 0x00000002
L = 0x00000000
RegA = 0x01001111
RegB = 0x00000000
S = 0x006ff700{0x00000001}
Comment: @vikash23, it's unclear what you think you've determined from running your code or my equivalent alternative in a debugger, but if you're running mine at all then it seems you've misunderstood my entire point.  I'm trying to tell you that **the result of the computation you have implemented is *always* zero**.  That the program in fact computes that result shows that the operations involved *are* being performed.  You have implemented a different computation than the one you were tasked with, and the computer is flawlessly executing what you told it to do.


Is there a way I can use an Interceptor in NHibernate 4.0 with stateless session?

Question: I have a big pre-exisiting project which was using NHibernate 2 with stateless session which used interceptors for altering values before CRUD operations (eg: timestamps of insert/update/ecc.); now after upgrading to NHibernate 4 I see that there is a design choice to not call interceptors for stateless sessions and I can't find a workaround, has anyone faced a problem like this and may there be a solution?
Answer: You can use Event Listeners instead. Ayende wrote a post in his blog about this.
Comment: Even I thought about that but I've seen that stateless does not fire events too:http://nhibernate.info/blog/2008/10/30/bulk-data-operations-with-nhibernate-s-stateless-sessions.html  "... A regular NHibernate ISession keeps a lot of data in its first-level cache (this enables a lot of the NHibernate magical goodies). The IStatelessSession however, does no such thing. It does no caching whatsoever and it also doesn't fire all of the events that you could usually plug into. This is strictly meant to be used for bulk data operations. ..."


How to sort files based on filename length with subdirectories?

Question: I am trying to look at a directory named Forever where it has sub-directories with Pure,Mineral which are filled with .csv files. I was able to see all the .csv files in the directory, but I am having hard time sorting them according to the length of filename.
As for current directory, I am at Forever. So I am looking at both sub-directories Pure and Mineral.
What I did was:
find -name ".*csv" | tr ' ' '_' | sort -n -r
This just sorts the file reverse alphabetically, which doesn't consider the length.(I had to truncate some name of the files as it had spaces between them.)
Comment: Possible duplicate of [Sorting file names by length of the file name](https://stackoverflow.com/questions/9868408/sorting-file-names-by-length-of-the-file-name)
Comment: These questions might be similar (sorting based on filename length), but they're not the same; one accounts for subdirs while the other does not.
Answer: I think this answer is more helpful than the marked duplicate because it also accounts for sub-dirs (which the dupe didn't):
find . -name '*.csv' -exec bash -c 'echo -e $(wc -m <<< $(basename {}))\\t{}' \; | sort -nr | cut -f2

FWIW using fd -e csv -x ... was quite a bit faster for me (0.153s vs find's 2.084s)
even though basename removes the file ext, it doesn't matter since find ensures that all of them have it


Time to $n$ heads when probability is a random variable

Question: I have the following problem. I toss coins until I get a $n$ heads and then stop.  The complication is that the probability of getting a head is itself a uniform random variable in the range $[0,1]$.   The probability of getting a head is however the same for all coins.
How can you get the probability distribution function of the time to get $n$ heads under these circumstances?
Answer: Suppose $X_1,X_2,X_3,\ldots$ are conditionally independent given $R$, and $R$ is uniformly distributed on $[0,1]$, and $\Pr(X_k=1\mid R)= R$ and $\Pr(X_k=0\mid R)=1-R$.
Let $K=\min\{k : X_1+\cdots+X_k=n\}$.  Then
$$
\begin{align}
& \Pr(K=k\mid R) \\[10pt]
= {} & \Pr(\text{exactly $n-1$ successes in the first $k-1$ trials}\mid R) \\
& {} \times\Pr(\text{success on the $k$th trial}\mid R) \\[10pt]
= {} & \binom{k-1}{n-1} R^{n-1} (1-R)^{k-n} \cdot R = \binom{k-1}{n-1} R^n (1-R)^{k-n}.
\end{align}
$$
Then
$$
\Pr(K=k)=\mathbb E(\Pr(K=k\mid R)) = \int_0^1 \binom{k-1}{n-1} r^n(1-r)^{k-n}\,dr.
$$
By this previous answer,
$$
\int_0^1 r^n(1-r)^{k-n}\,dr = \frac{1}{(k+1)\dbinom k n}.
$$
After simplifying, we have
$$
\frac{n}{k(k+1)} \text{ for }k=n,n+1,n+2,\ldots.
$$
Comment: @Lembik : The expected value is $\displaystyle\sum_{k=n}^\infty k\Pr(\text{number of trials}=k)$ $\displaystyle=\sum_{k=n}^\infty \frac n {k+1}=\infty$. ${}\qquad{}$
Comment: Thank you for this, this is very interesting (and different to the other answers it seems!).
Comment: @Lembik, yes it is.  Sorry about that.
Comment: Does this have a mean?
Comment: $\ldots\ldots$ it's a harmonic series. ${}\qquad{}$
Comment: Is the mean finite if $R$ is uniformly distributed on $[\epsilon, 1-\epsilon]$ instead, for some tiny $\epsilon$?
Comment: I suspect it will be finite if the interval is $[\varepsilon,1]$.  I'll look at this a bit later. ${}\qquad{}$
Answer: Let $X$ be the probability of getting a head; it is a uniform random variable. Let $T$ be the time to get $n$ heads.
If you knew what $X$ was, say $X=x$, then the distribution would be the sum of $n$ geometric random variables with parameter $1-x$. So this is the conditional probability distribution for $T \mid X=x$.
So, the probability distribution for $T$ is $f_T(t) = f_{T \mid X=x}(t)\cdot f_X(x)$ by the definition of conditional probability, where $f_{T \mid X=x}(t)$ is the sum of the $n$ geometric random variables, and $f_X(x)=1$ is the uniform distribution.
Answer: Opps.
It seems I misread the question.  You can skip the old answer and go straight to the new one.

Let $H$ be the distribution of the probability of getting a head, for each new coin tossed.  For simplicity we'll assume an unlimited source of coins and a different one used each toss; so the bias of each coin is independently determined with some probability distribution function; $f_H(p)$.
The usual geometric distribution of $n-1$ tails before the first head is modified to:
$$\Pr(N=n) = \int_0^1 p\;f_H(p) \operatorname{d}p \times \prod_{k=1}^{n-1} \left(1-\int_0^1 p\;f_H(p)\operatorname{d}p\right) $$
Or equivalently
  $$\Pr(N=n) = E[H]\left(\prod_{k=1}^{n-1} (1-E[H])\right)$$
And when this is a uniform distribution this becomes :
$f_H(p) = 1\cdot\operatorname{\bf 1}_{[0,1]}(p), E[H]=\frac 12$
$$\therefore \Pr(N=n) = (\frac 12)^n$$

If "the probability of getting a head is however the same for all coins." then you may as well be selecting one coin and using it for all tosses.
So in this case: $$\begin{align}\Pr(N=n) & = \int_0^1 (1-p)^{n-1}\;p\;f_H(p)\operatorname{d}p
\\ & = \int_0^1 q^{n-1}(1-q)\operatorname{d} q
\\ & = \int_0^1 q^{n-1}-q^n\operatorname{d} q
\\ & = \left[\frac {q^n}{n}-\frac{q^{n+1}}{n+1}\right]_{q=0}^{q=1}
\\ & = \frac {1}{n}-\frac{1}{n+1}
\\ & = \frac{1}{n(n+1)}
\end{align}$$
Comment: Is this using the fact that "The probability of getting a head is however the same for all coins."?
Comment: Ah,  no. @Lembik...adjusting...


angles between vectors in a high-dimensional space

Question: Say I am constructing a set $S$ of vectors in $\mathbb{R}^N$, where $|S|\leq N$.
Can I arbitrarily and independently assign values to the angles between all pairs of vectors in the set? It is impossible when $|S| > N$, but I am not sure if it is possible for $|S|\leq N$.
In other words, if I have an arbitrary symmetric matrix $M \in \mathbb R^{|S|\times |S|}$ (each element is in the range $[0, \pi]$), can I always find a set $S$ of $N$ dimensional vectors whose pair-wise angle matrix is $M$, when  $|S|\leq N$?
Comment: The angle between $u$ and $v$ can't exceed the sum of the angle between $u$ and $w$ and the angle between $w$ and $v$, can it?
Answer: No, these angles are constrained. As a simple counterexample, take $N=|S|=3$ with $M$ being $\pi$ on the off-diagonal and zero otherwise. This would require the three vectors to be mutually anti-parallel, which is plainly impossible.
To sharpen this one typically studies not the angles but the dot products $R_{ij}=\cos M_{ij} = \vec{v}_i\cdot \vec{v}_j$ between the vectors in set $S$. To simplify the resulting discussion, I'll further assume from here that these vectors in $S$ all have unit length. Then one has the following inequality:
$$\|v_1+v_2+v_3\|^2 = 3+2(v_1\cdot v_2+v_2\cdot v_3+v_1\cdot v_3)\geq 0$$
That is, the quantity $v_1\cdot v_2+v_2\cdot v_3+v_1\cdot v_3$ is at least $-2/3$. This amounts to a (nonlinear) constraint on the angles generated by these inner products, and in particular forbids all three dot products from being $-1$, i.e., the counterexample indicated above. Moreover, it is not the only such constraint: we can replace $v_1+v_2+v_3$ with arbitrary coefficients to generate an infinitude of such constraints.
To manage these inequalities more systematically, we switch from the matrix $M$ of angles to the matrix $R$ of dot products. Such a matrix is known as a Gram matrix, and it has a tidy representation: If we let $V\in \mathbb{R}^{N\times |S|}$ be a matrix whose column vectors are the (unit) vectors in $S$, then the definition of matrix multiplication immediately yields $R=V^\top V$.
From here we can prove a key property of such a Gram matrix $R$: For any vector $u\in \mathbb{R}^{|S|}$, we have $$u^\top R u = \| Vu\|^2\geq 0.$$ That is, $R$ is a positive semi-definite matrix (typically denoted as $R\succeq $ 0). To connect this with our above work, note that $u=(1,1,1)^\top$ yields $Vu=v_1+v_2+v_3$ and thus recovers the prior inequality. So the infinite family of linear inequalities indicated above is equivalent to $R\succeq 0$.  The family of such Gram matrices is a convex body known as the $n$-elliptope, with each linear inequality corresponding geometrically to one of its tangent half-spaces.
Moreover, note that the inequality is saturated iff $Vu=\sum_{k=1}^{|S|} v_k u_k=0$. But this amounts to these vectors being linear dependent. If we require that the vectors in $S$ be linearly independent, then the inequality is sharp and $R$ is positive definite ($R\succ 0$). The advantage of making this final change is that we can now appeal to Sylvester's criterion: a real symmetric matrix is positive definite if and only if its leading principal minors are all positive. We thereby reduce the problem to a finite set of inequalities, at the cost of these constraints being on polynomials of the dot products rather than linear functions as above. (If we relax to positive semi-definite $R$, we can proceed similarly but now we have to check all principal minors not just the leading ones.)
This does still leave us with quite a bit of work, and in particular these inequalities are hardly elementary as the dimension increases. However, the case of $N=3$ is tractable. In particular, in this setting the matrix $R$ of dot products will be positive semi-definite so long as $\det R=(\det V)^2$ is nonnegative. This yields the following inequality on the off-diagonal elements $R_{12},R_{13},R_{23}$:
$$ \det R = 1-R_{12}^2-R_{13}^2-R_{23}^2 +2 R_{12}R_{13}R_{23}\geq 0$$
This yields the following picture for the 3-elliptope:

Note that this looks like a somewhat-inflated tetrahedron. There is a final surprise to be had here, but it is one whose details I will leave to the reader: If we convert this set of possible dot products back into the set of possible angles, what body do we obtain?
Comment: Ah thanks, thinking in terms of Gram matrix is very nice. For any positive semi-definite matrix $R$ of size $|S| \times |S|$ and rank $N$, we can always find $V$ of size $N \times |S|$ that satisfies $R=V^TV$ by performing SVD on R (i.e. $R=USU^T$ where $U$ is an orthonormal matrix then $V=Q\sqrt{S}U^T$ where $Q$ is an arbitrary orthonormal matrix.) So I should have had an additional criterion that $R$ is a positive semi-definite matrix to make the statement in the question true.