python list modification to list of lists

Question: I am trying to learn python (just finished Learn Python the Hard Way book!), but I seem to be struggling a bit with lists. Specifically speaking, I have a list like so:
x = ["/2.ext", "/4.ext", "/5.ext", "/1.ext"]

I would like to operate on this above list, so that it returns a list (somehow!) like so:
y = [ ["/1.ext", "/2.ext"], ["/1.ext", "/2.ext", "/3.ext, "/4.ext"], ["/1.ext", "/2.ext", "/3.ext", "/4.ext", "/5.ext"], ["/1.ext"] ]

So, essentially, each element in x is now turned to a list of lists. I could probably loop over x, store all the sequence lists in another list and then merge then together - but it just seems like there must be a better way to do it.
Would be grateful if someone could point me in the right direction to solve this problem.
EDIT (taking into account Martijn's comments):
Specifically, I want to generate the intermediary filenames in a sequence, ending at the number for each x list element
Comment: Your question is a) not clear (the procedure on how the output list is to be generated was missing) and b) doesn't show any evidence of effort to solve it yourself.
Comment: What are you trying to do? A combinations of every possibles list?
Comment: Where did the `"/3.ext"` come from? Your `x` list doesn't have such an element. It is unclear to me how the sublists of `y` should be generated.
Comment: is the original list supposed to have five elements not four?
Comment: @MartijnPieters: What I am trying to do is run till the end of the list. So, for x[0] = "/2.ext" I would like a list which contains everything upto "/2.ext" - so, ["/1.ext", "/2.ext"] - Am I making it any clearer? So, for x[1]="/4.ext", I should have a minilist upto "/4.ext" like so: ["/1.ext", "/2.ext", "/3.ext, "/4.ext"] Hope this is a bit clearer! Please ask if it is not!
Comment: Not sure why the question is getting downvoted so fast :(
Comment: @AJW: Right, that was indeed not clear. Can you add that to your question please? You want to *generate* the intermediary filenames in a sequence, ending at the number for each `x` list element.
Comment: @MartijnPieters: I have added it to the question now. Well, my effort to solve the problem was by looping through the entries, generating the intermediate lists and then combining them to form list of lists - but this does not sound too elegant and therefore, I asked the question.
Answer: You can do it as follows:
x = ["/2.ext", "/4.ext", "/5.ext", "/1.ext"]

print [['/{}.ext'.format(j) for j in range(1,int(i[1])+1)] for i in x]

[OUTPUT]
[['/1.ext', '/2.ext'], ['/1.ext', '/2.ext', '/3.ext', '/4.ext'], ['/1.ext', '/2.ext', '/3.ext', '/4.ext', '/5.ext'], ['/1.ext']]

This only works for digits upto 9. I'll post update for more general solutions
HERE is the more general solution. Works for any numbers:
import re

x = ["/2.ext", "/4.ext", "/5.ext", "/1.ext"]

print [['/{}.ext'.format(j) for j in range(1,int(re.search(r'\d+',i).group(0))+1)] for i in x]

Comment: Yes it works! Thanks a lot. Accepted your answer. However, I have another follow up question: What if the list has: `x = ["we/2.exta", "fr/4.extb", "gb/5.extc", "de/1.extd"]`? Just wondering!


Why is the derivative of $e^x$ equal to $e^x$?

Question: I know that for the exponential function $e^x$ that the derivative will equal $e^x$ itself. But why? And also what is the significance of that?
Is that what gives $e$ its power? The rate of change of $e$ as it grows to the power of $x$, is $e^x$ itself. I get that the function doesn't produce $e^x$, that merely the rate at which its changes between $e^x$ and $h$ as $h \to 0$. But the intuition as to why and what is the significance to math eludes me. Mind you, I understand the math behind it, just not the intuition. For example, I understand this entire post https://mathinsight.org/exploring_derivative_exponential_function but why
I understand the math behind this post Could you explain why $\frac{d}{dx} e^x = e^x$ "intuitively"?. But I'm looking for an analogy.
Comment: https://math.stackexchange.com/questions/272507/how-would-you-explain-why-e-is-important-and-when-it-applies?rq=1
Comment: https://math.stackexchange.com/questions/26037/intuitive-understanding-of-the-constant-e
Comment: https://math.stackexchange.com/questions/3006/could-you-explain-why-fracddx-ex-ex-intuitively
Answer: Note $\ln e^x =x$.  Use the chain rule:  $\ln'(e^x)\cdot (e^x)'=1\implies \frac1{e^x}\cdot (e^x)'=1\implies (e^x)'=e^x$.
Comment: The important thing is that $e$ is the unique constant with $\lim_{x \to 0} \frac{e^x-1}{x} =1$.  THIS is why it is equal to its own derivative.
Comment: @Seph You could use $2^x$ or $3^x$, etc, to describe population growth and radioactive decay and interest. But if we use $e^x$ then the calculations are a little simpler and more clean, because the derivative of $e^x$ is just $e^x$.
Comment: "Exponential functions describe population growth, radioactive decay and interest" Why does e do that. What's wrong with just using 2^x or 3^x or 4^x
Comment: There certainly appears to be something interesting about $e$.  You are right.  I , like i said,  think of it as a phenomenon.
Comment: There are many interesting patterns in nature,  including mathematics. The Bell curve is interesting.   It seems kind of natural for things to be distributed that way.  More around the average,  fewer at the extremes.  I remember a joke to the effect that God must like average people:  he made an awful lot of them.  But normal is just a setting on your hair dryer.  But I digress.
Comment: This doesn't answer the question.  The derivative of $\ln x$ depends on knowing that the derivative of $e^x$ is itself, so this is circular.
Comment: I usually define $\ln x=\int_1^x\frac1t\operatorname dt$. @Randall
Comment: In that case that is a much stronger argument than "it's a natural phenomenon."
Answer: Without knowing anything about $e$, one could pose the question - is there a function $f(x)$ such that the derivative of the function evaluated at any point $x$ is equal to $f(x)$. The function that satisfies this property happens to be $\alpha e^x$.
$${d \over dx}f(x) = f(x)$$
$$\implies {df(x) \over f(x)} = dx$$
$$\implies ln(f(x)) = x + c$$
$$ \implies f(x) = \alpha e^x$$
Another way to look at it could be: (i) if the rate of change of a function is constant, the function is linear. (ii) if the rate of change is polynomial, the function is a polynomial (of a higher order than the derivative), and (iii) if the rate of rate change is exponential, the function is exponential.
$$ {d \over dx}f(x) = ae^x$$
$$ \implies df(x) = ae^x dx$$
$$ \implies f(x) = ae^x + c$$
Answer: I find cosine and sine very natural and significant in mathematics, and they can be represented by Euler's formula:

$$ e^{i\theta}  = \cos(\theta) + i\sin(\theta)$$

And from this we know the derivatives of these natural pair of functions easily thanks to derivative of $e^z$ being itself:

$$\frac{d}{d\theta}e^{i\theta}  = \frac{d}{d\theta}\cos(\theta) + i\frac{d}{d\theta}\sin(\theta)$$
$$ ie^{i\theta} = -\sin{(\theta)} + i\cos(\theta) = \frac{d}{d\theta}\cos(\theta) + i\frac{d}{d\theta}\sin(\theta)$$

so

$$ \frac{d}{d\theta}\cos(\theta) = -\sin{(\theta)} \tag 1$$
$$ \frac{d}{d\theta}\sin(\theta) = \cos(\theta) \tag 2$$

Perhaps it was the necessity of (1) and (2) that fueled nature to mandate

$$ \frac{d}{dz}e^z = e^z$$


Retrieving object from scala actor

Question: I have an intensive task that can distributed but whose end result needs to be accumulated and passed on to another method down the line.
For concreteness, let's say I'm doing word counts for individual files in a large collection of text files.
The version I've worked out so far looks like this:
import scala.actors.Actor
import scala.actors.Actor._
import scala.collection.mutable.{ArrayBuffer => mArray}

case object Stop

class Collector(val bin: mArray[(String, Int)], tcount: Int) extends Actor {
  def act() {
    loop {
      receive {
        case (fn: String, val: Int) => {
          // the following "bin" object is what I ultimately need to get back
          bin.append((fn, val))
        }
        case Stop => {
          tcount -= 1
          if(tcount == 0) exit()
        }}}}}

class Processor(col: Collector, flist: Seq[File]) extends Actor {
  def act() {
    for(fn <- flist) {
      val wcount = count words in fn // just a place holder for word counting code
      col ! (fn, wcount)
    }
    col ! (id, Stop)
  }
}

I can think of several homebrewed methods to make the main method wait for collector to finish and then deal with the "bin" object.
But what is the proper scala way to retrieve "bin" above and hand it back to main or what have you?
Answer: With an actor, you don't "retrieve" anything as calling actor methods can be dangerous.
Instead, you get the actor to send the answer out. You could add a case for a GET object, or in your case you could have it send the bin somewhere in the handler for Stop.
Answer: You could ping an actor using method !! to create a future result. The actors receiving the message can fill in the result by using reply.

However, you save a lot of management work by using executors instead, which are better for parallelising tasks (you don't really have a concurrency situation here where actors would be particularly useful).
The following is based on Scala 2.10 (forthcoming, you can use 2.10.0-M6 right now), because it contains the improved concurrent framework:
import java.io.File
import concurrent._
import java.util.concurrent.Executors

// count words in a file - probably not the best possible way to write this
def wc(f: File): Int = io.Source.fromFile(f).getLines.map(
   _.split(' ').filterNot(_ == "").size).sum

// utility method to get files within a directory (non-recursive!)
def filesInDir(dir: File): Seq[File] = dir.listFiles.toSeq.filter(_.isFile)

// process method which takes a list of files, spawns a word-count for each
// and collects the individual future results into a `Map` whose future is returned
def process(files: Seq[File])(implicit exec: ExecutionContext)
: Future[Seq[(File, Either[Throwable, Int])]] = {
  val futs = files.map { f =>
    // `future` submits the body for asynchronous processing. In order to
    // gracefully handle IO errors, a successful result is wrapped in `Right`,
    // and an exception in `Left`. The caller can decide how to handle errors.
    future {
      f -> (try {
        Right(wc(f))
      } catch {
        case e: Throwable => Left(e)
      })
    }
  }
  // collect all the individual results into one result object.
  // the new single `Future` is only complete after all of the individual futures
  // have completed.
  Future.sequence(futs)
}

Example:
// use as many threads as there are processor cores
val poolSize = sys.runtime.availableProcessors()

// create a new executor context to be used for spawning
implicit val exec = ExecutionContext.fromExecutor(
  Executors.newFixedThreadPool(poolSize))

// call the process
val map = process(filesInDir(new File("/my/directory")))

// execute some body when the future is completed
map.onSuccess { case m =>
  m foreach println
}

Comment: An alternative to `Either[Throwable, Int]` is `util.Try[Int]` which is also new in Scala 2.10.

Retrieving object from scala actor


Determining matrix which represents Linear Transformation

Question: Let F : E
3 → E
3 be one of the two possible orthogonal rotations of angle 5π/6 around
the line of equation 2x + y + 5z = 0 = 4x − y + 10z.
I.Determine the matrix representing F
II.Determine if such a rotation is a direct isometry.
I am struggling to see relation between ''orthogonal rotation'' and linear transformation as i have never encountered a question like this.And i am not sure what is meant by "direct isometry"
Answer: HINT
We can proceed as follow

find the normalized direction vector $\vec v$ for the given line
complete a basis by two orthonormal vectors $\vec u$ and $\vec w$ orthogonal to $\vec v$
in the basis $\{\vec u,\vec w,\vec v\}$ the rotation matrix is given by

$$R=\begin{bmatrix}\cos \theta &-\sin \theta &0\\\sin \theta &\cos \theta &0\\0 &0 &1\end{bmatrix}$$

then change basis from $\{\vec u,\vec w,\vec v\}$ to the canonical

Recall that if the orientation stays the same we say that the
isometry is direct, if the orientation changes we say that the isometry is opposite.
Comment: 1.Direction vector: (2,1,5)x(4,-1,10)=(15,0,-6)
2.Orthogonal complements: u=(0,1,0) and w=(2/5,0,1)
3.So our basis {u,w,v}={(0,1,0) (2/5,0,1) (15,0,-6)}
I don't understand how to use our basis {u,w,v} in rotation matrix provided.
Comment: @TuranNasibli Matrix $R$ represents the rotation in the given basis (with $\theta =5\pi/6$ or $=-5\pi/6). To find the rotation matrix in the standard basis we nedd to change basis.
Comment: So we need to express our Matrix R in canonical basis,but the process of finding rotation matrix for our basis isn't clear to me.Could you help with that?
Comment: In the given basis $u=(1,0,0)$ and $Ru=(\cos \theta, \sin \theta, 0)$ similarity for $w=(0,1,0)$ while $v=(0,0,1)$ is fix since $Rv=v$.
Comment: @amd Yes you are right! I'v fixed that. Thanks


Is $f'((0,0);d)=0$ (directional derivative) for every direction $d \in \Bbb R^{n}$?

Question: If $\frac{\partial f}{\partial x}(0,0) = \frac{\partial f}{\partial y}(0,0) = 0$, then $f'((0,0);d)=0$ (directional derivative) for every direction $d \in \mathbb{R}^n$.
Is this true? I'm trying to find a counterexample to prove it false, but nothing comes to mind.
Comment: confusing double use of the letter $d$ found here: $d \in \mathbb R^d$
Answer: Let $d=2$ and $f=\begin{cases}\frac{xy}{x^2+y^2},&x^2+y^2\neq0\\0, &x^2+y^2=0\end{cases}$
It's easy to see that $\frac{\partial f}{\partial x}f(0,0) = \frac{\partial f}{\partial y}f(0,0) = 0$ but
$$\triangle f(0,0)\neq o\left(\sqrt{x^2+y^2}\right)$$
Answer: Consider the following example. Let $f:\mathbb{R}^2\to \mathbb{R}$ be such that $f(x,0)=0$, $f(0,y)=0$ for all $x,y\in\mathbb{R}$ but $f(x,y)=\sqrt{x^2+y^2}$ whenever $xy\neq 0$. It is obvious that both $\frac{\partial f}{\partial x}(0,0)=\frac{\partial f}{\partial y}(0,0)=0$.
Now let $\vec{v}=(a,b)$ be a unit vector in $\mathbb{R}^2$ with $ab\neq 0$. So you can try to compute
$$\frac{\partial f}{\partial \vec{v}}(0,0)=\lim_{t\to 0}\frac{f(ta,tb)-f(0,0)}{t}=\lim_{t\to 0}\frac{t-0}{t}=1\neq 0.$$
What you might have in mind is the formula $\frac{\partial f}{\partial \vec{v}}=\vec{v}\cdot \nabla f(x)=a\frac{\partial f}{\partial x}+b\frac{\partial f}{\partial y}$. But you should note that this only holds if you suppose some sort of smoothness condition for $f$.


Compute covariance matrix given probability density fonction

Question:
I'm given a probability function for 2 random variables and I have to compute the covariance matrix of the vector they form.
Answer: They are independent random variables as per the explanation, so the off-diagonal entries are 0. The diagonal entries are the respective variances. In order to compute the variance, you can benefit from Exponential distribution.


How can I open a link in a new tab if it has target=_blank?

Question: I am trying to open a link in a new tab only if that link has a target=_blank like so.
Google

For some reason the target=_blank is not working in the a Bootstrap 4.5 navbar Therefore, I am trying to use jQuery to get it to work as some links have the target=_blank attribute:
$('a.navigation-title').click(function () {
    location.href = this.href;
    $(this).find('a').attr('target','_blank');
    window.open(this.href, '_blank');
  });

That's the script I've used, but its not having any effect.
Comment: do you have any browser settings, preventing this from working? It is not possible to force a new tab, if the browser settings says, new links should open in same tab, you will not be able to open a new tab
Comment: @JarlikStepsto - Yes am aware of that browser setting and not I don't have any browser setting that's preventing it from working.
Comment: that's a weird scenario. By default, new pages should open in new tab.
Comment: @Raptor, I know that's why was surprised it was not working.
Answer: Change code to
Google
I have added a new class to the 'a' tag for triggering the click event for jquery
$('.navigation-title').click(function () {
    var url = $(this).attr('href');
    window.open(url , '_blank');
  });

Comment: I've checked it and the changes you've suggested still don't work. Also I need to check if the _blank attribute exists since its only those that I want to open in a new tab, thanks for the response though.
Answer:

var elements = document.querySelectorAll('a[target=_blank]');
for (var index = 0; index < elements.length; index++) {
  const element = elements[index];
  element.addEventListener('click', function (e) {
    e.preventDefault();
    var href = element.getAttribute('href');
    if (href) {
      window.open(href, '_blank');
    }
    return false;
  });
}
Google
Comment: Thanks @Nilesh Chavan, works as expected. Very appreciated
Comment: it's my pleasure. :)


Invertible elements in the ring $K[x,y,z,t]/(xy+zt-1)$

Question: I would like to know how big is the set of invertible elements in the ring $$R=K[x,y,z,t]/(xy+zt-1),$$ where $K$ is any field. In particular whether any invertible element is a (edit: scalar) multiple of $1$, or there is something else. Any help is greatly appreciated.
Comment: @Hurkyl: I assume "multiple of $1$" in this context means scalar multiple of $1$ (that is, element of $K$).
Comment: In any ring, every element is a multiple of 1. What did you mean to ask?
Comment: @Hurkyl: Thank you for your comment. Indeed, I meant to say scalar multiple of 1, that is any element of the form a*1 with a in K\{0}. I will edit the question accordingly.
Comment: In http://math.stackexchange.com/questions/173021/is-the-coordinate-ring-of-sl2-a-ufd it is shown your ring is a UFD.  I doubt this helps to find units, but if you continue working with the ring, it could be quite helpful.
Answer: Here is a geometric proof that $R^*=K^*$.
Embedd $U=\operatorname{Spec}R$ as an open subvariety into the projective variety
$$P:=\operatorname{Proj} K[x,y,z,t, w]/(xy+zt-w^2).$$
Note that $xy+zt-w^2$ is irreducible over an algebraic closure of $K$, so $P$ is geometrically integral, hence ${\mathcal O}_P(P)=K$. Using Jacobian criterion, we see that $P$ is smooth, hence normal.
Let $f\in R^*$ that we consider as a rational function on $P$. As $E:=P\setminus U$ is the zero set of $w$ which is an integral hypersurface in $P$, the divisor of $f$
is $\mathrm{div}(f)=nE$ for some integer $n$. If $n\ge 0$, then $f$ has no pole on $P$, so $f\in {\mathcal O}_P(P)=K$ (because $P$ is normal). If $n<0$, then the same reasonning applied to $1/f$ shows that $1/f\in K$. In both cases, $f\in K$.

EDIT 2. Please forget the wrong answer below.
Edit. Simply the former proof thanks to the comments of the OP.
The only invertible elements are in $K^*$. I don't really like the proof below, but for the moment I don't have an alternative one.
In $R$, the relation $tz=1-xy$ implies that any element
$f(x,y,z,t)\in R$ can be written as
$$f(x,y,z,t)=g(x,y,z)+th(x,y).$$
Suppose $f$ is invertible in $R$. Let $K^a$ be an algebraic closure of $K$.
Denote by
$$Z=\{(a,b,c,d)\in (K^a)^4 \mid ab+cd=1\}.$$
Then $f(a,b,c,d)\ne 0$ for all $(a,b,c,d)\in Z$.
First observation: there is no common factor $h_1(x,y)$ of $g(x,y,z)$ and
$h(x,y)$ because otherwise $h_1(x,y)$ would be invertible in $R$, but
for any $(a,b)\in (K^a)^2$, there exists $(a,b,c,d)\in Z$, so $h_1(a,b)\ne 0$,
thus $h_1(x,y)\in K^*$.
Now for any $(a,b,c)\in (K^a)^3$ such that $c\ne 0$ and $h(a,b)\ne 0$,
we have $g(a,b,c)+(1-ab)h(a,b)/c \ne 0$ because otherwise
$f(a,b,c,d)=0$ with $d=(1-ab)/c$ and $(a,b,c,d)\in Z$.
This means that in the affine space $\mathbb A^3_K$, we have
$$ V(zg(x,y,z)+(1-xy)h(x,y))\subseteq V(z).$$
Therefore $z \mid f$ and $h=0$.
We are now reduced to the situation $f=g(x,y,z)$. Similar reasoning
show that $g(x,y,z)=\lambda z^n$ with $\lambda \in K^*$ and
$n\ge 0$. Again we see as above that $n>0$ is impossible. So
$f\in K^*$.
Comment: I'm trying to learn this sort of approach. I believe I know such things as "the number of poles is the number of zeros" and "all the bad stuff happens on E". I believe "the divisor of f is a multiple of E" is stating that f cannot have both poles and zeros on E. Can someone describe why that is so?
Comment: @user26565, the proof above is specific to the case when $K$ is a field. In general, the results doesn't hold, e.g. if $K$ is a ring with nilpotent elements, then $1+v\in R^*$ is a unit in $R$ for any nilpotent $v$. But this is probably the only possibility.
Comment: Could you please explain, why do you need $h(a,b)\neq 0$ in the paragraph that starts with "Now for any $(a,b,c)\in (K^a)^3$..."?
It looks like you only use that $c\neq 0$ when you write d=(1-ab)/c.
Comment: You are right. So the proof is simpler.
Comment: Your assertion "...any element
$f(x,y,z,t)\in R$ can be written as
$f(x,y,z,t)=g(x,y,z)+th(x,y).$" is not true. It is false for $t^2$, for example .
Comment: @GeorgesElencwajg, thanks ! But then I don't see how to repair. :(
Comment: Sorry about that, Cantlog, but it is not so important: your geometric argument is very beautiful and I upvoted it the moment I saw it. I strongly urge user 26565 to accept it and other users to upvote it.
Comment: @Cantlog Thank you! The geometric argument is very nice. I will accept it, since I understand how it works for a field $K$. However, as I imply from your terminology ("geometrically integral" etc.) that it is valid for some rings $K$ which are not necessarily fields. Could you please tell whether your argument is valid for all rings $K$?
Comment: @JackSchmidt I don't know much about algebraic geometry, and to understand argument, I looked in the Basic Geometric Geometry by Shafarevich, vol 1, 2 ed. Here (p. 154) it is proved that if $P$ is smooth and irreducible then if $div f\geq 0$ (that is, any coefficient in $div f$ is $\geq 0$) then $f$ is regular function. To prove it, Shafarevich assumes that $f$ is not regular at $x\in P$ and considers the local ring $O_x$. Since $f=g/h$ for some $g,h\in O_x$, $f\not\in O_x$ and $O_x$ is UFD, exists $\pi\in O_x$ which divides $h$ but not $g$. Then $div f$ at a component $C$ of $V(\pi)$ is $<0$.
Answer: Let $R=K[X,Y,Z,T]/(XY+ZT-1)$. In the following we denote by $x,y,z,t$ the residue classes of $X,Y,Z,T$ modulo the ideal $(XY+ZT-1)$. Let $f\in R$ invertible. Then its image in $R[x^{-1}]$ is also invertible. But $R[x^{-1}]=K[x,z,t][x^{-1}]$ and $x$, $z$, $t$ are algebraically independent over $K$. Thus $f=cx^n$ with $c\in K$, $c\ne0$, and $n\in\mathbb Z$. Since $R/xR\simeq K[Z,Z^{-1}][Y]$ we get that $x$ is a prime element, and therefore $n=0$. Conclusion: if $f$ is invertible, then $f\in K-\{0\}$.
Comment: I'm strongly reminded of the reasoning I gave in Bungo's question on associates (now buried in one of the many edits): anyway +1. I wonder just how far this type of reasoning with the units can be extended...


Facebook - You don't have permission to access "http://www.yourapp/?" on this server

Question: Users are getting the following message when trying to use my Facebook app:

Access Denied You don't have permission to access "http://www.myapp/?"  on this server.
Reference #18.8f265dcc.1338297690.20407019

It works when going directly to the app (http://www.myapp/), but not through Facebook.
I have a secured version (https) that works both directly and through Facebook.
This was working fine last week.  I haven't made an update since 5/10, and now it's just broken.  Did Facebook change something???
Help!
Comment: That error message is shown when exactly? As a part of using `FB.ui`?
Answer: "http://www.myapp/?" si not a secure connection. Check the settings in your facebook app. You have to use secure connection if your not in developer mode.
Comment: Correct.  I have my app set up so users can use a secured OR an unsecured site.  (I have an http version AND and https version.)  The unsecured version worked just fine until this weekend.
Answer: I was unable to fix the problem, but I did find a workaround.  I'm sharing it, in case others have the same problem.
Basically, I got rid of the unsecured version altogether.  I went into my developer panel and changed the link in my "Canvas URL" to point to my secured version, instead of the unsecured one.  As a bonus, I now only have once set of production code to maintain.


Proof of Brouwer fixed-point theorem in dimension 2

Question: I don't understand the proof of Brouwer fixed-point theorem:

Every continuous function $f:D^2\rightarrow D^2$ has a fixed point, i.e. $\exists x, f(x)=x$

Here is our professor's proof:
Assume not then exists a retraction $r$ with
$r:D^2\rightarrow S^1$, $\quad$$r(x)=(1-t)f(x)+tx$ and $||r(x)||=1$
then; $r|_{S^1}=id_{S^1}$
$i:S^1\rightarrow D^2$, $\quad$$x\mapsto x$$\quad$($i$ is the inclusion i think)
$r_*:\pi_1(D^2,x_0)\rightarrow \pi_1(S^1,x_0)$
$i_*:\pi_1(S^1,x_0)\rightarrow \pi_1(D^2,x_0)$
So,
$id=r\circ i\Longrightarrow id_*=(r\circ i)_*=r_*\circ i_*$
$\pi_1(S^1,x_0)\overset{i_*}\longrightarrow \pi_1(D^2,x_0)\overset{r_*}\longrightarrow\pi_1(S^1,x_0)$
$\mathbb Z\rightarrow 0\rightarrow\mathbb Z$
$\textbf{What have we reached now ?}$
-if we compare the domains, $id_*=(r\circ i)_*$ can't be true or what ?
Comment: The domain of $r_\ast$ is trivial, hence the image is trivial too. But $\pi_1(S^1,x_0)$ isn't trivial.
Answer: Because the final map goes through 0, its image must be 0, but the final map is supposed to be the identity on $\mathbb{Z}$, which can't be the zero map.
Answer: Notice that the map induced by the identity should be the identity itself (in the fundamental group), and you concluded that the identity is the composition of a $0$ map with the map induced by the retraction. There is no homomorphism $r_*$ with that property (consider the homomorphisms of the $0$ group).


How to handle App.XAML events in Main.cs?

Question: I would like to know how I handle events that I set in my App.XAML file in a standard WPF configuration. I have a button in my App.XAML file and I would like to add an event handler which is located in my Main.CS file.
Example code:
xmlns:local="clr-namespace:MyApp"

<Button Click="Myhandler" />

Even though App.CS and Main.CS both share the same namespace I get an error saying that my handler does not exist. How can I set the context in the right way?
Comment: You can't do that. Either move the button to Main.xaml OR bind Command DP to some ICommand in ViewModel.
Answer: That's because the class of your App.xaml is MyApp.App:
<Application x:Class="MyApp.App"
   ...
>

xmlns:local="clr-namespace:MyApp" is just like adding a using local = MyApp; line to the beginning of a c# code.
You have to create your event handlers in MyApp.App. but if you're concerned about the Right way to do it you should use Commands instead of event handlers.


Standardized regression coefficient ($\beta$) in multi-linear regression by groups?

Question: As you see, I have more than 500 groups of data. how can I get the std.coef in mult-linear regression for each group? Until now, I only know how to get one group by using lm.beta. For example:
library(QuantPsyc)
p <- read.csv('Data1.csv')
model1 <- lm(YCOORD110 ~ TEMMIN + TEMVAR)
lm.beta(model1)

For groups, several codes like by, apply can be used, but seem much more complicated beyond my control.
very appreciate for your answers!
Answer: Use a for loop:
library(QuantPsyc)
attach(iris)

group <- levels(Species)
group

out03 <- vector()
for (i in group){
   out00 <- subset(iris, Species==i)
   out01 <- lm(Petal.Width ~ Petal.Length + Sepal.Width, data=out00)
   out02 <- lm.beta(out01)
   out03 <- c(out03, out02)
}

finalTable <- cbind(group, data.frame(matrix(out03, ncol=2, byrow=T)))
colnames(finalTable) <- c("Species", "Petal.Length beta", "Sepal.Width beta")
finalTable

Final tabulated output:
     Species Petal.Length beta Sepal.Width beta
1     setosa         0.2997348        0.1794891
2 versicolor         0.6043644        0.3252391
3  virginica         0.1268589        0.4868520

Answer: As far as I can understand the query is how to find group coefficients in a single regression model, where some independent variables may be dependent on group (M/F, let us say). In this case you need to create n dummy binary variables (for n groups) as separate independent variables. These variables will have the values 1 for all individual observations of their respective group, and 0 values for all other observations. Now these dummy variables will be multiplied with each independent variable and included in the linear regression model.
E.g. Lets say your model is: (Y = C + A.x1 + B.x2) and we have 2 groups.
We will create 2 dummy variable, z1 and z2. z1/z2 is a binary variable with  value =1 for all observations in the respective group and rest values will be 0.
 Now input your linear regression model as:
Y = C + A1.x1.z1 + A2.x1.z2 + B1.x2.z1+ B2.x2.z2
A1, A2 will respectively, the coefficients for groups 1 and 2


When is std::weak_ptr useful?

Question: I started studying smart pointers of C++11 and I don't see any useful use of std::weak_ptr. Can someone tell me when std::weak_ptr is useful/necessary?
Comment: possible duplicate of [boost, shared ptr Vs weak ptr? Which to use when?](http://stackoverflow.com/questions/2036182/boost-shared-ptr-vs-weak-ptr-which-to-use-when)
Answer: std::weak_ptr is a very good way to solve the dangling pointer problem. By just using raw pointers it is impossible to know if the referenced data has been deallocated or not. Instead, by letting a std::shared_ptr manage the data, and supplying std::weak_ptr to users of the data, the users can check validity of the data by calling expired() or lock().
You could not do this with std::shared_ptr alone, because all std::shared_ptr instances share the ownership of the data which is not removed before all instances of std::shared_ptr are removed. Here is an example of how to check for dangling pointer using lock():
#include <iostream>
#include <memory>

int main()
{
    // OLD, problem with dangling pointer
    // PROBLEM: ref will point to undefined data!

    int* ptr = new int(10);
    int* ref = ptr;
    delete ptr;

    // NEW
    // SOLUTION: check expired() or lock() to determine if pointer is valid

    // empty definition
    std::shared_ptr<int> sptr;

    // takes ownership of pointer
    sptr.reset(new int);
    *sptr = 10;

    // get pointer to data without taking ownership
    std::weak_ptr<int> weak1 = sptr;

    // deletes managed object, acquires new pointer
    sptr.reset(new int);
    *sptr = 5;

    // get pointer to new data without taking ownership
    std::weak_ptr<int> weak2 = sptr;

    // weak1 is expired!
    if(auto tmp = weak1.lock())
        std::cout << "weak1 value is " << *tmp << '\n';
    else
        std::cout << "weak1 is expired\n";

    // weak2 points to new data (5)
    if(auto tmp = weak2.lock())
        std::cout << "weak2 value is " << *tmp << '\n';
    else
        std::cout << "weak2 is expired\n";
}

Output
weak1 is expired
weak2 value is 5

Comment: Ok, it's as if if you locally set a (owning) pointer to null (delete memory), all other (weak) pointers to the same memory are also set to null
Comment: `std::weak_ptr::lock` creates a new `std::shared_ptr` that shares ownership of the managed object.
Comment: Understood the concept. But what is practical use case? any example?
Comment: @Fennekin The use cases of `weak_ptr` are almost the same as those of weak references in references based languages like Java, that is, extremely few!
Answer: A good example would be a cache.
For recently accessed objects, you want to keep them in memory, so you hold a strong pointer to them. Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer.
But what if that object is in use and some other code holds a strong pointer to it? If the cache gets rid of its only pointer to the object, it can never find it again. So the cache keeps a weak pointer to objects that it needs to find if they happen to stay in memory.
This is exactly what a weak pointer does -- it allows you to locate an object if it's still around, but doesn't keep it around if nothing else needs it.
Comment: @R.M.: Basically, yes. When you have a weak pointer, you can attempt to promote it to a strong pointer. If that object still exists (because at least one strong pointer to it exists still) that operation succeeds and gives you a strong pointer to it. If that object does not exist (because all strong pointers went away), then that operation fails (and typically you react by throwing away the weak pointer).
Comment: While a strong pointer keeps an object alive, a weak_ptr can look at it... without mucking with the object's life time.
Comment: So std::wake_ptr can point only where another pointer points and it points to nullptr when the object pointed is deleted/not pointed by any other pointers anymore?
Comment: Wait, what is wrong with the cache holding a shared_ptr and just removing it from its list when it should be cleared from memory? Any users will hold a shared_ptr all the same and the cached resource will be cleared as soon as all users are done with it.
Comment: Another example, which I've used a few times at least, is when implementing observers, it sometimes becomes convenient to have the subject maintain a list of weak pointers and do its own list cleanup. It saves a little bit of effort explicitly removing observers when they are deleted, and more significantly you don't have to have information about the subjects available when destroying observers which generally simplifies things a lot.
Comment: @DavidSchwartz Could you clear up more on this? I couldn't get like when an object is not in the cache, how the new users of the cache can find the object in the cache and promote the weak pointer to strong pointer.
Comment: There's an [implementation that does this](https://github.com/ripple/rippled/blob/develop/src/ripple/basics/TaggedCache.h) in the source code for rippled. If the object expires from the cache but there are existing strong pointers, it is demoted to being cached by a weak pointer. This permits the object to be destroyed if it's not being used but also found (and re-cached) if requested prior to being destroyed.
Comment: I still don't see why the cache should use weak_ptr over shared_ptr. Is it an issue of overhead? In either case, you have to maintain some kind of last-access-time list for all the objects if you're going to remove disused items periodically. So why choose one type of pointer over the other?
Comment: I read your answer three times, but didn't understand what you accurately said.
Comment: The cache use case could work with a shared reference if the cache was able to test if the refcount is 1, thus knowing it has the only reference and it could release it  reclaiming on demand. This would eliminate the need for weak references in this case. Weak references require a separate object for the count which [has some performance and space drawbacks](https://stackoverflow.com/questions/5671241/how-does-weak-ptr-work/5671308#5671308) (although afaik that's the way `shared_ptr` always works in C++ apparently, so no choice).
Comment: @Oscar How do you remove something from the cache without risking having an arbitrarily large number of copies of the item in memory then? If you keep the `strong_ptr`, the object never goes away. If you throw it away, then you can wind up with an unlimited number of copies of the object in memory as the next thread won't find it in the cache even if it's still in memory. Having the cache demote the `strong_ptr` to a `weak_ptr` solves the problem.
Comment: Thanks for your reply. If you're going to iterate through the cache periodically to check for agedness, it can check the reference count on a shared_ptr just as it would check the validity of a weak_ptr, right? If something is expiring from the cache, it's going to be removed whether its reference is a weak_ptr or a sole shared_ptr, right? I don't see why using a different pointer type causes a proliferation of "unlimited copies." If the object is re-created, it'll be added back to the cache and won't expire for a while, no?
Comment: @Milan The OS has no idea this cache exists, it's part of the application. A "strong pointer" is a pointer that represents ownership in the object and prevents it from being deleted.
Comment: @Milan 1) The cache is part of memory. Keeping them in cache means keeping them in memory. 2) If we didn't have a weak pointer to the object, how would we find it if someone checked for it in the cache? It's in memory, we want the cache to be able to find it. 3) Not really, though you can look at the code. https://github.com/ripple/rippled/blob/develop/src/ripple/basics/TaggedCache.h
Comment: @ShelbyMooreIII If you write a ref counted smart ptr without a weak ptr, you need a separate object to store the count, unless the count is allocated with the managed object.
Comment: ...Unless you're using the presence of a resource some sort of cancellation signal...
Comment: @rubenvb What happens if new users of the cache look for the object in the cache? They won't find it even though it's in memory. If an object is used for long enough, you could wind up with numerous copies of it in memory, defeating the purpose of the cache. With the weak pointer, new cache users can find the object and cause the weak pointer to be promoted to a strong pointer, putting the object back in the cache and avoiding having unlimited copies in memory.
Comment: @Oscar Say something is holding a `shared_ptr` to the object but it expires from the cache. What do you do? You don't want the cache to pin it in memory, so you can't keep a `shared_ptr`. But so long as the object is still in memory, you need to make sure code that checks the cache can find it. Other than having the cache hold a `weak_ptr`, what's your solution?
Comment: If something is still using it (holding another shared_ptr to it), I wouldn't remove it from the cache. It's in use... so why would you deem it "expired?" As you say, if it's still in memory, other code should be able to find it.  On our next pruning trip through the cache, we'll see if everyone's done with it, and if so it will then be expired.
Comment: @Oscar Typically a cache has a well-defined operation that finds an object in the cache and extends it life. Your scheme would work but would allow any access to the object at all to reset the life of the object in the cache. So it would produce results with different semantics. I agree that this is a pretty fine difference and likely both schemes would work just as well under most circumstances.
Comment: @DavidSchwartz, if possible, could you please elaborate on what did you mean by a **strong pointer**? Also, what did you mean by *you scan the cache* in "Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer."? If I'm not wrong, OS scan the cache, right?
Comment: Thanks @DavidSchwartz for clarifying however I still have some more confusion/questions (sorry if they are stupid) 1. For recently accessed objects, we want to keep them in the cache rather than memory, right? 2. if some other application already has a strong pointe then why do we need weak_ptr? As another application has strong ptr to that object, the reference count won't be 0, right? 3. If you have good references for your answer that I can look into for an in-depth explanation then please do share.
Answer: Another answer, hopefully simpler. (for fellow googlers)
Suppose you have Team and Member objects.
Obviously it's a relationship : the Team object will have pointers to its Members. And it's likely that the members will also have a back pointer to their Team object.
Then you have a dependency cycle. If you use shared_ptr, objects will no longer be automatically freed when you abandon reference on them, because they reference each other in a cyclic way. This is a memory leak.
You break this by using weak_ptr. The "owner" typically use shared_ptr and the "owned" use a weak_ptr to its parent, and convert it temporarily to shared_ptr when it needs access to its parent.
Store a weak ptr :
weak_ptr<Parent> parentWeakPtr_ = parentSharedPtr; // automatic conversion to weak from shared

then use it when needed
shared_ptr<Parent> tempParentSharedPtr = parentWeakPtr_.lock(); // on the stack, from the weak ptr
if( !tempParentSharedPtr ) {
  // yes, it may fail if the parent was freed since we stored weak_ptr
} else {
  // do stuff
}
// tempParentSharedPtr is released when it goes out of scope

Comment: It's not so bad, I would think. If a member can belong to many teams, using a reference won't work.
Comment: @paulm Team will not destroy "its" members. The whole point of `shared_ptr` is to share ownership, so no one has the particular responsibility to free the memory, it is freed automatically when no longer used. Unless there is a loop... You may have several teams sharing the same player (past teams ?). If the team object "owns" the members, then there is no need to use a `shared_ptr` to begin with.
Comment: How is this a memory leak? If team is destructed it will destruct its members, thus the shared_ptr ref count will be 0 and also destructed?
Comment: @paulm You are right. But since, in this example, team is also a `shared_ptr` referenced by its "team members", when will it got destroyed ? What you are describing is a case where there is no loop.
Comment: Before calling "lock" to acquire shared_ptr, one can also call the method "expired" to ensure whether the object is alive or not
Comment: It won't destroy them but its shared_ptr will go out of scope with it, decrements the use_count, thus at this point use_count is 0 and so the shared_ptr will delete what its pointing to?
Comment: It is a bad use case but many people write this kind of code with circular shared_ptr.
Comment: @Offirmo "_it is freed automatically when no longer used. Unless there is a loop..._" no, it is freed when no longer used in every case; when a loop exist... a loop exist; every element of the list is a user. **The objects are still used.** There is no "loop defect" or loophole in ref counting. Loops work as specified: they cannot be destructed, period.
Comment: Why wouldn't the members have a raw pointer to their team? If the relationship is that the team owns the member, then the member doesn't own its team, and the team will always exist if the member exists. Hence a raw pointer would work just fine.
Answer: Here's one example, given to me by @jleahy: Suppose you have a collection of tasks, executed asynchronously, and managed by an std::shared_ptr<Task>. You may want to do something with those tasks periodically, so a timer event may traverse a std::vector<std::weak_ptr<Task>> and give the tasks something to do. However, simultaneously a task may have concurrently decided that it is no longer needed and die. The timer can thus check whether the task is still alive by making a shared pointer from the weak pointer and using that shared pointer, provided it isn't null.
Comment: :Sounds like a good example but can you please elaborate you example a bit more? I am thinking when a task is finished, it's should already been removed from the std::vector> without a periodic check. So not sure if the std::vector> is very helpful here.
Comment: @zzz777: The logic that invalidates the objects may not even be aware of the existence of the queue or vector of observers. So the observer performs a separate loop over the weak pointers, acting on the ones that are still alive, and removing the dead ones from the container...
Comment: @KerekSB: yes and in case of queue you do not even have to a separate loop - then resource is available you discard expired weak_ptrs (if any) until you got valid one (if any).
Comment: You could also have the threads remove themselves from the collection, but that would create a dependency and require locking.
Comment: Similar comment with queues: say you have objects and you queue them for some resource, objects could be deleted while waiting. So, if you queue weak_ptrs you do not have to bother with deleting entries from there queue. Weak_ptrs will be invalidated and then discarded when encoutnered.
Comment: (scenario 1: having `weak_ptr`, instantiating a temporary `shared_ptr` through it, and then using that temp shared_ptr.  (scenario 2: checking whether the main `shared_ptr` is valid or `nullptr`/`NULL`? Don't you think scenario 2 is way more straightforward (and probably a bit faster)? This thing confuses me a lot and it still makes me wonder why do we need `weak_ptr`? (except for tackling cyclic dependencies). Thank you so much in advance!
Answer: When using pointers it's important to understand the different types of pointers available and when it makes sense to use each one. There are four types of pointers in two categories as follows:

Raw pointers:

Raw Pointer [ i.e. SomeClass* ptrToSomeClass = new SomeClass(); ]

Smart pointers:

Unique Pointers [ i.e.  std::unique_ptr<SomeClass> uniquePtrToSomeClass ( new SomeClass() ); ]
Shared Pointers [ i.e.  std::shared_ptr<SomeClass> sharedPtrToSomeClass ( new SomeClass() );  ]
Weak Pointers [ i.e.  std::weak_ptr<SomeClass> weakPtrToSomeWeakOrSharedPtr ( weakOrSharedPtr );  ]

Raw pointers (sometimes referred to as "legacy pointers", or "C pointers") provide 'bare-bones' pointer behavior and are a common source of bugs and memory leaks. Raw pointers provide no means for keeping track of ownership of the resource and developers must call 'delete' manually to ensure they are not creating a memory leak. This becomes difficult if the resource is shared as it can be challenging to know whether any objects are still pointing to the resource. For these reasons, raw pointers should generally be avoided and only used in performance-critical sections of the code with limited scope.
Unique pointers are a basic smart pointer that 'owns' the underlying raw pointer to the resource and is responsible for calling delete and freeing the allocated memory once the object that 'owns' the unique pointer goes out of scope. The name 'unique' refers to the fact that only one object may 'own' the unique pointer at a given point in time. Ownership may be transferred to another object via the move command, but a unique pointer can never be copied or shared. For these reasons, unique pointers are a good alternative to raw pointers in the case that only one object needs the pointer at a given time, and this alleviates the developer from the need to free memory at the end of the owning object's lifecycle.
Shared pointers are another type of smart pointer that are similar to unique pointers, but allow for many objects to have ownership over the shared pointer. Like unique pointer, shared pointers are responsible for freeing the allocated memory once all objects are done pointing to the resource. It accomplishes this with a technique called reference counting. Each time a new object takes ownership of the shared pointer the reference count is incremented by one. Similarly, when an object goes out of scope or stops pointing to the resource, the reference count is decremented by one. When the reference count reaches zero, the allocated memory is freed. For these reasons, shared pointers are a very powerful type of smart pointer that should be used anytime multiple objects need to point to the same resource.
Finally, weak pointers are another type of smart pointer that, rather than pointing to a resource directly, they point to another pointer (weak or shared). Weak pointers can't access an object directly, but they can tell whether the object still exists or if it has expired. A weak pointer can be temporarily converted to a shared pointer to access the pointed-to object (provided it still exists). To illustrate, consider the following example:

You are busy and have overlapping meetings: Meeting A and Meeting B
You decide to go to Meeting A and your co-worker goes to Meeting B
You tell your co-worker that if Meeting B is still going after Meeting A ends, you will join
The following two scenarios could play out:

Meeting A ends and Meeting B is still going, so you join
Meeting A ends and Meeting B has also ended, so you can't join

In the example, you have a weak pointer to Meeting B. You are not an "owner" in Meeting B so it can end without you, and you do not know whether it ended or not unless you check. If it hasn't ended, you can join and participate, otherwise, you cannot. This is different than having a shared pointer to Meeting B because you would then be an "owner" in both Meeting A and Meeting B (participating in both at the same time).
The example illustrates how a weak pointer works and is useful when an object needs to be an outside observer, but does not want the responsibility of sharing ownership. This is particularly useful in the scenario that two objects need to point to each other (a.k.a. a circular reference). With shared pointers, neither object can be released because they are still 'strongly' pointed to by the other object. When one of the pointers is a weak pointer, the object holding the weak pointer can still access the other object when needed, provided it still exists.
Comment: Raw pointers should not be avoided. It should be avoided to own an object through a raw pointer, but in cases where you reference something without owning it, a raw pointer is very useful. For example an object pointing back at the parent.
Answer: They are useful with Boost.Asio when you are not guaranteed that a target object still exists when an asynchronous handler is invoked. The trick is to bind a weak_ptr into the asynchonous handler object, using std::bind or lambda captures.
void MyClass::startTimer()
{
    std::weak_ptr<MyClass> weak = shared_from_this();
    timer_.async_wait( [weak](const boost::system::error_code& ec)
    {
        auto self = weak.lock();
        if (self)
        {
            self->handleTimeout();
        }
        else
        {
            std::cout << "Target object no longer exists!\n";
        }
    } );
}

This is a variant of the self = shared_from_this() idiom often seen in Boost.Asio examples, where a pending asynchronous handler will not prolong the lifetime of the target object, yet is still safe if the target object is deleted.
Comment: Why did it take so long to find this answer... P.S. you're not using your capture of `this`
Comment: @Orwellophile fixed. Force of habit when using the `self = shared_from_this()` idiom when the handler invokes methods within the same class.
Answer: shared_ptr : holds the real object.
weak_ptr  : uses lock to connect to the real owner or returns a NULL shared_ptr otherwise.

Roughly speaking, weak_ptr role is similar to the role of housing agency.  Without agents, to get a house on rent we may have to check random houses in the city. The agents make sure that we visit only those houses which are still accessible and available for rent.
Comment: @Milan As far as I'm concerned, `std::weak_ptr` will guarantee that `lock` is done atomically. So scenario 2 may miss some cases: after you check it's valid, you gonna assign it to another; What if the thread switches and the assignment is intercepted, and in between the original `std::shared_ptr` empty its resource? You will get an empty pointer in the assignment but regard it as valid in your code block, which may cause strange crashes. Scenario 1 will not since all operations are down (equivalent to) "at the same time".
Comment: (scenario 1: having `weak_ptr`, instantiating a temporary `shared_ptr` through it, and then using that temp shared_ptr.  (scenario 2: checking whether the main `shared_ptr` is valid or `nullptr`/`NULL`? Don't you think scenario 2 is way more straightforward (and probably a bit faster)? This thing confuses me a lot and it still makes me wonder why do we need `weak_ptr`? (except for tackling cyclic dependencies). Thank you so much in advance!
Answer: weak_ptr is also good to check the correct deletion of an object - especially in unit tests. Typical use case might look like this:
std::weak_ptr<X> weak_x{ shared_x };
shared_x.reset();
BOOST_CHECK(weak_x.lock());
... //do something that should remove all other copies of shared_x and hence destroy x
BOOST_CHECK(!weak_x.lock());

Answer: Apart from the other already mentioned valid use cases std::weak_ptr is an awesome tool in a multithreaded environment, because

It doesn't own the object and so can't hinder deletion in a different thread
std::shared_ptr in conjunction with std::weak_ptr is safe against dangling pointers - in opposite to std::unique_ptr in conjunction with raw pointers
std::weak_ptr::lock() is an atomic operation (see also About thread-safety of weak_ptr)

Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join() etc is omitted, the threads would have to be handled differently in a real implementation etc)
// a simplified class to hold the thumbnail and data
struct ImageData {
  std::string path;
  std::unique_ptr<YourFavoriteImageLibData> image;
};

// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
   for( auto& imageData : imagesToLoad )
     imageData->image = YourFavoriteImageLib::load( imageData->path );
}

// a simplified manager
class Manager {
   std::vector<std::shared_ptr<ImageData>> m_imageDatas;
   std::vector<std::unique_ptr<std::thread>> m_threads;
public:
   void load( const std::string& folderPath ) {
      std::vector<std::string> imagePaths = readFolder( folderPath );
      m_imageDatas = createImageDatas( imagePaths );
      const unsigned numThreads = std::thread::hardware_concurrency();
      std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas =
        splitImageDatas( m_imageDatas, numThreads );
      for( auto& dataRangeToLoad : splitDatas )
        m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
   }
};

But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.
You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.
The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr in conjunction with std::weak_ptr.
// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
   for( auto& imageDataWeak : imagesToLoad ) {
     std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
     if( !imageData )
        continue;
     imageData->image = YourFavoriteImageLib::load( imageData->path );
   }
}

// a simplified manager
class Manager {
   std::vector<std::shared_ptr<ImageData>> m_imageDatas;
   std::vector<std::unique_ptr<std::thread>> m_threads;
public:
   void load( const std::string& folderPath ) {
      std::vector<std::string> imagePaths = readFolder( folderPath );
      m_imageDatas = createImageDatas( imagePaths );
      const unsigned numThreads = std::thread::hardware_concurrency();
      std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas =
        splitImageDatasToWeak( m_imageDatas, numThreads );
      for( auto& dataRangeToLoad : splitDatas )
        m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
   }
};

This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation.
You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.
Answer: I see a lot of interesting answers that explain reference counting etc., but I am missing a simple example that demonstrates how you prevent memory leak using weak_ptr. In first example I use shared_ptr in cyclically referenced classes. When the classes go out of scope they are NOT destroyed.
#include<iostream>
#include<memory>
using namespace std;

class B;

class A
{
public:
    shared_ptrbptr;
    A() {
        cout << "A created" << endl;
    }
    ~A() {
        cout << "A destroyed" << endl;
    }
};

class B
{
public:
    shared_ptraptr;
    B() {
        cout << "B created" << endl;
    }
    ~B() {
        cout << "B destroyed" << endl;
    }
};

int main()
{
    {
        shared_ptr a = make_shared();
        shared_ptr b = make_shared();
        a->bptr = b;
        b->aptr = a;
    }
  // put breakpoint here
}

If you run the code snippet you will see as classes are created, but not destroyed:
A created
B created

Now we change shared_ptr's to weak_ptr:
class B;
class A
{
public:
    weak_ptrbptr;

    A() {
        cout << "A created" << endl;
    }
    ~A() {
        cout << "A destroyed" << endl;
    }
};

class B
{
public:
    weak_ptraptr;

    B() {
        cout << "B created" << endl;
    }
    ~B() {
        cout << "B destroyed" << endl;
    }
};

    int main()
    {
        {
            shared_ptr a = make_shared();
            shared_ptr b = make_shared();
            a->bptr = b;
            b->aptr = a;
        }
      // put breakpoint here
    }

This time, when using weak_ptr we see proper class destruction:
A created
B created
B destroyed
A destroyed

Comment: A working example like this, is worth a thousand words. Thanks.
Answer: I see std::weak_ptr<T> as a handle to a std::shared_ptr<T>: It allows me
to get the std::shared_ptr<T> if it still exists, but it will not extend its
lifetime. There are several scenarios when such point of view is useful:
// Some sort of image; very expensive to create.
std::shared_ptr< Texture > texture;

// A Widget should be able to quickly get a handle to a Texture. On the
// other hand, I don't want to keep Textures around just because a widget
// may need it.

struct Widget {
    std::weak_ptr< Texture > texture_handle;
    void render() {
        if (auto texture = texture_handle.get(); texture) {
            // do stuff with texture. Warning: `texture`
            // is now extending the lifetime because it
            // is a std::shared_ptr< Texture >.
        } else {
            // gracefully degrade; there's no texture.
        }
    }
};

Another important scenario is to break cycles in data structures.
// Asking for trouble because a node owns the next node, and the next node owns
// the previous node: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > next;
    std::shared_ptr< Node > prev;
};

// Asking for trouble because a parent owns its children and children own their
// parents: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::shared_ptr< Node > next;
    std::weak_ptr< Node > prev;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::weak_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

Herb Sutter has an excellent talk that explains the best use of language
features (in this case smart pointers) to ensure Leak Freedom by Default
(meaning: everything clicks in place by construction; you can hardly screw it
up). It is a must watch.
Answer: http://en.cppreference.com/w/cpp/memory/weak_ptr
std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership. If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
In addition, std::weak_ptr is used to break circular references of std::shared_ptr.
Comment: "_to break circular references_" how?
Comment: @curiousguy Rainer Grimm has done a pretty good job in explaining these circular references and how to break them using `std::weak_ptr`: "Back to Basics: Smart Pointers - Rainer Grimm - CppCon 2020" -- https://youtu.be/sQCSX7vmmKY?t=2496 (for some reason if the video starts from the beginning then skip to *41:36*)
Comment: This is just a copy/paste of the link, which people searching could already find themselves. It adds nothing.
Answer: There is a drawback of shared pointer:
shared_pointer can't handle the parent-child cycle dependency. Means if the parent class uses the object of child class using a shared pointer, in the same file if child class uses the object of the parent class. The shared pointer will be failed to destruct all objects, even shared pointer is not at all calling the destructor in cycle dependency scenario. basically shared pointer doesn't support the reference count mechanism.
This drawback we can overcome using weak_pointer.
Comment: @curiousguy you didn't ask "How can a `weak_ptr` deal with a circular dependency with no change in program logic as a drop-in replacement for `shared_ptr`?" :-)
Comment: @curiousguy, a child employs a weak reference to the parent, then the parent can be deallocated when there are no shared (strong) references pointing to it. Thus when accessing the parent via the child, the weak reference has to tested to see if the parent is still available. Alternatively to avoid that extra condition, a circular reference tracing mechanism (either mark-sweep or probing on refcount decrements, both of which have bad asymptotic performance) can break the circular shared references when the only shared references to the parent and child are from each other.
Comment: How can a weak reference deal with a circular dependency?
Comment: @ShelbyMooreIII "_has to tested to see if the parent is still available_" yes, and you have to be able to react correctly to the unavailable case! Which doesn't occur with a real (i.e. strong) ref. Which means weak ref is not a drop in replacement: it requires a change in the logic.
Answer: When we does not want to own the object:
Ex:
class A
{
    shared_ptr<int> sPtr1;
    weak_ptr<int> wPtr1;
}

In the above class wPtr1 does not own the resource pointed by wPtr1. If the resource is got deleted then wPtr1 is expired.
To avoid circular dependency:
shard_ptr <----| shared_ptr <------
    ^             |          ^          |
    |             |          |          |
    |             |          |          |
    |             |          |          |
    |             |          |          |
class A           |     class B         |
    |             |          |          |
    |             ------------          |
    |                                   |
    -------------------------------------

Now if we make the shared_ptr of the class B and A, the use_count of the both pointer is two.
When the shared_ptr goes out od scope the count still remains 1 and hence the A and B object does not gets deleted.
class B;

class A
{
    shared_ptr sP1; // use weak_ptr instead to avoid CD

public:
    A() {  cout << "A()" << endl; }
    ~A() { cout << "~A()" << endl; }

    void setShared(shared_ptr& p)
    {
        sP1 = p;
    }
};

class B
{
    shared_ptr sP1;

public:
    B() {  cout << "B()" << endl; }
    ~B() { cout << "~B()" << endl; }

    void setShared(shared_ptr& p)
    {
        sP1 = p;
    }
};

int main()
{
    shared_ptr aPtr(new A);
    shared_ptr bPtr(new B);

    aPtr->setShared(bPtr);
    bPtr->setShared(aPtr);

    return 0;
}

output:
A()
B()

As we can see from the output that A and B pointer are never deleted and hence memory leak.
To avoid such issue just use weak_ptr in class A instead of shared_ptr which makes more sense.
Answer: Inspired by @offirmo's response I wrote this code and then ran the visual studio diagnostic tool:
#include <iostream>
#include <vector>
#include <memory>

using namespace std;

struct Member;
struct Team;

struct Member {
    int x = 0;

    Member(int xArg) {
        x = xArg;
    }

    shared_ptr<Team> teamPointer;
};

struct Team {
    vector<shared_ptr<Member>> members;
};

void foo() {
    auto t1 = make_shared<Team>();
    for (int i = 0; i < 1000000; i++) {
        t1->members.push_back(make_shared<Member>(i));
        t1->members.back()->teamPointer = t1;
    }
}

int main() {
    foo();

    while (1);

    return 0;
}

When the member pointer to the team is shared_ptr teamPointer the memory is not free after foo() is done, i.e. it stays at around 150 MB.
But if it's changed to weak_ptr teamPointer in the diagnostic tool you'll see a peak and then memory usage returns to about 2MB.

When is std::weak_ptr useful?


Which functions make it true? $(f(x)+g(x))^{-1} = f^{-1}(x) + g^{-1}(x)$

Question: Sum of inverses is inverse of sum:
$$(f(x)+g(x))^{-1} = f^{-1}(x) + g^{-1}(x)$$
It is not true for all functions.
For example $x$ is its own function inverse, but $x+x = 2x$ but the inverse is $x/2$ not $2x$.
Which functions make it true?
$$(f(x)+g(x))^{-1} = f^{-1}(x) + g^{-1}(x)$$
By $^{-1}$ I mean inverse of the function, not $1$ divided by it.
Comment: I doubt many or any do. Try your example with any  $f(x)$ that satisfies the claimed identity instead of $x$.
Answer: If you don't mind complex solutions, you can do it:  for any $b \ne 0$ take
$$ f(x) = b x,\ g(x) =  b \omega x$$
Thus
$$ f^{-1}(x) = x/b, \ g^{-1}(x) = x/(b \omega)$$
and
$$ f(x) + g(x) = b (1+\omega) x, \ (f+g)^{-1}(x) = x/(b (1+\omega))$$
So $(f+g)^{-1} = f^{-1} + g^{-1}$ if
$$ \frac{1}{1+\omega} = 1 + \frac{1}{\omega} $$
which is true if $1 + \omega + \omega^2 = 0$.  The roots of this are $\omega = \frac{1 \pm \sqrt{3} i}{2}$, the primitive cube roots of $-1$.
Comment: Thank you . So does it mean there is no real value solution?
Comment: We can leverage this to show is no real, differentiable solution with $f(0)=g(0)=0$.


Which cache have to clear to update new hooks?

Question: I added a new hook inside a module (hook_cart_commerce_pricecomponent_type_info_alter), which cache have to clear to only update that new hook? I mean i do not want to clear all caches.
Administration menu?
Class registry?
Menu?
Page and else?
Theme registry?
Token registry?
Update data?
Comment: I'm not sure exactly but it'll be either `hook_info` or `module_implements` (or maybe both) in the `cache_bootstrap` bin. You can't invalidate a single hook implementation (unless you alter the cache item manually) so the whole lot will be rebuilt on the next request.
Answer: To register a new hook, you can clear the following caches:
cache_clear_all('module_implements', 'cache_bootstrap');
cache_clear_all('hook_info', 'cache_bootstrap');

More info: https://api.drupal.org/api/drupal/includes%21module.inc/function/module_implements/7
Answer: If using drush, drush cc registry will suffice for that hook.
Answer: Theme Registry

The most common case for manually registering hooks is in forms. Form elements are them-able but there is another dimension to how they are processed. There are the generic elements such as check-boxes, radio selects, submit button, drop down menus, etc. Each element is them-able on its own and overriding it does not require manually registering the hooks associated with it. The extra dimension comes in with custom forms where each element is arranged in very specific ways. In some forms, they are already arranged, themed and registered. For these forms, manually registering is not required. The forms that are not explicitly themed will default to how form API renders them.
Comment: The OP is not asking about manually registering a hook. They changed the code of a module without first disabling it.
Answer: You can use:

module_implements()
or:

hook_module_implements_alter()
Answer: You can rebuild the registry to force Drupal to re-scan the code files and register your hook implementations. To do this with drush:

Before first use, install registry_rebuild:
drush dl registry_rebuild

Rebuild the registry:
drush rr

This worked for me in a case where both drush cc registry, drush cc all and clearing the hook_info and module_implements caches failed.
Comment: The question was how to avoid clearing all caches when a new hook is added. `drush rr` will definitely clear all caches.
Comment: @AlexBukach As I mentioned in the answer, `drush rr` is an option for cases where *even clearing all caches does not help*, so certainly clearing any one cache would not help either in such a case. I don't remember anymore what kind of special case I had that needed `drush rr`, but one day somebody will have one again, and love to find this answer …


Angular ngClick cannot access variable in a different scope

Question: I am completely new to Javascript and especially AngularJs. Here is my problem, I need to call ng-click function inside ng-repeat to hide a some html outside of it.
As I understand the problem is because all of the variables (in this case specifically variable "locations") is in another scope which I cannot access. Can anybody help me with the shortest way possible to go around this problem?
I have managed so far to almost finish my website with only angular html tags (meaning I didn't really have to write any custom functions) and this is the absolute last piece.
Also, as I understand whenever a new controller in angular is created, it has its own scope. In this case, all of the calls (besides the one that I am having problems with) have been made without initializing any of the controllers, so how do you access variables? Is there something like a "default Scope"? I know rootScope did not work for me.
Thank you in advance.

Comment: Why did rootscope not work? What have you tried?
Comment: I honestly have no idea. It was as if the variables were not in rootScope at all.
Answer: You will have to create a controller surrounding both HTML fragments:

The controller will define the locations property, but inside another object (let's call it viewState):
app.controller("Ctrl", function($scope) {
    $scope.viewState = {
        locations: false
    };
};

Then bind to the inner locations:

...

The reason for this, and why it didn't work for you with the $rootScope is how scopes inherit the properties of their parents through Javascript's prototypical inheritance. Roughly and really shortly:
When you read a property from a scope and that scope does not contain this property, JS will look at its prototype (again very roughly speaking, the scope's parent scope). The chain continues up to the $rootScope. So, putting locations in the $rootScope will result in successful reading of this property.
Whenever you write a variable to a scope, it is written directly to that scope, no matter where it was read from. So changing locations in the inner scope has no effect in the outer scope (e.g. $rootScope).
Putting the variable inside an object results in reading the object, which resolves to the correct scope, then writting the property to the correct object.
Comment: Thank you. I had a feeling it will come to this (as I was searching more info about it), I was just reluctant to go this way as it means that the way I use angular is wrong in itself.

But thanks once again. It is clear to me.
Comment: To be honest, I don't like mixing application logic in the view. I always try to separate the logic from the view.
Answer: This is what I ended up using. It seems extremely simple but maybe it will help others who are beginners as well. This is basically the code for making values accessible in different controllers. It is the same as Nikos suggested if I understood it correctly.
var myApp = angular.module('myApp',[]);

    myApp.value('Pages',{page:"My Profile"});
    myApp.value('Menu',{show:false});
    myApp.value('Menu2',{show2:false});

    myApp.controller('MainMenu', function($scope,Menu,Pages) {
        $scope.menu = Menu;
        $scope.pages = Pages;
    });

    myApp.controller('MainSidebar', function($scope,Menu,Menu2,Pages) {
        $scope.menu = Menu;
        $scope.menu2 = Menu2;
        $scope.pages = Pages;
    });

    myApp.controller('SecondSidebar', function($scope,Menu,Menu2,Pages) {
        $scope.menu = Menu;
        $scope.menu2 = Menu2;
        $scope.pages = Pages;
    });

    myApp.controller('TripsFx', function($scope,Menu2,Pages) {

        $scope.menu2 = Menu2;
        $scope.pages = Pages;
    })

Answer: This is what I do to have an  accessible Rootscope.
Set up Rootscope in app.run: (Don't forget to inject $rootScope)
    var myApp = angular.module('ProGen', []);
    myApp.run(function($rootScope) {
      //setup Rootscope
      $rootScope.locations = false;
    })

Create a Controller with a function that changes Rootscope ($rootscope injected too)
    function someCtrl($rootScope, $scope) {
      $scope.travels = [
        {dest: 'Rome'},
        {dest: 'London'}
        ];

      $scope.flipMenu = function() {
        $rootScope.locations = !$rootScope.locations;
      }

    }

So this is the html:

            {...}

x1

x2

x3

x4

y1

y2

y3

y4

Change me (no Controller)

And this is the JS:
  var myApp = angular.module('ProGen', []);
  myApp.run(function($rootScope) {
    //setup Rootscope
    $rootScope.locations = false;
  })

function someCtrl($rootScope, $scope) {
  $scope.travels = [
    {dest: 'Rome'},
    {dest: 'London'}
    ];

  $scope.flipMenu = function() {
    $rootScope.locations = !$rootScope.locations;
  }
}

You will find a working Plunker here: http://plnkr.co/edit/ygLlIoE55aI5q8Wkicc5?p=preview
Not sure if this what you wanted. But I hope it helps anyway.
(Don't yell at me that this is against Angular Zen, because of reasons:-)
Comment: Thanks for your help. I solved it by using what is called Factory I guess. :)

The thing is that it's basically the same logic behind using $rootScope and creaiting a Factory with accessible values so I just went the way that is as I understood more conventional. :)

I was trying to use $rootScope so I would avoid rewriting the whole logic behind my angular but I had to do it anyway, so I create separate controllers for all the chunks that I use and just passed the necessary values where it was needed. But once again thanks for your effort :)


Providing parameter names for delegate types

Question: Is it possible to specify parameter names for delegate types in F#? When I create a delegate of this type in F#:
type DataValidationEventHandler = delegate of obj * DataValidationEventArgs -> unit

...it auto-generates this signature for the handler in C#:
static void loader_ValidationEvent(object __p1, DataValidationEventArgs __p2)

Ideally it would generate the usual 'sender' and 'e' parameter names.
Answer: Yes:
type DataValidationEventHandler = delegate of sender:obj * e:DataValidationEventArgs -> unit

Comment: Bleh. I tried that, but I put parens around 'sender:obj' (as you would in a function signature). Good to know that doesn't work. Thanks.
Comment: @Bless Yahu - in C# delegate types always have parameter names - there is no way to omit them.  For example the equivalent C# delegate would be `delegate void DataValidationEventHanlder(object sender, DataValidationEventArgs e)`.
`
Comment: My mistake, I was mistook this on how to provide the xml comments for parameters of delegates.
Answer: Yes:
type MyDel = delegate of o:obj * ea:System.EventArgs -> unit

names them o and ea.


Minimizing the sum of the tangents of the half-angles of a triangle

Question: In a given $\triangle ABC$ what can be the minimum value of
$$\tan(\angle A/2) + \tan(\angle B/2) + \tan(\angle C/2)$$
I think it will be minimal in case of an equilateral triangle but I can't prove it
Context:
I had the problem of minimising the sum
$$\tan^2(\angle A/2) + \tan^2(\angle B/2) + \tan^2(\angle C/2)$$ which I wrote as
$$(\tan(\angle A/2) + \tan(\angle B/2) + \tan(\angle C/2))^2-2(\tan(\angle A/2)\tan(\angle B/2)+\tan(\angle C/2)\tan(\angle B/2)+\tan(\angle C/2)\tan(\angle A/2))$$
And the second term here is a constant which is one.
Comment: See [Jensen's Inequality](https://en.wikipedia.org/wiki/Jensen's_inequality)
Comment: Could you provide a more elementary approach that does not involve calculus?
Comment: Yes I can work with cauchy Schwarz but please provide more details
Comment: You've posed a problem that can be resolved by reasoned mathematical argument, but omitted important context such as the source of the problem or its motivation/importance/difficulty.  As your Comments reveal, you have definite wishes regarding what techniques can be used in the solution, so clarification of context is called for.  Voting to close.
Comment: @hardmath It was all fine until now and I had also recieved some solutions. I don't know what is your problem.
Comment: I'm glad you received help, but consider the benefit to future Readers if you supplied the missing context.  The [Quick Tour](https://math.stackexchange.com/tour) and other Help Center articles may explain the importance of supplying context better.
Comment: Ok now I have provided the relevant context. How do I reopen it?
Comment: Okay, it's a little cryptic but I'm able to follow your thinking.  Voting to reopen.  Your edit will already have put this Question into the review queue.
Answer: We will show that

Given $x,y,z>0$ s.t. $x+y+z = \pi/2$, $$\tan(x)+\tan(y)+\tan(z) \ge \sqrt 3$$

I still believe Jensen is the best way. Since the OP asks for a non-calculus approach, here are a few hints:

First, show that for $x,y \in (0,\pi/2)$
$$\boxed{\tan(x)+\tan(y) \ge 2\tan((x+y)/2)}$$
with equality iff $\boxed{x=y}$.
This is equivalent to showing$$\cos^2((x+y)/2) \ge \cos(x)\cos(y)$$which is true since $\cos^2((x+y)/2) = (\cos(x+y)+1)/2$ and $\cos(x)\cos(y) = (\cos(x+y)+\cos(x-y))/2$. This reduces the problem to$$1\ge\cos(x-y)$$and the equality case is also clear.
Then, note that for $x>0$,
$$\boxed{2x+\frac{1-x^2}{2x} \ge \sqrt 3}$$
with equality iff $\boxed{x = 1/\sqrt 3}$.
This should be easy as simplification leads to
$$(\sqrt 3x - 1)^2 = 3x^2-2\sqrt3x + 1 \ge 0$$
This can also be done by using AM-GM
$$\frac{1+3x^2}{2x} \ge \frac{\sqrt3x}{x} = \sqrt3$$
Observe that $$\boxed{\tan(z)} = \tan(\pi/2 - (x+y)) = \cot(x+y) = 1/\tan(x+y) = \boxed{\frac{1-\tan^2((x+y)/2)}{2\tan((x+y)/2)}}$$
Now, use the above three steps to prove the inequality. Also verify that the equality cases do not contradict each other and that equality is possible.
Answer: Instead of $\frac12\angle A,\frac12\angle B,\frac13\angle C$, let's call the three half angles as $\theta_1,\theta_2,\theta_3$.
Let $t_i = \tan\theta_i$ for $i = 1,2,3$.
Notice $\theta_1 + \theta_2 + \theta_3 = \frac{\pi}{2}$.
By tangent addition formula for 3 angles
${}^{\color{blue}{[1]}}$, we have
$$\infty = \tan(\theta_1 + \theta_2 + \theta_3) = \frac{t_1 + t_2 + t_3 - t_1 t_2 t_3}{1 - (t_1 t_2 + t_2 t_3 + t_3 t_1)}$$
Notice $\theta_1,\theta_2,\theta_3 \in \left(0,\frac{\pi}{2}\right)$, $t_1,t_2,t_3$ are finite numbers. In order to get $\infty$, the denominator at RHS needs to vanish. This leads to the equality
$$t_1 t_2 + t_2 t_3 + t_3 t_1 = 1$$
Apply Cauchy Schwarz to the 3 tuples $(t_1,t_2,t_3)$ and $(t_2,t_3,t_1)$, we obtain
$$t_1^2 + t_2^2 + t_3^2 \ge t_1 t_2 + t_2 t_3 + t_3 t_1 = 1$$
As a result,
$$(t_1 + t_2 + t_3)^2
= t_1^2 + t_2^2 + t_3^2 + 2(t_1t_2 + t_2t_3 + t_3t_1)
\ge 3$$
and hence
$$
\tan \theta_1 + \tan \theta_2  + \tan \theta_3 = t_1 + t_2 + t_3 \ge \sqrt{3}$$
This lower bound $\sqrt{3}$ is achieved at $\theta_1 = \theta_2 = \theta_3 = \frac{\pi}{6}$, ie. when $\triangle ABC$ is an equilateral triangle.
Notes

$\color{blue}{[1]}$ - This a special case of a more general formula.

Given $n$ angles $\theta_1,\ldots,\theta_n$,
$$\tan\left(\sum_{k=1}^n\theta_k\right) =
\frac{ s_1 - s_3 + s_5 - \cdots }{1 - s_2 + s_4 - \cdots}$$
where $\displaystyle\;
s_k = \sum_{\stackrel{S \subset \{1,\ldots,n\}}{ |S| = k}} \prod_{j \in S}\tan\theta_j\;$
Comment: Although I agree with the solution, and it had occurred to me before, I am not sure whether concluding $1 - (t_1 t_2 + t_2 t_3 + t_3 t_1) = 0$ from $\infty = \frac{t_1 + t_2 + t_3 - t_1 t_2 t_3}{1 - (t_1 t_2 + t_2 t_3 + t_3 t_1)}$ is valid....
Comment: @DS Since all $\theta_i \in (0,\pi/2)$, all $t_i$ are finite numbers. In order for $\tan(\sum\theta_i) = \infty$, the denominator need to vanish.
Comment: @DS   $\theta_1+\theta_2 = 90-\theta_3$ applying tan on both sides and simplifying also gives the same result


DrupalDateTime::createFromFormat() returns the wrong time value

Question: I want to get the date of last monday at 00:00:00 in a specific timezone. When I try this:
DrupalDateTime::createFromFormat('U', strtotime('last week monday'))->setTime(0, 0, 0)->setTimezone(new \DateTimeZone('America/New_York'))->render()

The result is:
2022-06-12 20:00:00 America/New_York

Which is actually Sunday at 10 PM.
How can I get it to return 2022-06-13 00:00:00 America/New_York instead?
This "corrects" what I was seeing, but feels wrong:
    date_default_timezone_set('America/New_York');
    $from = DrupalDateTime::createFromFormat('U', strtotime('last week monday'))->getTimestamp();
    $to = DrupalDateTime::createFromFormat('U', strtotime('last monday'))->getTimestamp();

This gives me:
June 13th, 2022 12:00 AM
June 20th, 2022 12:00 AM

Which is last week monday through last monday (this week). Is calling ->format() setting the timezone offset twice, perhaps?
If I format this timestamp using:
DrupalDateTime::createFromFormat('U', $returned_value)->format('F j, Y H:i:s e')

I get this on the screen:
June 13, 2022 04:00:00 +00:00

The server is in UTC time. I simply want the timestamp of a date, without offsets applied (but correctly formatted to the user).
Edit:
The objective is to query for entities in Drupal created in the last week (starting on Monday), at midnight (00:00:00) through the following Monday at midnight, in this specific timezone.
Comment: I'm thinking you probably have to set the timezone before the time. It's only a hypothesis though.
Answer: I can see nothing unexpected. Midnight in UTC is 8 PM the day before in New York, at least in the summer time.
Timestamps are always UTC. This is the reason why your second attempt
$from = DrupalDateTime::createFromFormat('U', strtotime('last week monday'))->getTimestamp();

can be reduced to
$from = strtotime('last week monday');

without changing the result.
Original question
How can I get it to return 2022-06-13 00:00:00 America/New_York instead?
In this case don't convert to UTC timestamps. You can specify the timezone (the Drupal enhanced DrupalDateTime object accepts the timezone as string) when creating the object:
$from = (new DrupalDateTime('last week monday', 'America/New_York'))->render();

results in
"2022-06-13 00:00:00 America/New_York"

Which will internally use a different timestamp than before, but this is only relevant if you convert it to a different timezone, for example to store it in the database or use it in a query against stored values.
Updated OP in the comments
The goal is to query for nodes created Monday to Monday, which only happens in this timezone in EDT.
The Created field in nodes is a timestamp field, so in this case you need the UTC timestamp:
$from = (new DrupalDateTime('last week monday', 'America/New_York'))->getTimestamp();

As you have already noticed in the second attempt, using legacy PHP date_default_timezone_set()/strtotime(), this will be indeed 4 hours ahead of New York time.
Comment: Is it fair to say entity created/changed timestamps are in UTC, then? For some reason I thought the Regional date setting in the admin may have affected this.
Comment: Updated OP. The goal is to query for nodes created Monday to Monday, which only happens in this timezone in EDT. No storage or saving.
Comment: Yes, this is fair to say. The regional settings affect how dates are entered and displayed. Storage is always UTC, also for complex date fields.
Comment: In this case the mentioned internal timestamp is exactly what you are looking for, see the edit.
Comment: @Kevin Unix timestamps by definition are the number of seconds (minus leap second) since 00:00:00 UTC on 1 January 1970. Internally, Drupal does everything in UTC ; time zones are an input/output thing.
Comment: @mpdonadio Yes, Unix timestamps use UTC, but that is different from the class that ignores the timezone when it gets a timestamp. Using procedural code, you would not get that behavior. (That's how the PHP class behaves, though, and the Drupal class inherits it.)
Answer: I tried different snippets, but they all output a time for June 12, not for June 13.
echo DrupalDateTime::createFromFormat('U', strtotime('last week monday'), new \DateTimeZone('America/New_York'))
  ->setTime(0, 0, 0)
  ->render(), "\n";
// 2022-06-12 00:00:00 +00:00

echo DrupalDateTime::createFromFormat('U', strtotime('last week monday'))
  ->setTimezone(new \DateTimeZone('America/New_York'))
  ->setTime(0, 0, 0)
  ->render(), "\n";
// 2022-06-12 00:00:00 America/New_York

echo DrupalDateTime::createFromTimestamp(strtotime('last week monday'), new \DateTimeZone('America/New_York'))
  ->setTime(0, 0, 0)
  ->render(), "\n";
// 2022-06-12 00:00:00 America/New_York

echo DrupalDateTime::createFromTimestamp(strtotime('last week monday'), new \DateTimeZone('America/New_York'))
  ->render(), "\n";
// 2022-06-12 18:00:00 America/New_York

The only way to get the expected result is to set the default timezone with date_default_timezone_set(). In that case, the following code outputs the expected result.
date_default_timezone_set('America/New_York');
echo DrupalDateTime::createFromTimestamp(strtotime('last week monday'))->render(), "\n";
// 2022-06-13 00:00:00 America/New_York

Notice that isn't necessary to call setTime(0, 0, 0), since strtotime('last week monday') returns a timestamp for midnight of last week Monday. (It can be verified with echo date("F j, Y, g:i a", strtotime("last week monday")), "\n"; which outputs June 13, 2022, 12:00 am.)
Answer: DrupalDateTime::createFromFormat() is basically a wrapper for PHP's createFromFormat.
A search of the PHP docs reveals this comment:

createFromFormat('U') has a strange behaviour: it ignores the
datetimezone and the resulting DateTime object will always have
GMT+0000 timezone.

So, PHP bug or feature, you decide.
To create a DateTime object with a time based on a string, as a general approach:

Instantiate the DateTime object with the timezone you want.
Change the object's time.

Source: I spent the past two years working on some scheduling software implemented in Drupal that does a lot of date manipulation, and ran into tons of gotchas like this.
EDIT

The objective is to query for entities in Drupal created in the last
week (starting on Monday), at midnight (00:00:00) through the
following Monday at midnight, in this specific timezone.

Drupal always stores dates in the database as UTC.  So if you are doing an EntityQuery, here is one way to do it:

Create a DateTime object. Set the timezone to the desired timezone.
Set the DateTime to the desired date and time.
Change the DateTime's timezone to UTC: $datetime->setTimeZone(timezone_open(DateTimeItemInterface::STORAGE_TIMEZONE));
Get a proper string from the DateTime: $datetime->format((DateTimeItemInterface::DATETIME_STORAGE_FORMAT).
Run the EntityQuery with that string.
Comment: Yes, this kind of date stuff has always been a blind spot for me. I was trying to use the Drupal wrappers thinking it may be easier, wound up doing the opposite. I also thought for some reason the timezone setting in the application affected this, but that does not seem to be the case.
Comment: The Drupal (site) timezone setting has basically no effects.  I don't use the Drupal wrappers but I do use the constants (see the update to my answer) to ensure I don't accidentally set things incorrectly.


Use VSCode Language specific settings for .min.js

Question: Visual Studio Code Version 1.10 adds the ability to specify languages settings on a per language basis (*1). You put something like this in your settings.json file:
"[javascript]": {
    "editor.fontSize": 100,
}

I'd like to do something more specific. I'd like to apply different rules to files that match *.min.js.
How would I do that?
I've actually got something that works, but it's a bit hacky, so I thought I'd ask.

*1) In case you want to know which ones: Use autocomplete after typing in "[]":, or see languageIds array in this file.
I'm aware beautify skips formatting min files by default. But just using "editor.formatOnSave": true, this doesn't seem to happen. Also, other non-formatting stuff like wordwrap is nice.
Answer: Here's my current solution:
"files.associations": {
    "*.min.js": "javascriptreact"
},
// Hijack javascriptreact to create custom settings for min.js files
"[javascriptreact]": {
    "editor.formatOnSave": false,
    "editor.wordWrap": "on"
}

I'm using the fact that vscode happens to have a second type of javascript, one that isn't used my my project. Not ideal, but it seems to work.


Software to Detect Device Missing from Network?

Question: I have several small Android tablets that I am going to deploy in a manufacturing environment. Each one will be assigned to an individual, but I'd still like to have some way of detecting if the devices are off of my network for longer than, say, a week or two. This will help identify theft as well as ensuring that the devices are actually being used. My search for a program that does this has been fruitless so far. Any ideas on what would fill this requirement?
Answer: You want an MDM solution that can do geo-fencing and asset reporting. This is a pretty common set of features.
Comment: Office365, Exchange on prem, Goole apps all have MDM features
Comment: I like the idea, but it seems overkill for my particular situation
Answer: You could use a local instance of PRTG Network Monitor that would allow you to set basic ping return thresholds that will alert you by email or text message that the device has not reported in. Its lightweight and I use it for temporary demo devices on our campus.
https://www.paessler.com/prtg
It is free for less than 100 sensors. Given your intended use, I cannot see you hitting this threshold. It would, however, require you to set a static IP address for the device.
Comment: It looks like this will be the best solution for my problem.


Mean value theorem question - proving F constant - answer check

Question: The question:
Given $f$ continuity at $[a,b]$ and derivative at $(a,b)$.
It is known $f'(x)=0$ for each x belongs to $(a,b)$.
prove $f$ is constant.
My Answer:
Need to prove $f(x)=k$ for each X belongs to $[a,b]$
Creating a new function: $$g(x)=f(x)-k$$
$g(x)$ is also continuity and derivative at $[a,b]$ and thus I can use the Mean value theorem
I will get $$g(b)-g(a)=0$$
because it is known the derivative equals zero, If I do derivative on $g(x)$, I will get:
$$g'(x)=f'(x)$$ $$g'(x)=0$$ Thus $$g(b)=g(a)$$
Then I just use the value $a$ and $b$ and do: $$g(b)=f(b)-k$$ $$g(a)=f(a)-k$$ and get $$f(b)=f(a)$$ and that's it
Sorry for the bad english... my english is not that great, I hope it will be forgiven :(
Answer: Try starting here instead of defining an auxiliary function. Suppose $a\leq x\leq b$. By the mean value theorem there is a $c_x\in [a,x]$ such that $f'(c_x) = \frac{f(x)-f(a)}{x-a}$.
Comment: The method behind the proof is the same. You just introduced a few extra steps, by introducing an auxiliary function. However, you only so far proved $f(b)=f(a)$.
Comment: Hi, thanks for the comment, actually the question I asked, the solution you gave , is the same solution they did :)
but I wanted to know if my answer is good, because I did not think of it at the beginning. only after I saw the video ( answer ), I realized how easy the question is.
But basically, is it good? my answer? even if it got a little complicated hehe
Comment: Yea, by proving $f(b)=f(a)$ I proved its constant. for every x inside the function, it is equals, i showed that between two different $x$'s, which are different and is parameter like, it is equal, so it doesnt matter which x I choose, its constant. every $f(x)$ is the same.
Comment: To the man who disliked this post, thank you very much, just so you know, you are helping people move away from this forum by doing this... you are making people not ask questions, they try hard to ask using latex and their english, although their english is bad and you still dislike... thank you very much ( didnt talk to you Doge chan, sorry it was on your message ).