Resolving smart pointer circular references without using weak pointers

Question: Suppose we have a design where a collection of objects have a possibly reciprocating dependency on other objects within the collection:
struct Object
{
  ...
  virtual void method();
private:
  std::vector<std::shared_ptr<Object>> siblings;
};

Circular references are allowed to occur (and do not represent degenerate cases). Normally, circular references would be resolved by weak pointers, but this requires a hierarchical concept of ownership, which doesn't apply in the scenario where all objects are equal peers.
How do we fix the problem of circular references without using weak pointers? Is there a design pattern for this and/or are there specialised garbage collection libraries that could be applied? ("Specialised" in the sense of not being conservative garbage collectors that scan the entire memory space for roots, such as the Boehm GC, but rather, provide an API that limits the scope of operation to just the objects of interest and provides the means of explicitly annotating/enumerating roots in the managed objects.)
Of course, I respect that the ideal solution is to avoid designs where mutual dependencies occur, but for the purposes of the current question, please work with the constraint that a mutual dependency design cannot be avoided. By way of motivating example, consider a recurrent neural network where each neuron is represented as an object that explicitly stores references to its connected neurons.
I've tagged the question C++, but language-agnostic answers are also welcomed.
Comment: The design of `weak_ptr` prevents an object from being deleted while in use, because you must convert the `weak_ptr` to a `shared_ptr` while you are accessing it.
Comment: Ah, no, I meant that an object can be deleted while one or more other objects refer to it with weak pointers, i.e., while these objects are "using" it. I confer I'm probably misusing "use" in this context; editing to correct...
Comment: "_Normally, circular references would be resolved by weak pointers_" As a rule: no. **Weak references are absolutely not designed to break cycles.** Just disregard the advice of anyone who tells you that crap. Any ownership cycle can only be "broken" by a different design w/o that problematic cycle. But you can make designs w/o an ownership cycle because you have weak references that are non owning by definition. It's always a design issue. If you have ownership cycle, you can't have smart ptr semantics: by definition they can't possibly handle cycle, not even in theory.
Comment: Agreed: smart pointers do not work with circular references (hence asking the question), but what _does_? Circular references certainly have a valid place in some designs and are handled without drama in garbage collected languages, so what do we do in languages without a GC? Certainly, reinventing an application-specific, ad-hoc garbage collector is not a solution, and neither is considering circular references a design deficiency: for some problems, they are elegant and natural solutions. So, agree that smart pointers aren't the solution, but what _is_?
Answer: In certain circumstances where we can manage Object instances as a group, the aliasing constructor of std::shared_ptr provides a partial solution to the problem. I don't consider this a proper solution, but I'm posting it in hope of spurring further discussion. Instead of using a completely generic formularisation, I'll describe the solution in the context of the proposed use-case of an artificial neural network.
Problem
We have a Neuron class where each instance references other neurons in a possibly reciprocating relationship (i.e., circular references are expected to occur).
struct Neuron {
  std::shared_ptr<Neuron> inputs, outputs;
};

We want automatic memory management of Neuron instances so that for as long as we hold a smart pointer to a Neuron, we can be sure that all its dependencies remain active (i.e., not expired).
Partial Solution
It's natural to group neurons into networks, and so we can introduce a Network class, which is a container that manages and owns a collection of Neuron instances:
class Network : public std::enable_shared_from_this<Network> {
  std::vector<Neuron> neurons;

public:
  static std::shared_ptr<Network> createNetwork();
  std::shared_ptr<Neuron> getNeuron(size_t indx);
};

The API allows the client to get individual Neuron instances as shared pointers. While the client holds such a pointer, it should not matter if the Network itself has gone out of scope; all dependencies of the referenced Neuron should still remain active:
std::shared_ptr<Neuron> neuron;
{
  auto network = Network::createNetwork();
  neuron = network.getNeuron(0);
}
neuron.inputs[0]; // <-- alive and well despite the
                  //     {network} smart pointer
                  //     having been destructed.

For this, we can use the aliasing constructor of std::shared_ptr:
std::shared_ptr<Neuron> Network::getNeuron(size_t const indx) {
  return std::shared_ptr<Neuron>(shared_from_this(), &neurons[indx]);
}

Analysis
The above solution gives us the following:

Clients get normal std::shared_ptr semantics for individually held Neuron instances.
Clients do not need to worry about what happens when their Network container goes out of scope.
Circular references within Neuron instances are allowed and do not interfere with memory management.

However, it has the following limitations, which makes it at best a partial solution, and possibly not a solution at all:

Requires management to be performed by some container class with ownership semantics.
Does not support multiple containers co-owning objects (i.e., a Neuron can only belong to a single Network).

Still very much looking for better answers, but in the mean time, hope this might be of curiosity to some passing soul.
Answer: One solution is to have a member of each type that releases whatever references are held.
struct type1
{
  std::shared_ptr<struct type2> ptr;
  void reset() { ptr.reset(); }
};
struct type2
{
  std::shared_ptr<type1> ptr;
  type2(std::shared_ptr<type1> & ptr) : ptr{ptr} {}
  void reset() { ptr.reset(); }
};

It can't be automatic like proper RAII (in that an additional step is needed and not just relying on destructors) but so long as you follow the contract it will keep the object(s) alive so long as they need to be then release them afterward. Depending on exact usage it may also be necessary to move to two-stage initialization (that is, for example with a type1 object, create the object, assign it to a shared_ptr and only then create the type2 object).
Although if that is your pattern you can also very often move to simply having type2 store a raw pointer and not have it worry about the owning object's lifetime at all. With circular chains like this somewhere there has to be an external reference and that is the proper place to start unwinding.
Comment: Thanks for the solution. So when our `Object` type only has a single possibly-reciprocating dependency, we can create a proxy type that is essentially a pair holding shared pointers to the object and its dependency, thereby ensuring that so long as this proxy never gets destroyed, the Object's dependency will never expire (we can use RAII for this). However, so far as I can work out, this type of solution doesn't work for when objects have a variable number of dependencies. Is this consistent with your thinking?
Comment: Actually, no. . shared_ptr has a rather odd alias ability that allows you to have say a shared_ptr that actually manipulates the lifetime of a shared_ptr. So you could then have a vector> of such alias instances. Note that this would not help you with the problem of getting actual objects (the type1*) but _would_ allow you to collect references to all the objects you want to keep alive in one place.
Comment: I can certainly imagine creating a bin where we aggregate shared pointers so that their respective objects don't go out of scope, but I can't imagine how we can do so in such a way that preserves automatic RAII-style memory management. So far as I can see, we would need to periodically traverse our object network to see which objects are still reachable, i.e., rolling our own garbage collector.


Explain why this relation has a reflexive, symmetric, antisymmetric, and transitive propery

Question: Let S = {1, 2, 3}
Let R = {(1,1),(3,3),(2,2)}
So the answer is that it is reflexive, symmetric, antisymmetric, and transitive. I understand that it is reflexive, however I do not understand how it could be symmetric, antisymmetric, and transitive.
Can anyone explain why it would have the 3 other properties?
Thank you.
Comment: Did you try to use the definitions? If you did, where did you stuck?
Answer: $R$ is symmetric if $\langle x,y\rangle\in R$ implies that $\langle y,x\rangle\in R$. Pick any member of $R$ to be $\langle x,y\rangle$, say $\langle 2,2\rangle$; then $x=2$ and $y=2$, so $\langle y,x\rangle=\langle 2,2\rangle$, and the reversed pair is identical to the original one and is therefore in $R$ as well. Since all of the pairs in $R$ have both components equal, the same thing happens with each of them: the reversed pair is still in $R$, because it's the same as the original pair. Thus, $R$ is symmetric.
$R$ is antisymmetric if the following is true: whenever $\langle x,y\rangle$ and $\langle y,x\rangle$ both belong to $R$, then $x=y$. For what values of $x$ and $y$ is it true that $\langle x,y\rangle$ and $\langle y,x\rangle$ both belong to this relation $R$? The only time we have $\langle x,y\rangle\in R$ is when $x=y$; in that case certainly both $\langle x,y\rangle$ and $\langle y,x\rangle$ are in $R$, since they're the same pair, and it is indeed true that $x=y$, as required for antisymmetry. Thus, $R$ is antisymmetric.
Transitivity is similar. Transitivity of $R$ requires that whenever $\langle x,y\rangle$ and $\langle y,z\rangle$ both belong to $R$, then so does $\langle x,z\rangle$. For this particular relation $R$ the only time $\langle x,y\rangle$ belongs to $R$ is when $x=y$, and the only time $\langle y,z\rangle$ belongs to $R$ is when $y=z$, so the only time $\langle x,y\rangle$ and $\langle y,z\rangle$ both belong to $R$ is when $x=y=z$. But in that case $\langle x,z\rangle\in R$, so the requirement for transitivity is met.


Do I have to exit ssh and perform 'vagrant reload' to see the changes I've made in my project's views files?

Question: I'm using CentOS 7 with Vagrant to work on my rails application and I was under the impression that I could just CTRL + c to restart my rails server and see any changes I've made to the view, but it looks like I have to exit the vm and 'vagrant reload' every time I make a change. Am I understanding this correctly, is this what I have to do each time I make a change in order for it to apply? Shouldn't I only have to restart the rails server each time I make a change?
This is how my Vagrant file is currently set up:
config.vm.box = "centos/7"
  config.vm.network "forwarded_port", guest: 3000, host: 3000
  config.vm.provision :shell, path: "bootstrap.sh", privileged: false
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "2048"]
    vb.customize ["modifyvm", :id, "--cpus", "2"]
    vb.customize ["guestproperty", "set", :id, "--timesync-threshold", 5000]
  end
end

Answer: This VM has the shared folder setup to run as rsync mode, you can review that from the Vagrantfile box file:
Vagrant.configure("2") do |config|
  config.vm.base_mac = "5254001fdbb7"
  config.vm.synced_folder ".", "/vagrant", type: "rsync"
end

You can learn more about vagrant and rsync by reading the doc https://www.vagrantup.com/docs/synced-folders/rsync.html.
Vagrant has a command line https://www.vagrantup.com/docs/cli/rsync-auto.html so you can run vagrant rsync-auto and the changes will be in sync from the host to the VM
Comment: this was exactly what I've been looking for, thank you!


Errors when trying to apply transform to search results

Question: Edit: I did some more debugging and that error is actually thrown when I am trying to install the transform, not use it. However, when I search though my DB I can find the script there.
I am using the Java API and Marklogic version 8.
I wrote an xquery transform to modify documents when they are retrieved by a search. I wrote it up in the query console, verified that it did what I wanted it to, but now that I have it in a file and am trying to use it in my application I get the following error:

Server Message: RESTAPI-INVALIDCONTENT: (err:FOER0000) Invalid content: invalid xml_to_string extension: xml_to_string either is not a valid module or does not provide extension functions (transform) in the http://marklogic.com/rest-api/transform/xml_to_string namespace

I followed the documentation pretty close to verbatim on how to install and use a transform, so i'm not really sure where the problem lies except for maybe in the script itself.  The code is as follows:
<code>xquery version "1.0-ml";
module namespace xmlTrans =
  "http://marklogic.com/rest-api/transform/xml_to_string";

declare function xmlTrans:xmlToString(
  $context as map:map,
  $params as map:map,
  $fullDoc as document-node()
) as document-node()
{
  if(fn:empty($fullDoc/*)) then $fullDoc
  else (
    let $root  := $fullDoc/*
    let $contentArray := $root/contents
    return document
    {
      element {fn:name($root)}
      {
        $root/@*, $root/element()[fn:not(fn:name(.) eq "contents")],
        element contents
        {
          for $contentEle in $contentArray/content

          return(
            if($contentEle/@type = "paragraph") then (<content type="paragraph"><paragraph>{xdmp:quote($contentEle/paragraph/*)}</paragraph></content> )
            else ($contentEle)
          )

        }
      }
    }
  )
};
</code>
Is there something wrong in my syntax that is preventing Marklogic from recognizing it as a transform?
Answer: The REST API extensions follow a convention-over-configuration approach.
A transform extension must contain a function named "transform" -- see:
http://docs.marklogic.com/guide/rest-dev/transforms#id_17421
Also, the REST API installs extensions even if it detects errors.
Hoping that clarifies,
Comment: I spent hours in the documentation and on Google and somehow missed that. I want to scream. Thank you!


Can the strict triangle inequality hold in a length space?

Question: Let $(M, d)$ be a metric space where

(0) for relevance: set $M$ contains at least three distinct elements and

distance function $d : M \times M \to \mathbb R$ explicitly satisfies

(1) non-negativity: $d[ \, x, y \, ] \ge 0$ (where $x, y \in M$ are not necessarily distinct),
(2) identity of indiscernibles: $d[ \, x, y \, ] = 0 \, \iff \, x \equiv y$,
(3) symmetry: $d[ \, y, x \, ] = d[ \, x, y \, ]$, and
(4) the general triangle inequality (a.k.a. inclusive subadditivity): $d[ \, x, z \, ] \le d[ \, x, y \, ] + d[ \, y, z \, ]$ for any three (not necessarily all distinct) $x, y, z \in M$.

Now consider the following two additional conditions:

(a) the strict triangle inequality (a.k.a. exclusive subadditivity): $d[ \, x, z \, ] \lt d[ \, x, y \, ] + [ \, y, z \, ] \iff (y \not\equiv x \hbox{ and } y \not\equiv z)$,
which includes the case that $x, y, z$ are all pairwise distinct;
(b) metric space $(M, d)$ is a length space;
which shall be defined here explicitly and suitably generally as follows:
$ \, $
$\forall \, x, z \in M \, | \,  x \not\equiv z : (\exists \, y \in M \, | \, d[ \, x, y \, ] \lt d[ \, x, z \, ] \hbox{ and } d[ \, y, z \, ] \lt d[ \, x, z \, ]) \implies $
$ \, $
$d[ \, x, z \, ] = \text{inf}_{\{\forall \, C \subset M | \, \exists \, q \, \in \, C \, : \, q \not\equiv x \text{ and } q \not\equiv z\}}{\Large[} \, \text{sup}_{\{ n \in \mathbb N \}}{\large[} \, $
${\left\{ \text{inf}_{ \{ \forall \text{ permutations } p \, : n \rightarrow C \} } \!\! \left[ \sum_{k = 1}^n d[ \, p_{(k - 1)}, p_{(k)} \, ] \right] | {x \equiv p_{(0)} \hbox{ and } z \equiv p_{(n)} \hbox{ and } (\forall \, k \le n : p_{(k)} \in C)} \right\}} $
$ \qquad \qquad \qquad \qquad \qquad \qquad \qquad \qquad \qquad \qquad \qquad {\large]} \, {\Large]},$
where the expression part
$ \text{sup}_{\{ n \in \mathbb N \}} \left[ \, {\left\{ \text{inf}_{ \{ \forall \text{ permutations } p \, : n \rightarrow C \} } \!\! \left[ \sum_{k = 1}^n d[ \, p_{(k - 1)}, p_{(k)} \, ] \right] | {x \equiv p_{(0)} \hbox{ and } z \equiv p_{(n)} \hbox{ and } (\forall \, k \le n : p_{(k)} \in C)} \right\}} \right] $
is to be regarded as (general, possibly polygonal) length of chain $C$ between $x$ and $z$.

Surely both these conditions (a) as well as (b) are separately consistent with conditions (0) through (4) stated above, describing a corresponding metric space.
My question:
Are these conditions (a) and (b) consistent with each other?
Or in other words: Can the strict triangle inequality hold in a length space?
Answer: In particular, such a space contains no nonconstant minimizing geodesics. Examples of complete metric spaces without any nonconstant minimizing geodesics  are constructed in this mathoverflow answer. You should check these examples to see if they satisfy your condition (you may have to modify the construction though).
Edit. Here is a construction of what you are asking for. I will leave you to fill in the details.
Definition. A point $m$ in a metric space $(X,d)$ is an $\epsilon$-midpoint between distinct points $x, y\in M$ if
$$
\frac{1}{2} d(x,y)< \min(d(m,x), d(m,y))\le \max( d(m,x), d(m,y) ) < \frac{1}{2} d(x,y) + \epsilon.
$$
Definition. A metric space $(X,d)$ is strict if any triple of distinct points in $X$ satisfies strict triangle inequalities.
Lemma. Given a countable strict metric space $(X,d)$, $\epsilon>0$ and two distinct points $x,y\in M$, there exists a strict metric $d'$ on $X':= X \sqcup \{m\}$ extending the metric $d$ on $X$, such that $m$ is an  $\epsilon$-midpoint between $x, y$.
Now, here is a construction of a (countable) strict length metric space $(X,d)$.
Start with a 2-point set $X_1=\{x,y\}$, $d_1(x,y)=1$. Then, using Lemma, inductively build finite strict metric spaces $(X_n,d_n)$ by adding $\epsilon$-midpoints  (where each $\epsilon$ is of the form $\frac{1}{i}$ for some $i\in {\mathbb N}$), in such a way that for each $n$ and every pair of points $x,y\in X_n$  and every $i\in {\mathbb N}$, there exists $k=k(n,x,y,m)$ such that on the $k$-th stage of the construction, we add to $X_{k}$ an  $\frac{1}{i}$-midpoint between $x$ and $y$. (This requires a certain enumeration of ${\mathbb N}^3$ where the first two coordinates in ${\mathbb N}^3$ represent points in our finite metric spaces and the last coordinate corresponds to the index $i$ as above.)
Lastly, take
$$
X:= \bigcup_{n} X_n
$$
where the metric $d$ on $X$ is defined as the direct limit of the metrics $d_n$,  i.e. it restricts to the metric $d_n$ on $X_n$ for each $n$. Then $(X,d)$ is a strict length metric space.
Note that $(X,d)$ will be incomplete and will not be a path-metric space.
Comment: Moishe Cohen: "_In particular, such a space contains no nonconstant minimizing geodesics._" -- But is such a metric space that you describe even called "length space"?? (And even: what exactly is the definition of "_nonconstant minimizing geodesic_" in suitable generality?) "_Examples [...] are constructed in this mathoverflow answer. You should check these_" -- Too bad I got, for all intents and purposes, kicked out off mathoverflow; due to having asked questions pretty much like the one above ... (Still: +1 for your interest and effort.)
Comment: @user12262: Yes, it is a length space (in the standard sense), which is what makes this example so amazing! I do not have much time to think about this, but read the example and see if it satisfies the stronger property you are asking.
Comment: Moishe Cohen: Well, I see that [the question there](https://mathoverflow.net/q/15592) relates to mine here, but doesn't quite match it: A space 'with intrinsic metric' (as defined there) is indeed an example of a length space; but in turn: a space satisfying the strict triangle inequality (of my definition) surely is an example of a space which 'has no nontrivial min.zing geodesics.' So the example given over there doesn't necessarily make an affirmative answer here quite yet. Moreover, I'm stymied by its jargon or assumptions: '$c_0$'? 'distance element $\|dx\|_{\infty}$'? '$m$-th position'??


Finding an endomorphism (having trouble converting between bases).

Question: I've been trying to solve an exercise about finding an endomorphism ($f:\mathbb{R}^2\rightarrow\mathbb{R}^2$) so that $f(2,5)=(1,3)$ and $f(1,3)=(1,-1)$. So my steps have been the following:

First, we have two bases: the canonic base of $\mathbb{R}^2$ and another base which which we shall call $\bar{B}=\{(2,5),(1,3)\}$.
Then, we know that for an equation $Y=CX$, $C$ would be the matrix associated with $f$ with bases $\bar{B}$ and $B$.

Then I didn't know how to proceed, so I looked it up in my textbook and it uses this figure:

And it says that, in order to find the matrix $A$ (which would be the matrix associated with our endomorphism using the canonical base only), one has to know that $A=CP^{-1}$. My book uses similar diagrams sometimes and I think I don't understand them, because I don't understand how they arrived at that formula. Why $A=CP^{-1}$ and not $A=P^{-1}C$? There's not constrain when it comes to the dimensions of the matrices because they're all square matrices, so the order of the factors must come from somewhere.
Thanks everyone in advance!
Answer: Note that you are looking for a matrix $A$ such that:
$$A\begin{bmatrix}2&1\\5&3\end{bmatrix}=\begin{bmatrix}1&1\\3&-1\end{bmatrix}$$
where the columns of $\left[\begin{smallmatrix}2&1\\5&3\end{smallmatrix}\right]$ are the domain vectors $(2,5)$ and $(1,3)$, while the columns of $\left[\begin{smallmatrix}1&1\\3&-1\end{smallmatrix}\right]$ are the image vectors $(1,3)$ and $(1,-1)$.
Thus the required matrix $A$ is obtained with right multiplication by the inverse of $\left[\begin{smallmatrix}2&1\\5&3\end{smallmatrix}\right]$, thus giving:
$$A=\begin{bmatrix}1&1\\3&-1\end{bmatrix}\begin{bmatrix}2&1\\5&3\end{bmatrix}^{-1}$$
as you can verify by direct computation:
\begin{align}
\begin{bmatrix}1&1\\3&-1\end{bmatrix}\begin{bmatrix}2&1\\5&3\end{bmatrix}^{-1}\begin{bmatrix}2\\5\end{bmatrix}
&=\begin{bmatrix}1&1\\3&-1\end{bmatrix}\begin{bmatrix}1\\0\end{bmatrix}\\
&=\begin{bmatrix}1\\3\end{bmatrix}
\end{align}
and similarly,
\begin{align}
\begin{bmatrix}1&1\\3&-1\end{bmatrix}\begin{bmatrix}2&1\\5&3\end{bmatrix}^{-1}\begin{bmatrix}1\\3\end{bmatrix}
&=\begin{bmatrix}1&1\\3&-1\end{bmatrix}\begin{bmatrix}0\\1\end{bmatrix}\\
&=\begin{bmatrix}1\\-1\end{bmatrix}
\end{align}
as required.
Comment: Okay, I appreciate the effort in giving me the answer, but I need to know how you got there instead of copying it. I just see matrices but I don't understand how you were able to decide the order (since just tring everything until something works isn't an option).
Comment: I add some details in the answer.
Comment: Okat, it's clearer now. Thanks for the effort and the answer :)
Answer: This all seems very complicated.
Conversely, there is a map that sends the standard basis to $(2,5),(1,3)$. The matrix form of this is $$P:=\begin{pmatrix}2&1\\5&3 \end{pmatrix}$$  Then, $P^{-1}$ will send these back to the standard basis.  You want to find a matrix $A$ that sends $(1,0),(0,1)$ to $(1,3),(1,-1)$. Then the composition, will first send us back to standard basis, and we know how to write a matri that sends everything to the correct vectors. So, first put the matrix back into standard basis with $P^{-1}$, and then send standdard vectors to the vectors in question.
In other words, $A:=\begin{pmatrix}1&1\\3&-1 \end{pmatrix}P^{-1}$
Comment: Even though Fabio's answer is more detailed, I like this explanation because it all made sense in my head as I read it. I've solved the exercise now, everything feels a lot easier now that I understand the train of thought necessary to solve these problems. Thanks!
Comment: Well, Im glad that I could help :)
Comment: There is a sentence at the beginning of Paul Halmos' book "I want to be a mathematician." The first sentence is "I've always liked words more than numbers..." I believe. I subscribe to this philosophy. If there is a place where formulae can be replaced with a sentence or two (without sacrificing anything) then I prefer it


Reconstruct an array of objects in javascript that contains nested arrays

Question: I'm struggling of coping with an issue here.
lets suppose I have an array of objects like this:
[
 {name:Alex, products: [{type: 1, code: 1213}, {type: 2, code: 2312}]},
 {name:Alex, products: [{type: 1, code: 1213}, {type: 2, code: 2312}]}
]

I would like somehow to reconstruct my object to be something like this:
[
 {name:Alex, products: [{name:Alex, type: 1, code: 1213}, {name:Alex, type: 2, code: 2312}]},
 {name:Alex, products: [{{name:Alex, type: 1, code: 1213}, {{name:Alex, type: 2, code: 2312}]}
]

so each nested array contains the name. Is that possible in javascript?
Comment: See below for spoon feeding, where you get to brush up on your copy/paste skills.  Alternatively, look __[here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)__ and learn how to do it :)
Comment: `Is it possible in javascript?`  Yes.
Comment: Could you so me the way to do this?
Answer:
I want somehow to reconstruct my object so as to be something like
  this:

Use map
arr.map( s => (s.products.map( i => (i.name = s.name, i) ), s) );

Demo

var arr = [{
    name: "Alex",
    products: [{
      type: 1,
      code: 1213
    }, {
      type: 2,
      code: 2312
    }]
  },
  {
    name: "Alex",
    products: [{
      type: 1,
      code: 1213
    }, {
      type: 2,
      code: 2312
    }]
  }
]
var output = arr.map(s => (s.products.map(i => (i.name = s.name, i)), s));

console.log(output);
Comment: Interestingly this is the only correct answer, as rightly you have noticed the word `reconstruct`, all other answer are assuming the OP wanted copy.
Answer: You could create new array/objects with Object.assign.

var data = [{ name: 'Alex', products: [{ type: 1, code: 1213 }, { type: 2, code: 2312 }] }, { name: 'Alex', products: [{ type: 1, code: 1213 }, { type: 2, code: 2312 }] }],
    converted = data.map(o => Object.assign(
        {},
        o,
        { products: o.products.map(p => Object.assign({ name: o.name }, p)) }
    ));

console.log(converted);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: You can use nested Array.map() calls with Object.assign() to create the new array without changing the original data:

const data = [{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]},{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]}]

const result = data.map((o) => Object.assign({}, o, {
  products: o.products.map((p) => Object.assign({ name: o.name }, p))
}))

console.log(result)

If you just want to change (mutate) the current array, use nested Array.forEach() calls:

const data = [{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]},{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]}]

data.forEach((o) => o.products.forEach((p) => p.name = o.name));

console.log(data)
Answer: You can use map() method with spread syntax in object to create new array with updated objects and keep original data.

const data = [
 {name:'Alex', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]},
 {name:'Alex', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]}
]

const result = data.map(e => ({
  ...e,
  products: e.products.map(p => {
    return {...p, name: e.name}
  })
}))

console.log(result)
Answer: You have typo in name property.Alex should be 'Alex' (string).You can get help from two array methods. Array.prototype.map() and Array.prototype.forEach() to achieve your goal
var initialArr = [
 {name:'Alex1', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]},
 {name:'Alex2', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]}
]

var newArr = initialArr.map(function(elem){
    elem.products.forEach(function(obj){
        obj.name = this.name
    },elem)
    return elem
})
console.log(newArr)


How can I programmatically delete a custom menu?

Question: I'm writing a hook_deploy_N that moves a bunch of menu items from a deprecated custom menu to some newer ones. So far, so good. After moving the items, I want to delete the old menu, but can't figure out how. \Drupal\Core\Menu\MenuTreeStorage has a delete function that may be  what I'm looking for, but the \Drupal\Core\Menu\MenuTreeStorage object is housed inside the \Drupal\Core\Menu\MenuLinkTree, which I can at least load, but has protected status, and I don't see a way to get to it. Plus, I'm not not 100% convinced that's what I want any way.
Answer: Since menus are configuration items, my poking into \Drupal\Core\Menu\MenuTreeStorage::delete() was wrong. You delete a custom menu thusly:
\Drupal::configFactory()->getEditable('system.menu.name-of-custom-menu')->delete();

Note that I'm assuming the menu is empty. I don't know what would happen if you deleted a menu that had menu items in it, whether they'd be orphaned or deleted.


Google DFP ads in email behaving strangely

Question: I am trying out serving DFP ads in email. I'm following the guidelines here.

I have an ad unit set up just for email
I have a line item targeting that ad unit with just an image creative
The line item doesn't have any targeting restrictions or anything like that

The ad will show up in the email, at least the first time. The strange thing that I'm seeing is, after the first click, clicking on the ad again will often bring me to a blank page rather than the click-through page of the creative. Also, when I reopen the message, occasionally the image will not load. The code in the email looks like this:

Comment: @slead I don't have an updated link. It's been a long time, but I think the original article I linked to was longer and more involved than the link you posted.
Comment: +1 for the link to "Serve ads in a non-JavaScript environment". It would have been nice for google to include that link in the "Serve creatives in an email or newsletter" article.
Comment: The link in your first line is no longer available - do you have an updated URL (was it [Serving creatives in an email or newsletter](https://support.google.com/dfp_premium/answer/1258792?hl=en)?
Answer: We've solved this by turning off cookies in the standard tag using the co= option; adding co=1 to the tag.

The only problem (for us) that this creates is that we're unable to serve 3rd party tags, even ones that resolve directly to .gifs, using the standard tag.
Comment: We serve 3rd party tags on the site only. For email newsletters we require image and clickthru href's only.
Comment: I haven't tested those specific scenarios but the co option essentially turns off cookies, so DFP isn't depending on them. So there's no reason it wouldn't work in those environments.
Comment: I haven't verified this, but according to the docs it should work. I don't think this was around when I asked the original question. Marking as accepted since it looks like this is the best option.
Comment: @scoopseven so do you cut 3rd party tags entirely or what is the solution there?
Comment: Does the clickthrough work in email clients that don't support cookies such as Outlook with a default browser that isn't IE, such as chrome or firefox?
Comment: I've created test code that generate random links. With co=1 it works fine. See code details in http://rextester.com/TBAKX36405
Answer: Had the same problem and I solved it by using script to redirect click via script on my web server where ad is shown again so that all the cookies can be set.
Link looks like this:
http://www.mysite.com/dfpclick.php?adunit=mailing&cbuster=1369608725
Script dfpclick.php:
<?php
/* Google DFP url redirect*/
if ($_REQUEST['adunit']) {
    $sUrl = 'http://pubads.g.doubleclick.net/gampad/jump?iu=/%mygoogleid%/'.$_REQUEST['adunit'].'&sz=1x1&c='.$_REQUEST['cbuster'];
}
?>

<meta HTTP-EQUIV="REFRESH" content="0; url=<?=$sUrl?>">

<?php
if ($_REQUEST['adunit']) {
    echo '';

}

?>

Comment: So I have encountered this issue, the redirect responds with the dreaded 204 response, UNLESS the image is sized appropriately. In my case 728x90. Any other size and Google returns the 204, but inconsistently. Sometimes it works and it varies from browser to browser.
Also it looks like Chrome is STRICT when it comes to meta refresh. Tjis is what worked on Chrome in PC (worked regardless on Mac)
Comment: This looks interesting, thanks for sharing.  Did you notice if this cause double impression counts?  It seems like that might be a risk, but since the cbuster is identical it should not double count.  I'm thinking I might introduce a slight delay to ensure the image loads first, or better yet wait for the image load via javascript before redirecting to the target.
Comment: I'm sorry to say this does not appear to work in my testing.  DFP may pull a different ad for the webserver-based request, resulting in a different click-through target.  Sadness.
Comment: To Julian: I tested this script and at least so far I get realistic number of impressions. How did you set your campaign? I usually use Sponsorship and have only one ad to ensure that the ad is always shown.
Comment: Right, if it's always the same ad being delivered, it should be OK, but if ads are rotated in a normal way, there is no connection between the ad the user sees initially and the one loaded by the website once they click through.
Comment: @besimple thanks very much for posting this. I'm finding that it works most of the time, for most users - but sometimes freezes without redirecting to the DfP URL. It may be related to ad-blockers? Is `meta HTTP-EQUIV="REFRESH"` still valid on all browsers?
Comment: I think I've narrowed the problem down to users running AdBlock, which prevents the redirect. [This page](http://thepcspy.com/read/how_to_block_adblock/) gave tips on detecting AdBlock, in which case I display a message to the user.
Answer: It turns out that DFP for small business requires cookie support to work, even when using the non-JavaScript method of calling ads. So it works fine in web-based clients like Gmail, but it doesn't work in Outlook and the like. DFP Premium can supposedly serve ads in email without requiring cookies.
Answer: Using the co= option doesn't work for DFP Small Business. My workaround is:
Use the same code for img
And build a redirect link on your website . This page reads and filters the response from http://pubads.g.doubleclick.net/gampad/adx?iu=/{my_pub_id}/300x250_email&sz=300x250&c={cachebuster} in order to get the click-tracking link using javascript link=$(xmlDoc).find('a').attr('href'); and redirect.
This workaround doesn't work for rotation (more than one creative/line item is competing for the same ad unit at the same time).
I'd like to know how to serve email ads in rotation using DFP SB


Write all PHP errors, warnings and notices to error_log

Question: Drupal catches PHP warnings and notices to log them via dblog or syslog. As a result, there are two places to monitor for PHP errors (with the watchdog UI not well suited to cater for any large number of notices).
Is it possible to prevent this behavior and have ALL php errors be logged to the error_log defined in the php config?
Comment: If the syslog module (in core) is working as expected, you should be able to disable the dblog module (also core). That will remove the watchdog UI page as well.
Comment: Thank you, but my question is neither aimed at disabling watchdog completely nor using syslog.
Answer: For that, you will need to implement the hook_watchdog to make calls to the error_log() function.
You could as example one of the places where is implemented, that is the syslog_watchdog. Instead of use the openlog() and syslog() function, you will use the error_log().
Comment: While this does not prevent PHP warnings and notices from being passed to dblog/watchdog, it makes possible the passing of php related entries to the default error_log. Thanks!
Answer: Rudimentary code example for the solution provided by @gerzenstl
<code>/**
 * Implements hook_watchdog()
 */
function MYMODULE_watchdog(array $log_entry) {

  if($log_entry['type'] == 'php') {

    $output = format_string($log_entry['message'], $log_entry['variables']);
    $output =  strip_tags($output);
    error_log($output);

  }

}
</code>
Answer: Got here when googling for the same. I want watchdogs go to webserver logging, since I use Docker. After checking @gerzenstl links, I tried again looking if someone already coded it and finally found a module:
https://www.drupal.org/project/logging_alerts
The 'errorlog' submodule does exactly this. Overall, all the modules are very complete and provide other useful goodies. Solved this without coding!


Incorrect syntax near 'sp_executesql'

Question: I don't understand why the following is giving me the error.  I thought it was related to the commented out section, but @SQL is nvarchar(4000).
BEGIN
  sp_executesql N'SELECT ''td'''
  --sp_executesql @SQL, N'@StartDate DateTime, @EndDate DateTime, @End2 DateTime, @Program varchar(4)', @StartDate, @EndDate, @End2, @Program
END

Answer: This is why:

-- This works just fine:
BEGIN
  -- You must have an exec before your sp_executesql or it will not work in a block
  exec sp_executesql N'SELECT ''td'''
END

You can't just call a stored proc without an exec when you are in a block.
Comment: You can call a stored proc without and exec, but only when the call to the stored proc is the only statement in the block.
Comment: it has to be the First statement, not necessarily the only one.
Answer: Why do you have this enclosed in a BEGIN ... END? Running the sp_executesql external the block will work.
Optionally you can put an exec before sp_executesql.
Answer: On some occasions I had to use master as well:
exec master..sp_executesql

Incorrect syntax near 'sp_executesql'


Installing software on Linux without root privileges

Question: At my workplace I have a regular user account on RedHat and Suse machines. I don't have root privileges.
How can I install software that I download from the internet (from sources or binaries)?
For example, now I want to install the Geany IDE for my own use. I tried to download sources and compile, and I tried to install the RPM, but non of of these works because it requires the root.
Comment: Do you require root because of destination permissions (don't have access to /etc, /bin, /sbin etc) or because rpm/gcc has restricted permissions?
Answer: You can install software into your own home directory.  If you're comfortable compiling from source, and the package uses automake, then you can use the following option on configure:
<code>--prefix=$HOME/install
</code>
or whatever.  Similarly, rpm has a prefix option as well.  However, this only works if the rpm was built to be relocatable.
Answer: I use JuJu which basically allows to have a really tiny linux distribution (containing just the package manager) inside your $HOME/.juju directory.
It allows to have your custom system inside the home directory accessible via proot and, therefore, you can install any packages without root privileges. It will run properly to all the major linux distributions, the only limitation is that JuJu can run on linux kernel with minimum reccomended version 2.6.32.
For instance, after installed JuJu to install pip just type the following:
<code>$>juju -f
(juju)$> pacman -S python-pip
(juju)> pip
</code>
Answer: Most of the time you can pass PREFIX to configure to install it into your home directory:
<code>./configure --prefix=/home/ioks/bin
</code>
This might get around the permissions issues.
Answer: Here's a very nice doc explaining non-root use of RPM:
"You've been told that working with RPMs needs system administrator privileges? You've been misled."
http://www.nordugrid.org/documents/rpm_for_everybody.html
Answer: If you want to install it in the standard place (/usr/bin, etc), the short answer is that you won't unless the sys admin sets up something special to allow you to do it.
If you are compiling from source, most packages have a --prefix option that will allow you to set a non-standard install target.  That allows you to install stuff in your home directory, including libraries that you can use for other software packages.
Answer: Hmmm.  Not that this is likely something a user could do, but I wonder if it might make sense for there to be per-user "overlay" filesystems (union-fs, etc) that overlay the "standard" system install directories, and so allow unprivileged users to install software in the 'normal' places.
You could also use a global union-fs filesystem to separate admin-installed non-standard SW (which often goes in /usr/local/* on many systems) from distribution packages.  (Perhaps also to separate updates as well, and even allow for "roll-back" ala XP System Restore).
Hmmm
Answer: I'm having the same problem as you. I haven't tried it yet but it seems that Linuxbrew can be handy on this issue.


"Use of unresolved identifier" using the new Swift 2.2 syntax for selectors on implicit setter

Question: Migrating my code to Swift 2.2, I have a property var activeTextField:UITextfield? and the selector I was using was "setActiveTextField:". This method does not exist explicitly in my swift code.
With the new syntax, #selector(setActiveTextField) doesn't work: Use of unresolved identifier
I know I could use Selector("setActiveTextField:") but I'd loose the benefit of the new swift selectors.
So, what's the new way of doing this?
Comment: He probably has to use "#selector(setActiveTextField(_:))". Using my phone so I can't format the code properly.
Comment: I have no method setActiveTextField, it's the implicit obj-c setter.
Comment: Thanks for the suggestion but since it's an implicit obj-c setter, it actually doesn't exist in swift.
Comment: Doesn't the compiler suggest the proper syntax?
Comment: He suggest `Selector("setActiveTextField:")`
Answer: The issue here is that you're working with a property, not a method. This has two problems:

The ObjC setter/getter method pair for a property is generated at run time.
The #selector expression requires a Swift function/method reference.

When Swift compiles your source, it doesn't know that the ObjC -(UITextField*)activeTextField and -(void)setActiveTextField:(UITextField*)field methods will exist, so it can't generate function references for them. Since it can't generate a function reference, it doesn't have something it can use for the #selector expression.
For now, there isn't a way to use #selector to access property getters/setters — using Selector(...) with a string constant is your only option.
(This is actually just a new face on a longstanding known issue... it's the same reason you also can't pass a property getter/setter to something like map or filter. I think I've seen something on http://bugs.swift.org about this, but I'm not finding it at the moment.)
Comment: I posted a bug on the jira (SR-1029), someone answered that there was a discussion on going on swift-evolution to provide a synthax for refering to setters & getters. So it's seems that i'll have to stick with `Selector()` for now .
Answer: In Swift 3, SE-0064 was accepted to solve this problem. Now, you would generate that setter like so:
#selector(setter: activeTextField)


Compute the fundamental group of a five - pointed star ( boundary plus interior )

Question: Compute the fundamental group of a five-pointed star ( boundary plus interior ).
Knowing that I have taken only chapter 1 & 2 of " introduction to knot theory " of Richard H. Crowell and Ralph H. Fox.
Which includes the fundamental group of the circle but does not include van Kampen theorem.
Could anyone give me a hint for the solution, please?
Comment: Perhaps a picture would help.  Isn't the region you describe contractible?
Comment: If you choose the center of your five-pointed star as base point for your fundamental group, you can shrink any closed path to the constant path by scaling. This is because the star is star-shaped around the center.
Answer: Say that $\Omega \subset \Bbb R^n$ is star-shaped if there is $p \in \Omega$ with the following property : for all $ q \in \Omega$, the segment $[p,q] \subset \Omega$.
We know that

If $\Omega$ is star-shaped, then $\Omega$ is contractible, that is homotopy equivalent to a point. In particular, $\Omega$ is connected and simply-connected.

For proof of this statement see Lemma 2.11 and Theorem 3.4 here
Now we have that:

A topological space X is simply connected if and only if X is path-connected and the fundamental group of X at each point is trivial.

Por proof of this see Theorem 2.3 here
Therefore for a star shaped region, the fundamental group is trivial.
As you asked for a hint I would try prove these claims without clicking the links first.


How to change a value while dropping?

Question: I'm currently trying to understand how drop works. The following code crashes and I don't understand why. From my understanding, the usage of std::ptr::write should prevent the destructor (edit: of the original value, here: Rc) from running (in this case nothing bad should happen beside the memory leak). But it doesn't seem to do that as (playpen, compile with -O0)
use std::rc::Rc;
use std::mem;
use std::ptr;

enum Foo {
    Bar(Rc<usize>),
    Baz
}
use Foo::*;

impl Drop for Foo {
    fn drop(&mut self) {
        match *self {
            Bar(_) => {
                unsafe { ptr::write(self, Foo::Baz) }
                //unsafe { mem::forget(mem::replace(self, Foo::Baz)) }
            }
            Baz => ()
        }
    }
}

fn main() {
    let _ = Foo::Bar(Rc::new(23));
}

gives an overflow error:
thread '' panicked at 'arithmetic operation overflowed', /Users/rustbuild/src/rust-buildbot/slave/nightly-dist-rustc-mac/build/src/liballoc/rc.rs:755

The other variant quits with an illegal instruction. Why does that happen? How can I replace self with a value that will be properly dropped?
Comment: For my own curiosity — *why* are you trying to do this? It seems a very odd thing to do.
Comment: I'm trying to realize some small vector optimization (`enum SmallVec { Small(u8, [T; SIZE]), Big(Vec) }`). It appears to me, that the only way to safely drop `Small` is to manually drop the occupied entries and then replace it with the `Big` variant in order to be able to forget it.
Comment: Is it the case that your `Small` array doesn't always have `SIZE` entries in it? I'm assuming that's what the `u8` is.
Comment: Exactly. And in case it grows beyond `SIZE` the values are moved into the `Big` variant. I'm doing the same almost the same there (`ptr::read` and `ptr::write`) as in drop and it works.
Answer: I'm not sure yet how to accomplish your goal, but I can show that

From my understanding, the usage of std::ptr::write should prevent the destructor from running

isn't true:
use std::mem;
use std::ptr;

struct Noisy;
impl Drop for Noisy {
    fn drop(&mut self) { println!("Dropping!") }
}

enum Foo {
    Bar(Noisy),
    Baz
}
use Foo::*;

impl Drop for Foo {
    fn drop(&mut self) {
        println!("1");

        match self {
            &mut Bar(_) => {
                println!("2");
                unsafe { ptr::write(self, Foo::Baz) }
                println!("3");
            }
            &mut Baz => {
                println!("4");
            }
        }

        println!("5");
    }
}

fn main() {
    let _ = Foo::Bar(Noisy);
}

This prints:
1
2
3
5
Dropping!

Indicating that the destructor for Foo::Bar is still being run, including the destructor of Noisy.
A potential solution is to use Option::take:
use std::mem;

struct Noisy;
impl Drop for Noisy {
    fn drop(&mut self) { println!("Dropping!") }
}

enum Foo {
    Bar(Option<Noisy>),
    Baz
}

impl Drop for Foo {
    fn drop(&mut self) {
        match *self {
            Foo::Bar(ref mut x) => {
                unsafe { mem::forget(x.take()) }
            }
            Foo::Baz => {}
        }
    }
}

fn main() {
    let _ = Foo::Bar(Some(Noisy));
}

Comment: @Ferio right - but this example shows that the destructor for `Noisy` **is still called**, even though you've replaced `self` with something that doesn't contain a `Noisy`. I'm guessing that the specific destructor is decided *before* the method runs, so you can't modify the variant during `Drop`, as you'd like.
Comment: Sorry, I was unclear and refined my post. My understanding is, that `ptr::write` does simply copy `src` to `dest` without previously calling the destructor in `dst`.
Comment: Indeed, I didn't get your example correctly on the first glance.
Comment: @Ferio that would explain your original error message - the destructor for `Rc` is still being run, but on a chunk of data that doesn't correspond to an `Rc`! It's actually *lucky* that you got a nice error message like overflow, as opposed to silent memory corruption.
Comment: Yes, and by using safe code only (`let _ = mem::replace(self, Foo::Baz);`) I'm getting a stack overflow instead.That should definitively not happen.
Comment: @Ferio I've added a potential solution. Your stack overflow happens because `_` will be a `Foo:Bar`, which will then be immediately dropped. But to drop that, you have to call the `drop` method, which will call `mem::replace`, and so on.
Comment: Oh yes, of course. Thanks for the solution but I'm still wondering whether there is a real problem or just a lack of documentation. What I was trying to do, is very similar to `Option` + `take` so it must be possible somehow.
Comment: @Ferio there certainly could be a bug in that `drop` pre-decides what variant's destructor will be run, regardless of what happens in the method. I'd suggest filing a bug report to see if the core devs agree that it is an issue.

How to change a value while dropping?


what is numeric(18, 0) in sql server 2008 r2

Question: I found a table with this a column from this data type
numeric(18, 0)

what is that please?  and why does 0 and 18 mean
I already check this question Difference between numeric, float and decimal in SQL Server but couldn't understand it.\
can I add (-10) in that column?
can I add all negative number in that column?
can I add any positive number in that column?
Update 1
This is a sample of the data I found in that column
100
263
13
2
9
4
3
3
28
15
33
16
135
50
64
60
100
500
150

Update 2
Is it possible to have - and + ?
Comment: Someone really loves to waste space if that sample is representative of the data
Comment: It is essentially a REALLY big int. Yes you have a negative number. No you can't have any number, it must be no larger than 18 significant digits.
Comment: Here is a link to BOL datatypes. http://msdn.microsoft.com/en-us/library/ms187752.aspx
Comment: @SeanLange you said that `it must be no larger than 18 significant digits` but please check the updated question, there are values less that 18 digits
Comment: @SeanLange that link didn't provide information, are you sure of it please?
Comment: @SeanLange 's comment means that the values can be 18 digits or less, but not more than 18 digits.
Comment: @SpectralGhost kindly tell me what does that mean, specially the 0 and 18 and if it is possible to have `-` and `+`
Comment: @AgnieszkaPolec It means that a smallint would work fine (based on the sample data provided. A smallint stores its value in 2 bytes, a numeric(18,x) stores it in 9 bytes. numeric(18,0) would allow negative #s; the range of data allowed would be - 10^18 +1 through 10^18 - 1
Answer: The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place.  If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
Comment: @AgnieszkaPolec yes you can have negative values. You need to learn about BOL (books online). It is the documentation for sql server. I posted a link the datatypes page earlier. The links from there will take you to the datatype pages for each datatype. It explains them in great detail.
Comment: @SeanLange thanks but I checked that link and browsed to numeric section, it was empty of description. it just has links to decimal and float. Anyway, now I understood the concept of numeric.
Comment: Maybe you looked at the wrong page or something because the numeric page is pretty in depth.  decimal [ (p[ ,s] )] and numeric[ (p[ ,s] )]

    Fixed precision and scale numbers. When maximum precision is used, valid values are from - 10^38 +1 through 10^38 - 1. The ISO synonyms for decimal are dec and dec(p, s). numeric is functionally equivalent to decimal.
p (precision)

    The maximum total number of decimal digits that will be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38....too long to fit here.
Answer: This page explains it pretty well.
As a numeric the allowable range that can be stored in that field is -10^38 +1 to 10^38 - 1.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1) to (10^18 - 1)
Or -999999999999999999 to 999999999999999999 Integers only


cron_last vs node_cron_last variable

Question: I wanted to get the time of last node update (any node). So, then I thought I could simple pick last cron run time ( because I am using feeds module to pull the RSS feeds so nodes will be updated on every cron run ). but then I discovered another variable "node_cron_last".
Can anyone explain me the difference between two variables, what value they contain?
Answer: The only place node_cron_last is set is in _node_index_node(), which is run when indexing a node for search results.
Its purpose, per the comments:

Save the changed time of the most recent indexed node, for the search results half-life calculation.

cron_last is simply used to

Record cron time.

per drupal_cron_run()
Given that REQUEST_TIME is used for all values (cron variables + node changed date) in the same request, you might well expect those two variables to contain the same value.
Comment: I did some trails, it seems like those two contains different values. running Corn updates value of "cron_last" but not "node_cron_last". But it seems like for the node update the "node_cron_last" is getting updated. Thanks you.
Comment: Pretty sure `node_cron_last` will only get updated if there are nodes to be indexed.
Comment: @MPD Definitely; but given the update hook in the search module ([`search_node_update()`](https://api.drupal.org/api/drupal/modules%21search%21search.module/function/search_node_update/7)) I would've thought nodes being updated in the same job would be re-indexed
Comment: @MPD Nope, you're right - the update hooks just queues it for re-indexing, doesn't guarantee it will be in the same job
Comment: @Clive  I am running a news site (pulling rss feeds using feeds module), I wanted to get the time last time the nodes were updated , which variable should be used in this context?

cron_last vs node_cron_last variable


How to change the label of an image's title field in a paragraph

Question: In a paragraph I have an image field for which the title field is enabled and required.
I need to alter the label of this title field to replace "Title" by "Caption"
I tried to use the hook_field_widget_single_element_WIDGET_TYPE_form_alter() to achieve this but all I see related to this title is
$element['subform']['image']['widget'][0]['#title_field'] = (bool) 1
$element['subform']['image']['widget'][0]['#title_field_required'] = (bool) 1

I am wondering how I can alter that label in this paragraph context.
Any help would be appreciated.
Answer: I finally achieved what I wanted doing the following
mymodule/mymodule.module
use Drupal\Core\Form\FormStateInterface;
use Drupal\mymodule\Alter\FieldWidget\BlockImagesParagraph;

/**
 * Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_single_element_entity_reference_paragraphs_form_alter(&$element, FormStateInterface $form_state, $context) {
  if ($element['#paragraph_type'] == 'block_images') {
    \Drupal::service('class_resolver')
      ->getInstanceFromDefinition(BlockImagesParagraph::class)
      ->alterFieldWidget($element, $form_state, $context);
  }
}

mymodule/src/Alter/FieldWidget
namespace Drupal\mymodule\Alter\FieldWidget;

use Drupal\Core\Form\FormStateInterface;

/**
 * Alter block_images paragraph.
 */
final class BlockImagesParagraph {

  /**
   * Alter the field widget.
   *
   * @param array $element
   *   The field widget form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param array $context
   *   An associative array representing the context.
   */
  public function alterFieldWidget(array &$element, FormStateInterface $form_state, array $context) {
    $widget = &$element['subform']['image']['widget'];

    foreach ($widget as $key => &$value) {
      if (!is_int($key)) {
        continue;
      }
      $value['#process'][] = [
        'Drupal\mymodule\Alter\FieldWidget\BlockImagesParagraph',
        'processImageWidget',
      ];
    }
  }

  /**
   * Process the image widget.
   *
   * @param array $element
   *   The field widget form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param array $form
   *   An associative array representing the form.
   */
  public static function processImageWidget(array $element, FormStateInterface $form_state, array $form) {
    if (isset($element['title'])) {
      $element['title']['#title'] = t('Caption');
    }

    return $element;
  }

}


How can I make my code faster? (Copying columns)

Question: I'm new to vba and wrote the code below to match and copy columns; I'm trying to figure out how to make it more efficient as it takes some time to churn out the output. Any advice or feedback would be much appreciated! I thought of switching screen updating to false but it doesn't really speed things up. Could it be slow because I am using the autofilter method of filtering cells? Thank you in advance.
Sub GetItems()
    Dim cel As Range
    Dim celAddress As Range
    Dim n As Integer
    Dim SelRange As Range
    Dim BrandsPasteLoc As Range

    n = 1

    'Application.ScreenUpdating = False

    Worksheets("CA").Activate
    ActiveSheet.Range("$A$1:$L$2622").AutoFilter Field:=10, Criteria1:="<>#N/A",
    Criteria2:="<>0", Operator:=xlFilterValues

    Worksheets("Items to push to CA").Activate

    For Each cel In Range("A1:O1")
        Brand = cel.Value
        If Brand = "" Then
            Resume Next
        End If
        Worksheets("CA").Activate
        Application.Workbooks("Items Suggestion_CA").Worksheets("MY").Range("$A$1:$M$3959").AutoFilter Field:=5, Criteria1:=Brand, Operator:=xlFilterValues

        Range("B:B").Sort _
           Key1:=Range("b1"), Order1:=xlDescending     'sorts on Quantity

        Columns("A:A").Select
        Selection.SpecialCells(xlCellTypeVisible).Select
        Selection.Copy
        Sheets("Items to push to CA").Select
        Set SelRange = ActiveSheet.Columns(n)
        Set BrandsPasteLoc = Range(Range("A1:Z1").Find(Brand).Offset(1), Range("A1:Z1").Find(Brand).Offset(1).End(xlDown))
        BrandsPasteLoc.Select
        ActiveSheet.Paste
        Worksheets("CA").Activate
        n = n + 1
    Next cel

    Worksheets("Items to push to CA").Rows(2).Delete

    Worksheets("Items to push to CA").Activate
    Columns("A:O").Select
    Selection.EntireColumn.AutoFit
    Worksheets("Items to push to CA").Rows(60 & ":" &
    Sheet1.Rows.Count).ClearContents

    Worksheets("CA").Activate
    Cells.AutoFilter

    Worksheets("Items to push to CA").Activate

    'Application.ScreenUpdating = True
End Sub

Comment: This would better fit to [Stack Exchange: Code Review](https://codereview.stackexchange.com)
Comment: First of all avoid using `.Activate`, `.Select` and `.Selection`: [How to avoid using Select in Excel VBA](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba)
Comment: Thanks for your feedback :)
Answer: .Activate, .Select and AutoFilter are very slow. Try to change your Range into array and do the operations, and with some smarter search algorithm before copying to the target location. This should boost up the speed by a few times at least.
Answer: This question is more for Code Review but try adding Application.ScreenUpdating=False when the sub starts and Application.ScreenUpdating=True when tue sub ends
Comment: I didn't downvote, but the OP refers to screen updating not making any difference, oddly.
Comment: *screen updating to false but it doesn't really speed things up* Absolutely right. I did not read the question properly. My bad.


Square in an Inequality

Question: Say we have the inequality $x^2 \leq 4$. This should imply, unless I'm mistaken, $-2 \leq x \leq 2$.
This sounds rather trivial, but I'm having some trouble understanding why exactly it's the case or what the general rule may be in this case. (A proof would actually be extremely helpful, if anyone has ideas on how to put one together.)
Thanks.
Comment: It might be helpful to note that for real $x$, $\sqrt{x^2} = |x|$.  Thus can consider the cases $x \ge 0$ and $x < 0$ separately.
Comment: It is not clear what you are asking. In the example you give (assuming we are working in the reals) it is straightforward to show that the sets $\{ x | x^2 \le 4 \}$ and $\{ x | -2 \le x \le 2 \}$ are the same.
Answer: It's $$\sqrt{x^2}\leq2$$ or $$|x|\leq2,$$ which is $$-2\leq x\leq2.$$
Answer: $$x^2 \le 4$$
$$x^2-4 \le 0$$
$$(x-2)(x+2) \le 0$$
The sign changes when $(x-2)(x+2)=0$, by testing the $x < -2, -2 < x < 2, x>2$, you can find the corresponding region easily.
Sketching of graph might help. Look for the region that is below the $x$-axis.
Answer: It's not that trivial.
We have that if $0 < a$ and $b < c$ than $ab < ac$. (an axiom)
So if $0 < a < b$ then we must have $a^2 = a*a < a*b < b*b = b^2$ and if $0 < b < a$ the reverse.
So for $0< a; 0 < b$ then $a < b \iff a^2 < b^2$.
And we have if $a < 0$ and $b < c$ then $ab > ac$.  (an easy proposition)
So if $b < a < 0$ then $b^2 = b*b > b*a > a*a = a^2$ (and the converse if $a < b < 0$.
So if $b < 0; a < 0$ then $a < b \iff a^2 > b^2$.
And therefore if we don't know the signs of $a$ or $b we have:
$a^2 < b^2$ if and only if $-|b| < |a| < |b|$.
Thus we can assume if $x^2 \le 4$ then $-2 \le x \le 2$ and if $x^2 \ge 4$ then either $x \le -2$ or $x \ge 2$.
It is treated as something obvious and in one sense it is obvious, but... it's not as trivial in my opinion as people treat it.
However once you prove it, you've proven it forever and never have to worry about it again.
Answer: $x^2 -4\le 0.$
$\star$: $(x-2)(x+2) \le 0.$
One of the factors is $\ge 0$, the other factor is $\le 0$.
1) Assume $x \ge 0: $
The second factor in $\star$ is positive.
Hence $x-2 \le 0$, or $x \le 2:$
Putting together : $0 \le x \le 2$.
2) Assume $x \lt 0.$
The first  factor in $\star$ is negative.
Hence $x+2 \ge 0$, or $x\ge -2.$
Putting together: $-2 \le x \lt 0.$
Finally:
$-2 \le x \le 2.$

Square in an Inequality


Prove:$x^2+2xy+3y^2-6x-2y\ge-11\;\;\forall(x,y)\in\Bbb{R}$

Question:
Problem Statement:-
Prove that for all real values of $x$ and $y$
  $$x^2+2xy+3y^2-6x-2y\ge-11$$

I have no idea how to approach this question all I could think on seeing it was tryin to find the linear factors, turns out that the determinant
$$\begin{vmatrix}
a & h & g\\
h & b & f\\
g & f & c\\
\end{vmatrix}\neq0$$
So finding linear factor just flew out of the window, so I plotted the equation $x^2+2xy+3y^2-6x-2y=0$ turns out it is an ellipse. I could conclude no further as to how to approach this problem.
Comment: Are you allowed to use derivatives?
Comment: @Sil - Hmm...didn't think about that but does partial derivative w.r.t either of $x$ or $y$ produces the result?
Comment: Try taking derivatives to find extrema (in particular a minimum).
Comment: @user350331 Yes, it reduces to solving $2$ linear equations in $2$ variables.
Answer: We have
$$\begin{align}x^2+2xy+3y^2-6x-2y+11&=x^2+(2y-6)x+3y^2-2y+11\\\\&=(x+y-3)^2-(y-3)^2+3y^2-2y+11\\\\&=(x+y-3)^2+2y^2+4y+2\\\\&=(x+y-3)^2+2(y+1)^2\end{align}$$
Comment: @tatan: We have $x^2+(2y-6)x=(x+y-3)^2-(y-3)^2$ because $x^2+2Ax=(x^2+2Ax+A^2)-A^2=(x+A)^2-A^2$ where $A=y-3$.
Comment: How did you get the third step from second step?
Answer: Consider $f(x,y) = x^2 + 2xy + 3y^2 -6x -2y + 11 = x^2 + (2y -6)x + (3y^2-2y -11)$ as quadratic polynomial on $x$ variable, then the classic discriminant is
$$ \Delta =-8y^2 -16y -8 < 0 \quad\forall y\in \mathbb{R}/\{-1\}  $$
Thus $f(x,y) > 0 $ for each $y \in \mathbb{R}/\{ -1\}$, now the only case that you should work is for $y=-1$ and this is easy.
Answer: Once you can use derivatives this is straightforward:
$$
f_x = 2x+2y-6=0\\
f_y = 2x+6y-2=0
$$
These give you a critical point $(x_0,y_0)=(4,-1)$. You can verify that $f(4,-1)=-11$. It remains to show that this is indeed the minimum (here is where the second derivatives come):
$$
f_{xx} = 2,f_{xy} = 2,f_{yy} = 6
$$
So you have
$$
f_{xx}f_{yy} -f_{xy}^2 = 12-4=8 > 0, f_{xx}>0
$$
and by the Second Derivative Test it is sufficient to conclude that $f(4,-1)=-11$ is indeed the minimum.
Answer: Let $f(x,y)=x^2+2xy+3y^2-6x-2y$
$$\frac{\partial  f(x,y)}{\partial x}=2x+2y-6=0\\\frac{\partial  f(x,y)}{\partial y}=6y+2x-2=0$$ It is clear that $f(x,y)$ has no maximum. Then the solution of this system $(x,y)=(4,-1)$ gives a minimum. This minimum is precisely
$$f(4,-1)=-11$$
Comment: You actually have a function z = F (x, y) and the criterion of the second derivative applies similarly to when it has a function y = f (x). In this case, when there is, say, a minimum (graphically), you can see that as the variable grows, the value of the derivative (i.e. the value of the tangent) goes from zero (at the extreme point) to a positive value, that is, the derivative is increasing. Something similar is given for the function z = F (x, y). Now if you are "inspired" it would be better to look at Mathlove's answer above. Sorry for bad English.
Comment: Can you explain what you have done?
Comment: See at  Sil's solution above and consider that it is obvious that there is no maximum
Comment: I did not understand the second part of his answer
Answer: The matrix for the quadratic form is
$$
A=\begin{bmatrix}
1 & 1 & -3 \\
1 & 3 & -1 \\
-3 & -1 & 11
\end{bmatrix}
$$
A sufficient condition for the quadratic form to be positive semidefinite is that the leading principal minors but the last (that ought to be nonnegative) are positive. If also the full determinant is positive, the matrix is positive definite.
The leading principal minors are
$$
\det[1]=1,
\qquad
\det\begin{bmatrix}1 & 1 \\ 1 & 3\end{bmatrix}=2,
\qquad
\det A=0
$$
Thus $A$ is a positive semidefinite symmetric matrix and thus $v^TAv\ge0$ for all $v\in\mathbb{R}^3$, in particular for $v=[x\;y\;1]^T$, which proves the thesis.
The null space can be determined by Gaussian elimination:
\begin{align}
\begin{bmatrix}
1 & 1 & -3 \\
1 & 3 & -1 \\
-3 & -1 & 11
\end{bmatrix}
&\to
\begin{bmatrix}
1 & 1 & -3 \\
0 & 2 & 2 \\
0 & 2 & 2
\end{bmatrix}&&R_2\gets R_2-R_1, R_3\gets R_3+3R_1
\\&\to
\begin{bmatrix}
1 & 1 & -3 \\
0 & 1 & 1 \\
0 & 2 & 2
\end{bmatrix}&&R_2\gets \tfrac{1}{2}R_2
\\&\to
\begin{bmatrix}
1 & 1 & -3 \\
0 & 1 & 1 \\
0 & 0 & 0
\end{bmatrix}&&R_3\gets R_3-2R_2
\\&\to
\begin{bmatrix}
1 & 0 & -4 \\
0 & 1 & 1 \\
0 & 0 & 0
\end{bmatrix}&&R_1\gets R_1-R_2
\end{align}
So an eigenvector for the zero eigenvalue is
$$
\begin{bmatrix}4 \\ -1 \\ 1\end{bmatrix}
$$
and, indeed, the point with coordinates $(4,-1)$ is the only one where the form vanishes.


Determinar o maior numero primo apos ser fornecido um valor usando função while

Question: Tenho que criar um exercicio para descobrir o maior numero primo apos ser me fornecido um certo valor usando a função while, o que esta errado no que criei abaixo??
def maior_primo(n):
    x=0
    y=0
    while y<=n:
        y=y+1
        x=n-1
        if (x % y==0 and x//y==0):
            return x
        else:
            x%y!=0
            return y

Comment: E você quer que a gente adivinhe qual é a  linguagem?
Comment: Python pela sintaxe
Comment: Isso não elimina o uso das tags xD
Comment: Claro, foi só numa de tentar adivinhar :D
Answer: Existem alguns problemas com a sua solução. O incremento no ciclo estava a ser feito logo no inicio por isso iria analisar um elemento a mais, em:
while y<=n:
    y=y+1

Para saber se um numero é primo temos de tentar dividir por todos os que estão no meio e não somente um, como acontece aqui:
if (x % y==0 and x//y==0):
    return x

Estendendo a sua solução e tornando correta:
def maior_primo(n):
    x=0
    y=n #começar do cima para baixo para poder sair no primeiro primo

    while y>=1: #ciclo agora ao contrario até 1
        for x in range(2, y + 1): #range nao inclui o ultimo, logo tem de ser y +1
            if y % x == 0:
                break

        if x == y: #se chegou até y é porque nao deu para dividir por nenhum, logo primo
            return x

        y = y - 1

    return 1 #se nao deu para achar nenhum primo retorna-se um


Python: How to store mutable variables like sets?

Question: I wanted to store a set and afterwards remove some elements inplace like:
>>> A = set({1,2,3})
>>> B = A
>>> A.remove(3)

But so B changes also:
>>> B
set([1, 2])

Is there a way to store A and not changing B without using:
>>> A = A - {3}

Comment: If you're expecting statements like `B = A` to make a copy, you should probably read up on [what Python variables are and what assignment actually does in Python](http://nedbatchelder.com/text/names.html).
Comment: @user2357112 Thanks for this hint, this is a very good summary!
Answer: So you need to write like this:
A = {1,2,3}
B = A.copy()
A.remove(3)
print(B)

Prints:
{1, 2, 3}

Comment: In this case, `copy.deepcopy()` wouldn't be required, `copy.copy()` would suffice.
Comment: You can also do `B = A.copy()`  This method exists on `set` and also provides a deepcopy without the import
Comment: @sedavidw: `set.copy()` is a shallow copy, not a deep copy.
Comment: You're right in that it's a shallow copy, but here a shallow copy is actually okay, mistyped my comment
Answer: The function you are looking for is deepcopy from copy.
>>> from copy import deepcopy
>>> A = set({1,2,3})
>>> B = deepcopy(A)
>>> A.remove(3)
>>> A
set([1, 2])
>>> B
set([1, 2, 3])

Answer: You need to use copy, set is a collection of immutable object, element of set can't be changed in place, Hence deep copy is not needed.
a = set({1,2,3})
b = a.copy()
a.remove(1)
>>> a
set([2, 3])
>>> b
set([1, 2, 3])


Does there exist a double cover with trivial deck transformation group?

Question: Sorry for the naive question. The following statement at the beginning of Bredon, chapter 4, §20, got me confused:

Let $\pi:X \to Y$ be a two-sheeted covering map. Let $g:X \to X$ be the unique nontrivial deck transformation. [...]

With no additional hypotheses on $X$ and $Y,$ is Bredon claiming that the deck transformation group of $\pi$ is always $\mathbb{Z}/2?$ I thought that it could happen to be the trivial group, but I haven't been able to work out a concrete example yet.
Comment: One can describe $g$ explicitly: It's simply the map that exchanges the two elements of each $\pi$-fiber. This is a deck transformation by construction, and it is nontrivial (in fact $g$ fixes no points).
Comment: @Travis Right, in this case it's clear that $g$ is an homeomorphism since it's a continuous involution...
Answer: Look at the classification of covering spaces (e.g. Hatcher's Theorem 1.38 and Proposition 1.39): A two-sheeted cover $p : (\tilde X, \tilde x_0) \to(X, x_0)$ is determined by the subgroup $\Gamma = p_*\left[\pi_1(\tilde X, \tilde x_0)\right] \subset \pi_1(X, x_0)$, which is of index two. Now, an index-two subgroup is automatically normal, and then the deck transformation group is isomorphic to the quotient $\pi_1(X, x_0)/\Gamma$, which is of order two.
As Travis remarked in his commentary, the nontrivial deck transformation is quite easy to describe explicitly. This is nothing but a geometric translation of the well-known proof that an index-two subgroup is normal (which I can recall in few words: if $H \subset G$ is of index two, its only non trivial left coset has to be $G \setminus H$, and ditto for the right coset, so we have $gH = Hg$ for every $g \not\in H$. Since it's also true [and obvious] for $g \in H$, $H$ is indeed normal).
Comment: Oh, so this is why this doesn't work for 3-sheeted covers and above; the image of the fundamental group of $\tilde{X}$ then isn't automatically normal inside the fundamental group of $X,$ so that the deck transformation group is not necessarily isomorphic to a quotient of the entirety of $\pi_1({X})$ by $p_*(\pi_1(\tilde{X}))...$
Comment: This is especially nicely put!
Answer: Why an answer to a five year old question? Simply because it is an interesting question and the existing answers do not really take up the question in the title.
We shall show hat the answer is "no" without any assumptions on $X,Y$.
The scope of Bredon's book is limited to Hausdorff, arcwise connected and locally arcwise connected spaces (see also Valentin's answer). Bredon's definition of a covering map is therefore not the most general one (see e.g. here). However, within Bredon's scope PseudoNeo tells the complete story. Valentin shows that for general covering spaces the group of deck transformations may be bigger than $\mathbb Z_2$.
So let us prove the following two theorems for general two-sheeted covering maps $\pi : X \to Y$.
Theorem 1. There exists a unique deck transformation $g : X \to X$ without fixed points. This deck transformation flips the points in each fiber $\pi^{-1}(y)$, $y \in Y$.
Remark. Each deck transformation $\phi$ has the property $\phi \circ \phi = id_X$. Thus all non-trivial elements of the group $\mathcal D(\pi)$ of deck transformations of $\pi$ have order two. If $\phi \ne id_X$, then $D(\phi) =\{id_X,\phi\}$ is a subgroup of $\mathcal D(f)$ such that $D(\phi) \approx  \mathbb Z_2$. As Valentin has shown, there may be more than one such $\phi$, i.e. the $\mathcal D(f)$ may have more than one subgroup isomorphic to  $\mathbb Z_2$.
Theorem 2. If $X$ is connected, then $id_X$ and $g$ are the only deck transformations. Thus $\mathcal D(\pi) \approx \mathbb Z_2$.
Proof of Theorem 1: For each $x \in X$ there exists a unique $g(x) \in X$  such that $\pi^{-1}(\pi(x)) = \{x,g(x)\}$. This gives us a unique function $g : X \to X$ such that

$\pi \circ g = \pi$
$g$ has no fixed points.

Clearly, $g$ is a bijection such that $g^{-1} = g$. We shall show that $g$ is continuous (which implies that $g$ is a homeomorphism and thus a deck transformation). Each $y \in Y$ has an open neighborhood $U(y)$ in $Y$ which is evenly covered, that is  $\pi^{-1}(U(y)) = V_{+1}(y) \cup V_{-1}(y)$ with disjoint open $V_i(y) \subset X$, $i = \pm 1$, such that the restrictions $\pi_i : V_i(y) \to U(y)$ of $\pi$ are homeomorphisms. Clearly each $V_i(y)$ contains exactly one point of each fiber $\pi^{-1}(y')$, $y' \in U(y)$. In other words, if $x \in V_i(y)$, then $g(x) \in V_{-i}(y)$. For $x \in \pi^{-1}(U(y))$ we therefore have
$$g(x) = \begin{cases} \pi_{-1}(\pi_{+1}(x)) & x \in V_{+1}(y) \\  \pi_{+1}(\pi_{-1}(x)) & x \in V_{-1}(y) \end{cases}$$
This shows that $g \mid_{\pi^{-1}(U(y))}$ is continuous. But $X$ is covered by the open sets $\pi^{-1}(U(y))$, $y \in Y$, thus $g$ is continuous.
Proof of Theorem 2: Certainly $id_X$ and $g$ are distinct deck transfomations. Let $\phi : X \to X$ be an arbitrary deck transformation. Clearly $id_X, g,\phi$ are lifts of $\pi : X \to Y$. Since $X$ is connected, it is well-known that two lifts agree if they agree at some point $x \in X$. See e.g. Hatcher Proposition 1.34. Pick any $x \in X$. Then either $\phi(x) = x = id_X(x)$ or $\phi(x) = g(x)$ and we conclude that either $\phi = id_X$ or $\phi = g$.
Answer: A small addendum to the uniqueness statement: Bredon only works with arcwise connected covering spaces. If we do not assume $X$ to be connected consider a map between spaces with discrete topologies $\{a_1,a_2, b_1,b_2\} \to \{a,b\}$, where $a_i\mapsto a, b_i\mapsto b$. This $2$-sheeted covering has $4$ Deck transformations (the deck transformation group is isomorphic to $\mathbb{Z}_2\times \mathbb{Z}_2$).
This is a special case of a more general construction of $p$-sheeted covering maps from a space with $pn$ points to a space with $n$ points with deck transformation group isomorphic to $\prod_{i=1}^n S_p$. Here $S_p$ denotes the permutation group. We may also replace the points with disjoint unions of any fixed space to get this results in a general situation.


Change CSS from TextBox With ID using Master Page

Question: I've changed my css from an element into a master page.
But in my css, i need to put ContentPlaceHolder1_ to apply the changes.
Anyone know how can i avoid this (To use contentplaceholder_1) before element ID).
CSS
/* LOGIN */
.login #ContentPlaceHolder1_lbtnCadastrar, #ContentPlaceHolder1_lbCadastrado
{
    font-size: small;
}

.login #ContentPlaceHolder1_btnAcessar
{
    margin-top: 5px;
    float: right;
}

LOGIN PAGE
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

                        <asp:Label ID="lbEmail" Text="E-mail" runat="server" for="Email" />
                        <asp:TextBox ID="txtEmail" runat="server" class="form-control" placeholder="Digite seu e-mail" />
                        <asp:Label ID="lbSenha" Text="Senha" runat="server" for="Senha" />
                        <asp:TextBox ID="txtSenha" runat="server" class="form-control" TextMode="Password"
                            placeholder="Digite sua senha" />
                        <asp:Label ID="lbCadastrado" Text="Não é cadastrado ainda?" runat="server" />
                        <asp:LinkButton ID="lbtnCadastrar" Text="Cadastre-se" runat="server" PostBackUrl="../site/cadastro.aspx" />
                        <asp:Button ID="btnAcessar" Text="Acessar" runat="server" class="btn btn-default"
                            OnClick="btnAcessar_OnClick" />

</asp:Content>

Answer: ASP.net changes, some say mangle, ID and Name attributes to ensure they will be unique on a page if they are in some form of Naming Container. If you know they will be unique and you are .net framework 4 and upwards, you can use ClientIDMode="static" (https://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode%28v=vs.110%29.aspx)
E.g:
<asp:Button ID="btnAcessar" ClientIDMode="static" Text="Acessar" runat="server" class="btn btn-default"  OnClick="btnAcessar_OnClick" />

Will enable you to use:
#btnAcessar {/*Styles here*/}

It is, however, better practice to use CSS classes where possible. Some people advocate avoiding IDs all together in CSS.


Can you goaltend a shot that won't count?

Question: I was watching a review of the longest shot in NBA history and was reminded of this pretty incredible bucket:
https://www.youtube.com/watch?v=xm8CS9DVsUA
This video is of the 2015 Boston Celtics attempting an inbounds play against the Indiana Pacers from the opposite baseline with only 1.1 seconds left. The play is to heave the ball across the entire court towards the basket, but it actually goes in the basket instead.
Of course, that shot doesn't actually count. The player, Jae Crowder, is out of bounds on the opposite baseline and you can't score from out of bounds. His intent is to actually pass it to a teammate so they can attempt a shot within the last second+ of time in the half.
But this leads me to my question: this heave has no chance of scoring even if it goes through the basket. Can a player, preferably a player from the team on offense, simply touch the ball, or just straight up catch and dunk the ball despite the fact that it's clearly heading down towards the basket and would otherwise be a goaltending violation if it were a "normal" shot?
Answer: I can't find anything in the rules that would indicate this to be a violation.  So absent other evidence, this should be a legal play.
Section 8 of the NBA Rulebook governs the throw-in.  As long as the throw-in directly touches a player in the game, it is legal and should not be penalized.
Section 11 covers basket interference.  Except for what appear to be some editing issues, the prohibitions on touching the ball before it reaches the basket area are limited to balls that "have a chance to score".  Since the throw-in does not fit this condition, there can be no basket interference.
Answer: No. You can't goaltend a shot that won't count. For example, if the clock runs out and THEN, someone shoots (after the buzzer) and a player on the opposing team hits the ball off of the rim of the hoop (or 'goaltend's' in some other way) the points are still invalid.
Comment: Sure, and I understand this. But the context in the body of my question is different. What you're describing is a situation that won't matter at all. Kevin Garnett, for example, would regularly jump up and pluck shots out of the air that occurred after whistles. My question is focused on a situation where a shot could count, but would require a player to commit an action that would otherwise be a violation in a different, more normal situation.


Find maximum and minimum eigenvalues of symmetric matrix

Question: I have to find maximum and minimum eigenvalues of symmetric matrix. First that I've done is tridiagonalize it and now it looks like
$$
{A_{n \times n}} = \left[ {\begin{array}{*{20}{c}}
{a_1}&{b_2}&{}&{}&{}\\
{b_2}&{a_2}&{b_3}&{}&{}\\
{}&{b_3}&{\ddots}&{\ddots}&{}\\
{}&{}&{\ddots}&{\ddots}&{b_{n}}\\
{}&{}&{}&{b_{n}}&{a_n}
\end{array}} \right]
$$
I have to do it with some kind of recursion but can't find anything that can help me to understand how to do it.
Comment: Have a look at this question https://mathoverflow.net/questions/131527/eigenvalues-of-symmetric-tridiagonal-matrices
Answer: The key is that the task is formulated not properly. I thought I should use some properties of tridiagonal matrices but I don't. To find max and min eigenvalues it's enough to use simple iterations:
$$
x^{(0)} = (x_1, x_2, \ldots, x_n)^T
$$
$x^{(0)}$ is a random vector.
$$
x^{(k+1)} = A \frac{x^{(k)}}{\alpha_k}
$$
Where $\alpha_k$ is the maximum element of $x^{(k)}$ in absolute value.
So, $\lambda_{max}=\alpha_n$ is the max eigenvalue in absolute value.
To find the minimum eigenvalue:
$$
x^{(k+1)} = A^{-1} \frac{x^{(k)}}{\alpha_k}
$$
Where $\alpha_k$ is the maximum element of $x^{(k)}$ in absolute value.
So, $\lambda_{min}=\frac{1}{\alpha_n}$ is the min eigenvalue in absolute value.


In Multisite setup the custom page '/speakers' should available on domain1 site only

Question: I have Multi-site setup , want to make available custom page say '/speakers' on domain1 site but not on domain2 site
I have tried to figured out in routing.yml file to check is there way to pass any variable in route where I can define that route should available for specific domain only,
even I tried with the alter routes approach as well but no luck.
Note: Both sites has same custom module installed.
Comment: Does this mean each site has the same custom module installed that provides the route? If so the question is missing that information.
Comment: Yes , both sites has same custom module installed, updated that missing info.
Comment: One solution is not to install the module on some sites. Another is to define the route dynamically in PHP.
Comment: Yet another is to have the route controller return a 404 base on the request domain.
Comment: Thanks a lot, I used kind of similar approach in which removed the route conditionally by using alter routes()
Answer: Just for record purpose, posting answer:
I used alter routes() approach in which used remove function w.r.t to domain condition:
  $collection->remove('route_name');

Created: module_name.services.yml (root of custom module)
module_name.route_subscriber:
    class: Drupal\module_name\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Created: RouteSubscriber.php (module_name\src\Routing)
<?php
  namespace Drupal\module_name\Routing;
  use Drupal\Core\Routing\RouteSubscriberBase;
  use Symfony\Component\Routing\RouteCollection;

  class RouteSubscriber extends RouteSubscriberBase {

    protected function alterRoutes(RouteCollection $collection) {
      $domain = \Drupal::request()->getHost();
      // check domain
      if($domain == 'domain_name'){
        if ($collection->get('route_name')) {
          // remove route conditionally
          $collection->remove('route_name');
        }
      }
    }

  }

Info: I Choose this particular approach becoz I need to enabled same module for both sites
To get more info related to routes, visit to this documentation link on official site of DRUPAL


Number of elements in a ring such that $x^2=1$

Question: How many elements,$x,$ in the ring $\mathbb Z/95 \mathbb Z$ such that $x^2=1?$
Hints please...
Thanks in advance...
Comment: You should ask whoever gave you the question what he/she means with $x^2$ if there is reason for doubt. However it should mean $x*x$.
Comment: No. There is at least another, 94. I reasoned this from noting that $x^2=1$ implies $(x-1)(x+1)=0$ and this is true if $x=-1=94$.
Comment: I think there is only one element. $x=1.$ Is this correct?
Comment: @sahab  in the ring $\mathbb Z/95 \mathbb Z,\ 19\times5=0,$ neither 19 nor 5 is zero.
Answer: Regarding the actual problem, $\mathbb{Z}/95\mathbb{Z} \cong (\mathbb{Z}/19\mathbb{Z}) \times (\mathbb{Z}/5\mathbb{Z})$ and $-1 \mapsto (-1, -1) = (18, 4)$ under the natural isomorphism, so you can solve the problem in $(\mathbb{Z}/19\mathbb{Z})$ and $(\mathbb{Z}/5\mathbb{Z})$ separately, and then combine your answers to arrive at the complete solution.
Answer: A ring is said to have two basic operations defined on its elements; namely, addition and multiplication.
Unless explicitly mentioned, assume that $x^2$ is defined as the product of $x$ with itself inside the ring.
Thus, $x^2 = x \times x = 1$.
Hint
The notation $\mathbb{Z}/95\mathbb{Z}$ means a ring of integers modulo $95$. Thus, it will have the elements: $\{ 0, 1, 2, 3, 4, \cdots, 94 \}$
Comment: How to proceed to find such a $x?$
Comment: $x\cdot x \equiv 1 \mod(95)$
Answer: $x^2$ is usually taken to be $x*x$.


Java 7 get number of days between 2 dates with correct calculation for leap years

Question: I've seen many examples on Java 7 how to calculate days between 2 dates but I have found out that they do not include leap years correctly.
I've seen this example, but apparently leap years are not included:
Calculating days between two dates with in java
So I would like to see correct Java code how to get number of days without using Joda Time and Java 8?
Comment: No, sorry, the easiest way would be to use Jodatime or Java 8 :)
Comment: The easiest way would be to convert your Gregorian date to a Julian day number. This is described [on Wikipedia](https://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_day_number). Once you have the Julian day number for both dates, subtract them.
Comment: I mentioned I am interested in Java 7. I am using Java 7 for my work for specific reasons.
Comment: Use Julian days, and you could do it in any version of Java.
Comment: Before java.time framework arrived in Java 8 (and [back-ported to Java 6 & 7](http://www.threeten.org/threetenbp/)), there was no built-in way to truly represent a date-only value sans time-of-day & time zone. For such a value, see the [`java.time.LocalDate`](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) class. So there is no clean simple answer for you using old code, as seen in the comments on the [Answer by tamas rev](http://stackoverflow.com/a/37204352/642706). Those old date-time classes were supplanted by java.time classes for a reason (actually, *many* reasons).
Answer: What about this arithmetic?
package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DayDifference {

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse("2016-02-28");
        Date d2 = sdf.parse("2016-03-01");

        long diff = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24);

        System.out.println("diff: " + diff);
    }
}

This outputs 2, so works well with leap years.
Update: According to Andreas's comment you're better of with the +12h hack because it handles the daylight saving too: (d2.getTime() - d1.getTime() + 1000 * 60 * 60 * 12) / (1000 * 60 * 60 * 24)
Comment: But doesn't work when crossing Daylight Saving Time. Says there are `0` days between `2016-03-13` and `2016-03-14` (America/New_York).
Comment: Since inputs are pure dates, and DST is never 12+ hours, this can be fixed by making the division rounding, i.e. add half a day: `(d2.getTime() - d1.getTime() + 1000 * 60 * 60 * 12) / (1000 * 60 * 60 * 24)`
Comment: That gives '1' on my machine (CET/CEST). Anyway, we need full specification for what do we consider as 'one day difference'. E.g. what should be the difference between `2016-03-13 23:12:05` and `2016-03-14 00:17:44` ?
Comment: If the interpretation is that a "date" doesn't have a time-of-day, i.e. is a "pure" date like your code example has it, then it is a non-issue.


ProFTPD - File owner is www-data instead of connected user

Question: For some reason, when I ftp in using ProFTP, files I create are owned by www-data:www-data. I'd like them to be owned by myusername:www-data. The strange thing is, there's nothing in the files in /etc/proftpd that mentions www-data.
User's info:
$ id user1
uid=1002(user1) gid=33(www-data) groups=33(www-data)
$ grep 1002 /etc/passwd
user1:x:1002:33:User,,,:/home/user1:/bin/bash

Comment: @MichaelBailey Edited my post.
Comment: AFAIK you [can't award the bounty to yourself](http://meta.stackexchange.com/questions/120242/what-happens-to-a-bounty-if-you-accept-your-own-answer)   so the fake Internet points are gone.
Comment: Man that's depressing.
Comment: Please can you check if the UID of both users is the same?
Comment: I don't see how two users on a Linux system would have the same UID. I checked anyway, and no.. all UIDs are unique.
Comment: Are your ProFTPD configuration employing "Virtual Users" as for http://www.proftpd.org/docs/howto/VirtualUsers.html and, if yes, which is the UID assigned to the username you're using? P.S.: as for your previous doubts: main passwd file is subject to (error-prone) manual handling :-)
Comment: @DamianoVerzulli No, using real users that are in /etc/passwd.
Comment: What they're asking you to do is check /etc/passwd for the UIDs. If they had manually assigned UIDs somehow, they'd have that. **grep myusername /etc/passwd** and **grep www-data /etc/passwd**. Please display the results here if you can.
Comment: What is ProFTPD being run by? Kinda a moonshot but...
Comment: Ugh, I was connecting to the wrong port! I guess I have to let this question get dusty, because I can't delete it now that it has a bounty on it.
Comment: That seems like one hell of a SF flaw. Can you self-award it?
Comment: Just answer it yourself and mark your own answer correct?
Answer: Try making sure you're using the right port number next time! ;)


Primefaces (TabView): Propriedades nulas ao salvar

Question: Estou utilizando uma TabView com duas abas e cada aba com um arquivo externo com campos. Ao clicar no botão "Salvar" os atributos estão vindo como nulos.
Segue o código:
ClientesCadastrados.xhtml:
<code>...
<h:form id="frm-cadastro-cliente-dialog">
    <p:dialog header="Cadastrar Cliente" widgetVar="cadastroClienteDialog">
        <p:tabView>
            <p:tab title="Dados Pessoais">
                <h:panelGrid columns="2">
                    <ui:include src="/WEB-INF/cliente/ClientePartialDadosPessoais.xhtml" />
                </h:panelGrid>
            </p:tab>

            <p:tab title="Endereço">
                <h:panelGrid columns="2">
                    <ui:include src="/WEB-INF/cliente/ClientePartialEndereco.xhtml" />
                </h:panelGrid>
            </p:tab>
        </p:tabView>

        <p:commandButton value="Salvar" action="#{clienteBean.salvar}"/>
    </p:dialog>
</h:form>
...
</code>
ClientePartialDadosPessoais.xhtml:
<code>...
<p:outputLabel value="Nome" for="nome" />
<p:inputText id="nome" required="true" value="#{clienteBean.cliente.nome}" />

<p:outputLabel value="E-mail" for="email" />
<p:inputText id="email" value="#{clienteBean.cliente.email}" />

<!--  outros campos... -->
</code>
ClientePartialEndereco.xhtml:
<code>...
<p:outputLabel value="Logradouro" for="logradouro" />
<p:inputText id="logradouro" value="#{clienteBean.cliente.logradouro}" />

<p:outputLabel value="Complemento" for="complemento" />
<p:inputText id="complemento" value="#{clienteBean.cliente.complemento}" />

<!--  Outros campos... -->
...
</code>
ClienteBean.java:
<code>@Named
@RequestScoped
public class ClienteBean {

    @Inject
    private Cliente cliente;

    public void salvar() {
        System.out.println("Nome: " + cliente.getNome()); //null
        System.out.println("E-mail: " + cliente.getEmail()); //null
        System.out.println("Logradouro: " + cliente.getLogradouro()); //null
        System.out.println("Complemento: " + cliente.getComplemento()); //null
        ...
    }
}
</code>
Obs: Estou usando CDI.
Answer: Acredito que faltou processar o formulario.
Experimente no  processar o formulario
Ex
<code><p:commandButton value="Salvar" action="#{clienteBean.salvar}" process="@form"/>
</code>
Pode tambem ser problema de scope,  tente mudar para @ViewScoped  do javax.faces.view.ViewScoped ao invés de @RequestScoped. E mantenha o process="@form"
Comment: Valeu Marcelo, o problema era não ter colocado o ViewScoped mesmo. E o erro que estava dando no tomcat ao colocar o ViewScoped era porque eu não estava serializando a classe.
Comment: Obrigado Marcelo, mas não foi. Tentei também o update mas também não deu certo.
Comment: Adicionei um complemento na resposta. veja se agora funciona.
Comment: Marcelo quando eu coloquei o ViewScoped do CDI deu erro ao iniciar o Tomcat 8. Não entendi, pois eu configurei o context.xml e o web.xml para isso. Você sabe o que pode ser isso também?
Comment: Veja se o import esta como javax.faces.view.ViewScoped
Comment: Sim, está dessa forma.
Comment: Não sei o que pode ser. Eu utilizo com Wildfly 10.1 não conheco p Tomcat 8


property of a curve $\alpha(t)$

Question:
Find a parametrized curve $\alpha(t)$ whose trace is the circle $x^2 + y^2 = 1$ such that
$\alpha(t)$ runs clockwise around the circle with $\alpha(0) = (0, 1)$.
A parametrized curve $\alpha(t)$ has the property that its second derivative $\alpha''(t)$ is
identically zero. What can be said about $\alpha$ ?
Let $\alpha:I \to \mathbb{R}^3$ be a parametrized curve and let $v \in \mathbb{R}^3$ be a fixed vector. Assume
that $\alpha'(t)$ is orthogonal to v for all $t\in I$ and that $\alpha(0)$ is also orthogonal to $v$.
Prove that $\alpha(t)$ is orthogonal to $v$ for all $t\in I$.

My thoughts:-
1.the given curve will be $\alpha(t)=(\sin {t},\cos {t})$.
2.The given $\alpha $ is a equation of a straight line.
3.here by the given condition we have $$\alpha'(t).v=0$$ Integrating w.r.t $"t" $ from $t=0$ to $t=t$ we have $v.(\alpha(t)-\alpha(0))=0$
$\implies$ $v.\alpha(t)-v.\alpha(0)=0$ $\implies$ $v.\alpha(t)=0$ as
[$\alpha(0)$ is also orthogonal to $v$ so $v.\alpha(0)=0$]
Am I right in these cases? Can someone please help me to verify these results.
Comment: $\alpha(t) = \alpha(0) + \int_0^t \alpha'(s) \mathrm{d}s$.  Dot with $v$ on both sides.
Comment: These are exercises in chapter 1-2 in do Carmo's Differential Geometry of Curves and Surfaces.
Answer: $\bigl(\alpha(t).v\bigr)'=\alpha'(t).v+\alpha(t).0=0$, i.e, $\alpha(t).v$ is constant.  Now plug in $t=0$.
Comment: How can we differentiate $v$ if it is just a vector and not a function?
Comment: Component wise, as usual.
Answer: The first two points are what you need, yes.
Just a thought on the third, although I believe your solution is correct: the derivative of $\alpha(t)\cdot v$ is $\alpha'(t)\cdot v = 0$, meaning the value of $\alpha(t)\cdot v$ is constant over all $t$. Because $\alpha(0)\cdot v=0$, this means $\alpha(t)\cdot v=0$ for all $t$. I think this is a simpler way of proving what you proved, there is also less writing required if you want to write it rigorously.

property of a curve $\alpha(t)$