Understanding StatQuest video: why cross entropy is used over Sum Squared Error

Question: I was watching cross entropy video from StatQuest. While explaining why to use cross entropy over SSE in multi output scenario with softmax output activation, Josh gives this graph of both losses:

He the says that loss is very high for CE than MSE.
But I am not able to get how he got that orange straight line. I tried to plot in desmos.
. Note that what I have plotted in blue is just (1-p), which I dont believe Josh thought of for MSE. In fact, I dont know if my Cross Entropy plot is correct. Josh says its -log(p). But the x axis is not clearly labeled as p by Josh. What he exactly means by X axis labels "worst prediction" and "great prediction"? How exactly make sense out of this graph by Josh?
PS: I didnt plot $(1-p)^2$ because its not straight line as in video.
Answer: $p$ here is the predicted probability of an outcome to belong to the class it actually turns out to belong to. To illustrate: suppose we have three possible classes, and our model says that a given new instance has a probability $0.5$ of belonging to the first class, $0.3$ of belonging to the second, and $0.2$ of belonging to the third class. The instance actually turns out to belong to the second class. So in this case, $p=0.3$.
Now, the question is one of how to measure the "badness" of our probabilistic prediction. The two losses you note are quite common. We note that a perfect prediction would have been $p=1$, i.e., we would have predicted the new instance to belong to the class it actually turned out to belong to with certainty. (Of course, this also implies that our probabilistic prediction of the instance to belong to the other classes would have been zero.) Both losses are zero for such perfect predictions:
$$ -\log p = -\log 1 = 0\quad\text{and}\quad (1-p)^2=(1-1)^2=0. $$
The question is how these losses behave when our prediction is not perfect. Of course, the lower $p$, the worse the prediction is - and correspondingly, the higher the loss should be.
This is what is depicted. The MSE grows quadratically with decreasing $p$, and ends up at $1$ if $p=0$ (i.e., if we had believed it to be impossible for the instance to belong to the class it actually does belong to). So the MSE is bounded. The line should indeed not be straight, but a parabola. This is presumably to draw attention to the fact that the Cross-Entropy grows much faster as $p$ decreases. In fact, the Cross-Entropy is infinite for $p=0$: seeing an outcome we believed to be impossible yields an infinitely large Cross-Entropy loss.
Cross-Entropy is also known as the log loss, and the MSE is the Brier score. (Many concepts are developed independently by different people, and given different names.) Both are proper scoring rules, i.e., losses that incentivize us to output the true class membership probabilities. (Other losses, like accuracy, do not. Also, a straight line loss like you plotted, which would correspond to the Mean Absolute Error, or MAE, would reward biased predictions.) There is a comparison between the two losses at Why is LogLoss preferred over other proper scoring rules?
Answer: You should not plot $$(1-x)^2$$ Instead, you should plot $$(x-1)^2$$
The reason is that we look at how the loss behaves according to the assigned probability to the ground truth class. For binary cross entropy, it boils down to computing $-log(y_{pred})$. For MSE loss, where we compute in general $(y_{pred} - y)^2$, if we assume y=1, it means: $(y_{pred}-1)^2$.
Basically, you can use this Python snippet to plot the losses:
x = np.linspace(0, 1, 1000)

mse_loss = lambda x: (x-1)**2
log_loss = lambda x: -np.log(x)
#Plot the losses
plt.plot(x, mse_loss(x), label='MSE')
plt.plot(x, log_loss(x), label='Log')
plt.xlabel('Proba assigned to the correct class')
plt.ylabel('Loss')
plt.legend()
plt.show()

Comment: How does $(x-1)^2$ differ from $(1-x)^2?$


how can i remove the login form from the home page

Question: I'm trying to remove the login form from the front page, but i see both frontpage and user/login page are using the same template file: page--front.html.twig.
Is there a way to use two different template files for each page?
Comment: check your blocks, your login form might be a block.
Comment: Or your frontpage is set to /user. In that case, just configure the frontpage to whatever you want it to be.
Answer: Try going to Admin/Structure/Blocks and set User account menu's region to None.
Answer: I had the front page set to null. I had to create an empty basic page and set it as front page to be able to have a front page different than the /user/login page. I don't feel it's the best way to do it, but it works.
Comment: use panels if you could try panopoly.
Comment: Panels is still in development for drupal 8. i wouldn't like to add a whole module for this...


Can the distribution of emission probabilities of an HMM be swapped out for the re-estimated ones only after all training sequences have been covered?

Question: Regarding the re-estimation procedure of the Baum-Welch algorithm, the sources I looked into so far all describe the process in an abstract manner. Therefore I am wondering the following about actually implementing the algorithm:
The re-estimation of the transition probabilities covers all transitions, every single training sequence, right? Meaning, given the current training sequence, I will go through all transitions $a_{ij}$ with $i, j \in H$ (the set of hidden variables) and re-estimate each $a_{ij}$. While I do so I store the re-estimated probabilities somewhere separate from my current transition probabilities and once I am done with all re-estimations I change out the current probabilities with the re-estimated ones. I cannot modify the individual probabilities in place without storing them temporarily, because inserting them directly one after the other would disrupt the probability distribution. Have I got this right so far?
Okay, but I am confused about re-estimating the emission probabilities, for the following reason:
While the $a_{ij}$ are all re-estimated for every single training sequence, this is not true for the emissions $b_i(O_t)$, because
$$b_i^*(O_k) = \frac{\sum_{t = 1}^T 1_{O_t = O_k} \gamma_i(t)}{\sum_{t = 1}^T \gamma_i(t)}$$
($1_{O_t = O_k}$ being an indicator function that returns true iff $O_t = O_k$.)
Thus only those $b_i(O_t)$ are re-estimated for which $O_t$ is an observed variable from the current training sequence $O$. Therefore
1) The distributions of emissions can only be changed out for the distribution of re-estimated emissions after all training sequences have been covered.
2) Many re-estimated emission probabilities will be repeatedly overwritten (if done naively) if the observed variable $O_t$ occurs in several training sequences.
Are these statements correct? I am not sure if I am missing something about the whole process here.
Answer: Both the emission and transition probabilities are calculated as the sum of each sequence's contribution according to its weight in the training set. For example if your training data consist of two sequences:
Sequence 1: H, H, H, T, H, H, T, H, T, H
 Sequence 2: H, H, T, T, H, T, H, T, T, H
and are equally weighted, their emission probabilities are
Sequence 1: $P(heads) = 0.7, P(tails) = 0.3$
 Sequence 2: $P(heads) = 0.5, P(tails) = 0.5$
and the new emission probabilities to use in the next iteration of the expectation-maximization procedure will be
$P(heads) = (0.5 \times 0.7) + (0.5 \times 0.5) = 0.6$
  $P(tails) = (0.5 \times 0.3) + (0.5 \times 0.5) = 0.4$
The same applies when calculating the transition probabilities.
For more details there is a great explanation in chapter 3.3 of Durbin R, Eddy SR, Krogh A, Mitchison G (1998) Biological sequence analysis: probabilistic models of proteins and nucleic acids. Cambridge University Press, Cambridge, United Kingdom.
Comment: Hmm, I don't understand your answer. Consider this: Say I my first training sequence is `H H H`. So no Tails in that sequence. If I re-estimate my emissions now, the emission distribution for each hidden variable is not guaranteed so sum to 1 anymore, right? Because there were no tails in my sequence, so I could not re-estimate the emissions for `T`. The emission distributions will only sum to one, once all observed variables from the training data have been observed at least once. This might take until the very last training sequence of the training data. Are these considerations correct?
Comment: In you example I also don't understand where the respective $0.5$ are coming from, as there are two possible sources.
Comment: In your example, assuming there is only one training sequence, your emission probabilities will still sum to 1 since $P(heads) = 1$ and $P(tails) = 0$. This also illustrates why you should always add pseudocount contributions to the probability calculations, particularly for small training datasets. For example you could add the contribution from a single hypothetical sequence whose emission probabilities are 0.5 for heads and 0.5 for tails to your single sequence above, giving $P(heads) = (0.5 \times 1) + (0.5 \times 0.5) = 0.75$ and $P(tails) = (0.5 \times 0) + (0.5 \times 0.5) = 0.25$.
Comment: In this example and the one above the equations are formatted as $(sequence weight \times emission probability)$. Note that here we assume the sum of the sequence weights is 1.
Comment: what exactly do you mean by sequence weight? I never heard that expression in the context of HMMs.
Comment: If for example, the sequences in the training set vary in their reliability they can be assigned unequal weights, where high-confidence sequences are up-weighted and low-confidence ones are down-weighted. In simple cases such as the one above all sequences are given equal weights. I showed their weights to demonstrate how each sequence contributes to the final emission and transition probabilities in the model.


How to control z-index when using perspective and transform?

Question: I've read a lot of pages talking about z-index and how transform and perspective destroys his context. I understand why my code isn't working what I don't know is how to make it work (or at least use and alternative).
As you can see on the image, the select menu is being covered by the card below.

Here is a snippet with a reproduction of the issue:

.square { position: relative; width: 100%; padding-bottom: 100%; }
.square>* { position: absolute; width: 100%; height: 100%; }

/* flip */
/* u -> uncontroled / c -> controled */
.flip { perspective: 200em; }
.flip .front, .flip .back {
 -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden;
 backface-visibility: hidden; position: absolute;
 top: 0; left: 0; right: 0; bottom: 0;
}
@supports (-webkit-transform-style: preserve-3d) or (-moz-transform-style: preserve-3d) or (transform-style: preserve-3d) {
 .flip .front, .flip .back {
  -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; transition: 1s;
 }
}
/* -> horizontal */
.flip .front { z-index: 2; transform: rotateY(0deg); perspective: none;}
.flip .back { transform: rotateY(-180deg); }
.flip.u:hover .back, .flip.c.active .back { transform: rotateY(0deg); }
.flip.u:hover .front, .flip.c.active .front { transform: rotateY(180deg); }
/* -> vertical */
.flip.vertical .back { transform: rotateX(-180deg); }
.flip.vertical.u:hover .back, .flip.vertical.c.active .back { transform: rotateX(0deg); }
.flip.vertical.u:hover .front, .flip.vertical.c.active .front { transform: rotateX(180deg);  }

.test {
 position: absolute; top: 70%; left: 10%; background-color: green;
 height: 100px; width: 10px; z-index: 100;
}

      Front

Back

Front

Back

What I need is the
 to be displayed in front of all. Like this. But I don't want to set the z-index on the square divs, because they will be placed inside a flex layout Grid.
Is there a way to say to an element to be always rendered in front of all other? No mathers where is he placed or what is happening to the stack context.
Answer: Nobody has found a solution over this last years so here you have what I finally did (as an alternative to solve my specific problem):
I just changed the z-index of all child elements, using js, making thos childs that are first having a higher z-index.

var targets = document.getElementsByClassName("invertChildZOrder");

var i;
for (i = 0; i < targets.length; i++) {
  target = targets[i];
  for (var i = 0; i < target.childNodes.length; i++) {
    var childNode = target.childNodes[i];
    if (childNode.className == "square flip u") {
      childNode.style.zIndex = "" + (target.childNodes.length - i);
    }
  }
}
.square { position: relative; width: 100%; padding-bottom: 100%; }
.square>* { position: absolute; width: 100%; height: 100%; }

/* flip */
/* u -> uncontroled / c -> controled */
.flip { perspective: 200em; }
.flip .front, .flip .back {
  -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden;
  backface-visibility: hidden; position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
}
@supports (-webkit-transform-style: preserve-3d) or (-moz-transform-style: preserve-3d) or (transform-style: preserve-3d) {
  .flip .front, .flip .back {
    -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; transition: 1s;
  }
}
/* -> horizontal */
.flip .front { z-index: 2; transform: rotateY(0deg); perspective: none;}
.flip .back { transform: rotateY(-180deg); }
.flip.u:hover .back, .flip.c.active .back { transform: rotateY(0deg); }
.flip.u:hover .front, .flip.c.active .front { transform: rotateY(180deg); }
/* -> vertical */
.flip.vertical .back { transform: rotateX(-180deg); }
.flip.vertical.u:hover .back, .flip.vertical.c.active .back { transform: rotateX(0deg); }
.flip.vertical.u:hover .front, .flip.vertical.c.active .front { transform: rotateX(180deg);  }

.test {
  position: absolute; top: 70%; left: 10%; background-color: green;
  height: 100px; width: 10px; z-index: 100;
}

      Front

Back

Front

Back

As you can imagine. This only solves the problem partially. If the square on the botton has another menu but this times droping up instead of down we will have same problem.
Answer: I took a different approach. i removed the animation class after the animation finished. I think it is a simpler solution (and I also wasted hours trying to figure out what was going on...)
Answer: All I did was moving the div with class .test outside the div with the flipping element.

.square {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}

.square>* {
  position: absolute;
  width: 100%;
  height: 100%;
}

/* flip */

/* u -> uncontroled / c -> controled */

.flip {
  perspective: 200em;
}

.flip .front,
.flip .back {
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

@supports (-webkit-transform-style: preserve-3d) or (-moz-transform-style: preserve-3d) or (transform-style: preserve-3d) {
  .flip .front,
  .flip .back {
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;
    transition: 1s;
  }
}

/* -> horizontal */

.flip .front {
  z-index: 2;
  transform: rotateY(0deg);
  perspective: none;
}

.flip .back {
  transform: rotateY(-180deg);
}

.flip.u:hover .back,
.flip.c.active .back {
  transform: rotateY(0deg);
}

.flip.u:hover .front,
.flip.c.active .front {
  transform: rotateY(180deg);
}

/* -> vertical */

.flip.vertical .back {
  transform: rotateX(-180deg);
}

.flip.vertical.u:hover .back,
.flip.vertical.c.active .back {
  transform: rotateX(0deg);
}

.flip.vertical.u:hover .front,
.flip.vertical.c.active .front {
  transform: rotateX(180deg);
}

.test {
  position: absolute;
  top: 30%;
  left: 3%;
  background-color: green;
  height: 100px;
  width: 10px;
  z-index: 10;
}

      Front

Back

Front

Back

Comment: Plese read carefull my question. I provided an Image of the project. Of course, if I move the div outside then It will be displayed in front of the other div because then they share the same context. The problem is that that "test" div represents the menu that is shown in the image (and It have to stay inside).


How to extract 32x32 icon bitmap data from EXE and convert it into a PIL Image object?

Question: I'm trying to extract a 32x32 icon from an EXE, and convert the bitmap data into an PIL Image object. My final goal is to compare the icon to another 32x32 PNG and get the difference with RMS.
I've tried doing win32gui.ExtractIconEx() then win32gui.GetIconInfo() and attemping to Image.open() on that, but PIL doesn't accept PyHANDLE objects, apparently. I've also attemped to open the exe directly with Image.open(), obviously that doesn't work.
I'm stumped right now, is there any way this is possible in Python or should I be writing this part of my code in a different language?
Answer: From a mailing list here, I found this code snippet:
import win32ui
import win32gui
import win32con
import win32api

ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)

large, small = win32gui.ExtractIconEx("C:\Program Files (x86)\Malwarebytes' Anti-Malware\mbam.exe",0)
win32gui.DestroyIcon(small[0])

hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) )
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap( hdc, ico_x, ico_x )
hdc = hdc.CreateCompatibleDC()

hdc.SelectObject( hbmp )
hdc.DrawIcon( (0,0), large[0] )

hbmp.SaveBitmapFile( hdc, 'icon.bmp')

From there, you could load it into PIL in the normal Image.open fashion.
If you dig through the docs, you should be able to avoid the IO step and do it all in memory if you want. PIL has a from frombuffer method that you can use to convert the result of GetBitmapBits to an Image object.
Comment: Thanks, I ended up finding some code to convert it into an Image object, [this is what I ended up with](https://gist.github.com/ron975/7314682)
Comment: @ron975: broken link


How to invoke super when the parent method may not be defined?

Question: Certain classes in the Python standard library (and more generally) make use of dynamic dispatch to call specialised methods in subclasses.
For example, the ast.NodeVisitor class defines a visit method.
This method calls visit_classname methods where appropriate.
These methods are not defined on ast.NodeVisitor itself, but may be provided by interested subclasses.
In other words, subclasses override only the methods that they wish to handle, eg:
class SpecialNodeVisitor(ast.NodeVisitor):
    def visit_FunctionDef(self, node):
        print(node)  # prints any node of type FunctionDef

Things get more complicated if SpecialNodeVisitor is itself subclassed.
super() may be used if visit_FunctionDef is overriden, but not in other cases, ie:
class EvenMoreSpecialNodeVisitor(SpecialNodeVisitor):
    def visit_FunctionDef(self, node):
        super().visit_FunctionDef(node)  # works fine
        # ...

    def visit_Call(self, node):
        super().visit_Call(node)  # AttributeError
        # ...

Specifically, the second example causes AttributeError: 'super' object has no attribute 'visit_Call'.

The above behaviour makes sense: the parent class doesn't have the method in question.
However, it causes two problems:

When writing the subclass, some dynamic methods need to call super(), but some don't.  This inconsistency makes it really easy to make mistakes.
If a new dynamic method is later added to the parent class, all of the subclasses have to be altered to call super().  This breaks a really fundamental rule of object-oriented programming.

Ideally, all subclass methods should be able to make use of super(), with the call being a no-op if the method is not defined.
Is there a 'pythonic' way to achieve this?
I am particularly after a solution which is transparent to the subclass (for example, I don't want to try/except on AttributeError in every single method, as this would be just as easy to forget, and is ugly as hell).
(It's worth noting that in many cases, and indeed in this particular example, it's not possible to simply define all the possible methods on the parent class, as doing so may have side effects.)
Comment: A) add the no-op methods to the parent class B) encapsulate the try-except approach.
Comment: What you describe here its just the normal behavior of the language. Looks very logic to me if there is no method in one of the parent classes to raise an attribute error on super().

How can you call something that doesn't exist?!

If you really want to do that add the no-op method on the parent classes.
Comment: Dude, adding methods to classes during the runtime is just wrong. Why would you do that? It generates these kinds of problems. I'm sure it can be avoided. Maybe try to redesign your app.
Comment: @andrefsp - The standard behaviour in frameworks which use this paradigm (eg Objective C) is for invalid messages to be ignored.  I understand that Python doesn't normally make use of this, but I didn't design the `ast` library.
Comment: @freakish - No methods are being added to classes at runtime in the above examples.
Comment: @KarolyHorvath - Encapsulation was my first thought, but because `super()` in Python 3 is 'magic' (ie, relies on the `__class__` cell), I'm not even sure how to make *that* work nicely.  Do you know of a (non-hacky) way?
Comment: @sapi I'm refering to that sentence: `If a new dynamic method is later added to the parent class`. If you were not refering to adding methods in runtime, then you are telling us that at some point you won't know the code you are working with? Yes, sometimes you have to refactor lots of code when you add a method to the parent class. But hiding logic behind `try: except:` is just wrong and it will backfire on you later. That's a bad design.
Comment: @sapi "Explicit is better than implicit" (The Zen of Python)
Answer: You cannot have what you want; the most readable method is to simply use try..except on that AttributeError:
def visit_Call(self, node):
    try:
        super().visit_Call(node)
    except AttributeError:
        pass

The alternative would be for you to add aliases for NodeVisitor.generic_visit for every node type to SpecialNodeVisitor:
import inspect

class SpecialNodeVisitor(ast.NodeVisitor):
    def visit_FunctionDef(self, node):
        print(node)  # prints any node of type FunctionDef

_ast_nodes = inspect.getmembers(
    ast,
    lambda t: isinstance(t, type) and issubclass(t, ast.AST) and t is not ast.AST)
for name, node in _ast_nodes:
    name = 'visit_' + name
    if not hasattr(SpecialNodeVisitor, name):
        setattr(SpecialNodeVisitor, name, ast.NodeVisitor.generic_visit)

You could encapsulate that into a meta class if you want to. Since super() looks directly into the class __dict__ namespaces you cannot simply define a __getattr__ method on the meta class to do the lookup dynamically, unfortunately.
Comment: That's actually kind of brilliant.  I'd thought about using `inspect` to get all the possible methods, but it didn't even occur to me to alias them to `generic_visit`;  Thanks!


One time login redirect to password change page

Question: In D7, How can i redirect the user when he/she use One time login. My target is after clicking one time login button user has to redirect to change password. Can any one help on this.....
Answer: hook_form_alter can be used to add a custom redirect rule. Do it in your custom module.
<code>function MODULE_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'user_pass_reset'){
        $form_state['redirect'] = array('path/to/redirect', array('param' => 'val'));
    }
}
</code>


Implicitly differentiating $y = y^2 x$

Question: I am self learning calculus and have a problem that may be simple here but  I cant find an answer on the web so here it is:
If we have the equation:
$$y = y^2x$$
and differentiate it (implicitly and using product rule) we get:
$$\frac{dy}{dx} = \frac{y^2}{1-2xy}.$$
However, $y =y^2x$ can be simplified to $1 = xy$, i.e. $y = \frac{1}{x} $, which when differentiated using the power rule gives $\frac{dy}{dx} = -\frac{1}{x^2}$. The two differentials are different, as
$\frac{dy}{dx} = -\frac{1}{x^2}$ does not equal $\frac{dy}{dx} = \frac{y^2}{1-2xy}$.
Why is this when we are essentially differentiating the same equation?
(I plotted the graph on wolfram alpha and they are indeed not the same.)
Comment: Ignoring the zeroes, $y=y^2x\implies x=\frac 1y$ so $1-2xy=-1$  But then your second form is $-y^2=-\frac 1{x^2}$ as desired.
Answer: Remember that you found that $y=\frac{1}{x}$.  So, $$\frac{y^2}{1-2xy}=\frac{1/x^2}{1-2}=-\frac{1}{x^2}$$ and the two answers you have found actually are the same.
However, there are some issues with division by $0$ in your second approach.  It is not correct to simplify $y=y^2x$ to $1=xy$; that is only valid if $y\neq 0$.  So in fact, the graph of the equation $y=y^2x$ consists of the parabola $y=\frac{1}{x}$ (along which $\frac{dy}{dx}$ is indeed $-\frac{1}{x^2}$) together with the line $y=0$ (since if $y=0$ the equation $y=y^2x$ is always true).  At points on $y=0$, your first answer $\frac{dy}{dx}=\frac{y^2}{1-2xy}$ is correct (and it simplifies to $0$) but your second answer $\frac{dy}{dx}=-\frac{1}{x^2}$ is wrong.
Answer: The equation is
$$
y(1-xy)=0
$$
so the curve is the union of the line $y=0$ and of the hyperbola $xy=1$.
The function is locally invertible at every point; the derivative at points with nonzero $y$-coordinate is $y'=-1/x^2$; the derivative at points with zero $y$-coordinate is $y'=0$.
If you do implicit differentiation, you get
$$
y'=2yy'x+y^2
$$
that indeed gives
$$
y'=\frac{y^2}{1-2xy}
$$
which is not contradictory: if $y=0$, then $y'=0$; if $y\ne0$, then $xy=1$ and you get
$$
y'=-y^2=-\frac{1}{x^2}
$$

Implicitly differentiating $y = y^2 x$


How can i show an icon in xamarin?

Question: I´m developing an app in xamarin forms and I want to know how show an icon in a menu, the image of this icon is in the resource folder (drawable). The menu is in a Inavigation page in the same project.
I´m trying this with the next code, but it doesn´t work:
*var iconlogin = new ToolbarItem
{
  Icon = "login.png"};*`

  *new Sample("Login", typeof(LoginPage), SampleData.DashboardImagesList[0], iconlogin.Icon, false, false)*

Answer:
How can I show an icon in xamarin?

Add the following code :
var settings = new ToolbarItem
{
    Icon = "icon.png",
    Text = "Settings",
};

this.ToolbarItems.Add(settings); //<-- this line

The icon.png in located in Resource\Drawable folder. If you want use the ToolbarItem in xaml, you need do :
<ContentPage.ToolbarItems>
    <ToolbarItem Name="Menu1" Activated="OnClick"  Order="Primary" Priority="0"  Icon="icon.png" />
    <ToolbarItem Name="Menu2" Activated="OnClick"  Order="Primary" Priority="1" />
</ContentPage.ToolbarItems>

Effect :

For more information, you could refer to the document or this question.

How can i show an icon in xamarin?


having trouble selecting nested same class elements

Question: I am having troubling finding a clean and non-hacky way of selecting my nested intro-cntnr divs. Each nested intro-cntnr gets a different transition delay. I was looking for something like an nth-type-of, which doesn't work cause they are nested. What else can I use in terms of css selectors?

Comment: There's no CSS selector for nested children unfortunately.
Comment: So I guess I just have to do this: .intro-cntnr {
    border-left: 1px solid darkorange;
    padding-left: 10px;
    margin-top: 10px;
}

.intro-cntnr > .intro-cntnr {
    delay..
}

.intro-cntnr > .intro-cntnr > .intro-cntnr {
    delay...
} feels a bit cheap. alrighty then.
Comment: Why not give them unique identifiers? or use scripting to cascade down them? This structure is very abnormal so it is no surprise you are running into some roadblocks support wise.
Comment: I was thinking maybe using and selecting the data-attribute which would be indexed?
Comment: That works about just as well as adding a second class
Comment: Hmm, yea maybe like a delay-transition-x?
Comment: What you name it is inconsequential
Comment: Sounds good. Thanks man.
Answer: Specificity is a key solution. The longer the selector the higher the value according to what is used in selector's path.  Specificity rules are:

inline styles = 1000
ID = 100
Class = 10
Tag name/element = 1

you don't need to do calculations, but keep in mind that more specified means higher chance of targeting required element.  more on Specificity
Following snippet shows different results based on different selectors.

.intro-cntnr .intro-cntnr .intro-cntnr .intro-cntnr .intro-cntnr{
  color: red;
}

.intro-cntnr .intro-cntnr .intro-cntnr{
  color: yellow;
}

.intro-cntnr .intro-cntnr{
  color: blue;
}

.intro-cntnr{
  color: green;
}

        Target value 10

            Target value 20

                    Target value 30

                        Target value 40

Also choosing what kind of selector to use will affect the result Here is a reference to css selectors
Find what will work well with you based on the previous rules and you will get a result. or simply add IDs to elements required to style :')


Can I add some computer/synthesized voices from a computer to my digital piano?

Question: I just bought a digital piano (gear4music DP-6) and I'm a newbie with electronic pianos. I would like to know if it is possibile to add some computer/synthesized voices to my digital piano using my computer. And if it is possibile, how could I do that. I already downloaded some VSTs but I don't think I can add their sample sounds to my digital piano right?
Thank you
Answer: Your piano has MIDI connectors, so you can use it to control VSTs running in a suitable host program on your computer.  There is no way of adding to the sounds made directly from the piano, coming through its speakers or Line Out socket.


if else along with >= (2 times) compiles well but doesnt work

Question: I'm making a Grade log application and I have this piece of code here which doesn't work as I intend it to work. (It compiles great with no errors but doesn't work) (please keep in my mind I am a begginer in C++, thank you for your time and knowledge to help me learn also).
(The testscore is being given from a series of questions where the value gets a +1 if its correct and a -1 if its wrong.
I think the error is in the => it gets conflicted one with the other but i dont know how to give a value for ex. if the score is < 20 cout = failed if its <40 failedgood but see 20 is < 40 so one overrides the other how could i put if its from 20-40  cout = failed good and if its from 0 - 20 cout = failed. I hope you understand what I mean.
   int testscore;
    string studentmark;

            if ( testscore  == 10 )

            {
                studentmark == ( "failed" );
            }
            else if ( testscore >= 11 && testscore <= 20 )
            {
                studentmark == ( "closebutfailed" );
            }
            else if ( testscore >= 21 && testscore <= 30)
            {
                studentmark == ( "passed" );
                }
            else if ( testscore >= 31 && testscore <= 40 )
            {
                studentmark == ("excelent");
            }
            else if ( testscore >=49 )
            {
                studentmark == ("hasteachersbook");
            }
cout << "Studentmark is:" << studentmark << endl;

Comment: Where's your else-clause?  What if the score is less than 10?
Comment: I don't understand what your point is here. I can say that your first `if` test is using `==`. when it looks like you meant to use `<=`. I can also say that all your string assignments are not assignments, they are equality tests (`==` instead of `=`).
Comment: Less than 10 or 41->48 are not covered. For consistency I would add these to the test condition and just comment that nothing should be printed in these conditions (otherwise people will think you forgot to add them).
Comment: (Side note: If you're ever thinking "the language is broken" -- no, it's not.)
Comment: Yes, you are right forgot to add them, but even when the testscore meets the else if creteria it doesnt cout the studentmark. I did the edits mentioned but still nothing.
Answer: First off, your problem is that you should use a single equals sign for assignment, e.g.
studentmark   = "failed";
///         ^^^^ Note single =

Second, you're probably better off writing these if statements as
if (testscore <= 10) { ... }
else if (testscore <= 20) { ... }
else if (testscore <= 30) { ... }
...

Because that's easier to read, and the presence of the else statement means you don't have to test that testscore is greater than the amounts you've already covered.
Comment: +1 for just upper bounds check, if you already tested if something isn't `<= 10`, you don't have to check if it's `> 10` in `else` clause.
Comment: @Sinner: You need to post your code for us to know why it isn't working.  As pointed out in some other comments, your if/else statements fail to handle the case where testscore is less than 10 or between 31 and 40.  I've written a complete working program which demonstrates the simple use of if/else and posted it at http://pastebin.com/5J8PfDPj in the hopes that it will help demonstrate the proper use of if/else statements.
Comment: @Eli Thank you very much for all your help Eli, I see that the problem must be somewhere else in my code or there must be some sort of malfunction in the #includes maybe We will see. Again thank you for your time!
Comment: I tried it but still it doesnt cout anything of the studentmarks. (Exactly as written here just changed the ... to the cout command
Answer: == tests for equality, = assigns.
When you write studentmark == ( "failed" ); you are testing whether the string studentmark is equal to "failed", then throwing away the answer.
Answer: You need to assign value to studentmark like this:
studentmark = "hasteachersbook";

== checks if the value is equal. = assigns a value.
This should work. If not, the problem is elsewhere.
int testscore;
string studentmark;

if ( testscore  == 10 )
{
    studentmark = "failed";
}
else if ( testscore >= 11 && testscore <= 20 )
{
    studentmark = "closebutfailed";
}
else if ( testscore >= 21 && testscore <= 30)
{
    studentmark = "passed";
    }
else if ( testscore >= 31 && testscore <= 40 )
{
    studentmark = "excelent";
}
else if ( testscore >=41 )
{
    studentmark = "hasteachersbook";
}
else
{
    studentmark = "scoreLessThanTen";
}

Comment: I did that but still i get no cout value in this case hasteachersbook to be print out. I dont know why.
Comment: if `testscore` has a value `<10` or `(40,48)`, `studentmark` is never assigned a value.
Comment: could it be I need to add something else to the #include or change something at int main() ??
Answer: Your code doesn't work because you're attempting to do assignment with ==. There is no code in there that actually changes the value of studentmark.
Comment: so how can I change the value of studentmark? I changed it to
studentmark = "passed";
Comment: Yeah that will work. Like everybody else says, = is assignment and == is a comparison.
Answer: Looking at it, you have a case for 31-40, then 49 and above.
There is no case for 41-48.
I dont know if this is possible in C++, but maybe look into using CASE
Comment: It's possible, but with CASE he needs to specify all cases (`case 11:` `case 12:` `case 13` ...). CASE doesn't operate on ranges, just on values.
Comment: @Doomsknight: Then edit it out before someone downvotes you for it :P
Comment: AH right. i wasnt sure if it was possible at all, and I usually get downvotes for suggestions. :P  Yes, if it doesnt operate on ranges, I wouldnt recommend it as it would be a pain..
Answer: studentmark == ( "closebutfailed" ); does not assign the value "closebutfailed" into studentmark -- it does an equality comparison between "closebutfailed" and studentmark, which presumably returns false.
Change those to be assignment rather than comparison and try again.
Comment: I tried it but still it doesnt cout anything of the studentmarks :(
Comment: @Sinner: I'm not going to do your work for you. There are other problems with that code but that's the most obvious one. Have you tried stepping through the code in a debugger?
Answer: Your question seems to be "what if my value would be true for more than one of the tests in the if-else chain?"
C++ evaluates in textual order, i.e. from top-to-bottom.  Thus, the first predicate that is true for a given value, will be the branch selected.
For example:
int a = 2;

if (a > 0) {
  cout << "First branch";
} else if (a > 1) {
  cout << "Second branch";
}

Even though both tests would be true for a = 2, the first one is selected because it comes first.  Thus, First branch is printed out.
Answer: Software development is 1% inspiration and 99% debugging.  If you cannot debug, you cannot write software.
One often-used debugging technique - KISS:
Comment out or remove as much gunge as possible in an attempt to make a program actually do something.  When you get down to:
int testscore;
string studentmark;
        {
            studentmark == ( "failed" );
        }
cout << "Studentmark is:" << studentmark << endl;

..and still you're getting no studentmark output, it will surely dawn that your attempted assignment is not working and therefore almost certainly wrong, (as already explained by other posters, '==' != '=').
Practice/develop your debugging skills before posting here - you will be better off in the long run than just passing your trivial-but-non-working code to a load of experienced developers on a group and getting them to fix your bugs.


Why doesn't hook_preprocess_node() get triggered?

Question: I use the following code in a theme whose machine name is yokai.
// works like expected, output visible
function yokai_preprocess_html(&$variables) {
  dpm('yokai_preprocess_html');
  dpm($variables);
}

// does not work, no output visible
function yokai_preprocess_node(&$variables) {
  dpm('yokai_preprocess_node');
  dpm($variables);
}

Why doesn't hook_preprocess_node() get triggered?
Comment: Did you clear all caches? Btw, `dsm()` is just calling `dpm()`, there's no need to do the same thing twice. Just use `dpm()`. You can see the source [here](https://api.drupal.org/api/devel/devel.module/function/dsm/8).
Comment: just used both to see if either of them works. Rebuilt the cache several times with drush `dr cr`.
Comment: Strange; the code looks OK; there's nothing else that comes to my mind. Maybe someone else will be able to point you in the right direction. I would try to do this from another theme - even hack Bartik temporarily and see if `hook_preprocess_node()` works from there.
Comment: Only thing I can think of is either you are not printing the $messages, you misspelled the theme name.. try putting an exit in there and you'll know the code is being hit. I also recommend xdebug in instances just like this.
Comment: It looks like the above code. I copied it from my theme file. Therefore the misspelling can not be an issue and neither the $message because like mentioned above, the `dpm()`'s in `yokai_preprocess_html` get displayed, therefore called and output.
Comment: Apart from printing a debug message with `dpm()` what else are you doing to be sure Drupal is going to invoke that preprocess function? What page are you visiting? If it's a custom page, what code is that page executing?
Comment: Enable twig debugging and use a DOM inspector. Check if the node.html.twig is even being printed in the page.
Comment: It looks like this is by design and DS hijacks `HOOK_preprocess_node()` like described over [here](https://drupal.stackexchange.com/a/95626/3965). I assume this is still the case in Drupal 8?
Answer: The problem is with dpm(). This uses drupal_set_message(), which uses the session variable to store messages:
function dpm($input, $name = NULL, $type = 'status') {
  if (\Drupal::currentUser()->hasPermission('access devel information')) {
    $export = kprint_r($input, TRUE, $name);
    drupal_set_message($export, $type, TRUE);
  }
  return $input;
}

When the node template is processed, the page is already built with the session variables at this point. Any messages that come later will not make it on the page. In this case better use kint(). dpm() is more usefull for debugging code that doesn't produce a page output, like form validation.
Comment: DS is causing the not calling of `HOOK_preprocess_node`. Until I enable a Display Suite layout the HOOK gets called, but just after enabling the default One-Column layout `HOOK_preprocess_node` does not anymore get called
Comment: thanks for your answer, but unfortunately `kint()` does not work either. I tried to log if the `HOOK_preprocess_node` with `\Drupal::logger('theme')->notice('yokai_preprocess_node was called');` which does not work either therefore the HOOK never gets called. If I log `HOOK_preprocess_html` like that `\Drupal::logger('theme')->notice('yokai_preprocess_html was called');` everything works like expected and I can see the msg in the watchdog.
Comment: what could cause that `HOOK_preprocess_node` does not get called? Never occurred to me before.
Comment: I wanted to point out, that this is not easy to debug with dpm(). Other than that I could think of two reasons 1) the node is cached 2) the page has no node. Did you enable Twig debugging as suggested by Eyal? Then look, if there is `` in your html source.
Comment: Page is definitely a node and Twig debugging is on too.

Created a super basic new content type (only body field and no config) which does not use Display Suite nor Paragraphs (enabled for my other content types) and `HOOK_preprocess_node ` gets triggered and I can see the notice in the watchdog.

Now checking if DS or Paragraphs is causing this ...
Comment: DS brings its own templates: http://cgit.drupalcode.org/ds/tree/templates?h=8.x-2.3


Debug Exception Breakpoints in multiple sub packages

Question: I get the following error in my application:

Error has occured with message:
  [com.arjuna.ats.internal.jta.transaction.arjunacore.commitwhenaborted]
  [com.arjuna.ats.internal.jta.transaction.arjunacore.commitwhenaborted]
  Could not commit transaction.

Somewhere in my code I expect there is an exception being thrown that is being swallowed without re-throwing or printing the stacktrace and that marks my transaction as dirty. The set of code under suspicion is quite large (very large) so just stepping through it won't cut it.
Eclipse supports breaking whenever a exception is thrown, caught or uncaught. Problem is that I'm running in the context of JBoss which also throws exceptions. Is there a way with the exception filtering to tell Eclipse to only break on code that is in a certain package and its sub packages. The keyword here being sub packages.
I can't add just the packages I want because the list of packages is large. Hundreds of potential ones. All of our packages start with za.co so was wondering if there was a way to specify something like za.co.** which would match za.co and all of the sub packages.
Comment: If your going to downvote my question, please leave a comment suggesting on why and how to improve it.
Comment: I think it's a fine question. Don't know why it was downvoted.
Answer: In the Eclipse debug perspective, click the 'J!' button on the 'Breakpoints' view and type java.lang.Exception.
This will cause you to catch ALL exceptions, of course, so you can right-click the new breakpoint in the list and select 'Breakpoint properties'. In the filtering section, add a package filter.
Answer: So presumably you have already added an exception breakpoint.

In breakpoints window Right click the breakpoint
Select "Breakpoint properties"
Select Filtering
Click "Add Package"
Choose the package(s) you want to check in
Comment: Thanks TedTrippin. Yes I have done that already. Please see the updated question that is a little more specific to exactly what I'm after.
Comment: You should have really have had a try yourself, its what I did. Instead of "Add package" just use "Add" then you can specify "za.co.*" which means za.co and all sub packages. Dont forget to check the checkbox.


How can I use GeneralizedNewTypeDeriving to derive Vector and MVector?

Question: Near the top of the haddocks for Data.Vector.Unboxed, there is a discussion of how to use GeneralizedNewTypeDeriving to derive instances of Vector and MVector. The following example, edited to use LANGUAGE pragmas, is stated:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}

import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Unboxed as U

newtype Foo = Foo Int

newtype instance U.MVector s Foo = MV_Int (U.MVector s Int)
newtype instance U.Vector Foo = V_Int (U.Vector Int)
deriving instance M.MVector U.MVector Foo
deriving instance G.Vector U.Vector Foo
instance U.Unbox Foo

However, it does not type check, failing with a long message that begins
• Couldn't match representation of type: m Int
                           with that of: m Foo
    arising from a use of 'GHC.Prim.coerce'
  NB: We cannot know what roles the parameters to 'm' have;
    we must assume that the role is nominal
• In the expression:
    GHC.Prim.coerce
      @(U.MVector (Control.Monad.Primitive.PrimState m) Int
        -> Int -> m Int)
      @(U.MVector (Control.Monad.Primitive.PrimState m) Foo
        -> Int -> m Foo)
      (M.basicUnsafeRead @U.MVector @Int)
  In an equation for 'M.basicUnsafeRead':
      M.basicUnsafeRead
        = GHC.Prim.coerce
            @(U.MVector (Control.Monad.Primitive.PrimState m) Int
              -> Int -> m Int)
            @(U.MVector (Control.Monad.Primitive.PrimState m) Foo
              -> Int -> m Foo)
            (M.basicUnsafeRead @U.MVector @Int)

The example is somehow wrong or lacking, but I'm at a loss as to how to fix it.
I'll note that I can get this working quite easily with Data.Vector.Unboxed.Deriving (or by writing everything out manually):
derivingUnbox
  "Foo"
  [t|Foo -> Int|]
  [|\(Foo i) -> i|]
  [|Foo|]

My understanding of GeneralizedNewTypeDeriving is that it avoids the trivial application and removal of the constructor that I have to do in the above, so I'd like to be able to use it here if possible.
EDIT: Per request, I am using stack resolver lts-19.33, which is at ghc-9.0.2.
Comment: Well, type roles were introduced to distinguish when `coerce` is actually safe. Initially, GHC would allow some incorrect coercions (when a type variable changes that does affect the internal implementation), which was subsequently made impossible by tracking which type variables affect the implementation and which don't. That, however, meant that some code which didn't propagate this information stopped working: even if the coercions were correct, the compiler wasn't able to prove it and thus rejected the code. That was my guess for what's causing your problem, but I was wrong (see answer).
Comment: Might be helpful to specify the compiler version you're using. The vector docs probably refer to an older version that didn't take type roles seriously yet.
Comment: @leftaroundabout I've updated the answer. If you would, please clarify what you mean by "tak[ing] type roles seriously."
Answer: Recently, vector version 0.13.0.0 got a change that allows deriving using GeneralizedNewtypeDeriving with its classes (changelog). Indeed, before that, this just wasn't possible. Since you are using vector version 0.12.3.1 (via lts-19.33), the solution is to upgrade to the latest version.
Comment: I'll note for other stack users that there don't appear to be any snapshots as of this writing with vector higher than 0.12.3.1, including [nightly-2023-01-15](https://github.com/commercialhaskell/stackage-snapshots/blob/master/nightly/2023/1/15.yaml), so the only way to do this (that I'm aware of) with stack is to specify `vector-0.13.0.0` under `extra-deps` and possibly `allow-newer: true` and then cross your fingers and hope nothing breaks.


Distributing Microsoft.Office.Tools Dlls along with Office addins

Question: I wrote C# Office add-ins and I'm installing them manually by distributing them along with their assembly dependencies (Microsoft.Office.Tools.Common.v4.0.Utilities.dll and Microsoft.Office.Tools.Outlook.v4.0.Utilities.dll) and setting the proper registry entries for the add-ins.
I just wanted to verify that there is no legal limitation of distributing those two Microsoft DLLs along with my add-ins?
Answer: The short answer is yes, you can redistribute Microsoft Office Primary Interop Assemblies (PIA). The more solution developed using Microsoft Office, the more copies of Office is sold. You can find the EULA while installing PIA on one of the wizard pages.
In the image below is EULA for Microsoft Office 2010:

You can also take a different route, where you don't need to redistribute the PIA. Here is an excerpt from Microsoft Documentation:

If the project targets the .NET Framework 4 or later, the Embed Interop Types property for the assembly reference is set to True by default. By using this setting, your solution does not require the PIA on end-user computers.


Standard deviation in SERVQUAL

Question: I'm doing a project on measuring customer satisfaction using SERVQUAL. How do you calculate the standard deviation of each statement?
For example, if for one of the questions, there were:

2 respondents as strongly disagree (SD)
5 disagree (D)
20 neutral (N)
21 agree (A)
2 strongly agree (SA)
  (sample being 50)

How would you calculate the standard deviation if the scale were SD=1, D=2, N=3, A=4 and SA=5?
Also, how do you calculate the standard deviation for one dimension on the whole: e.g., the standard deviation for one of the dimensions in SERVQUAL say, Tangibles which has 4 statements or questions, and the standard deviation for Reliability which has 5 questions, etc.?
Comment: Regarding your second point, if you have an estimate of scale reliability (test-retest measurement, or internal consistency--i.e., Cronbach's alpha), it can be used to compute the [standard error of measurement](http://bit.ly/OQo7ZB) of your scale scores.
Answer: This is a Likert type scale and involves ordinal numbers and since intervals are not defined nor are ratios there is really not a meaningful concept for it.  However when scores are averaged there are models such as the Rasch model which allow these averages to be viewed as interval data.  I really know nothing about these models but Peter Flom and others at this site have discussed these ideas here yesterday and prior to that. Gung and Peter Flom provide some information on this at this question. Is 0 a valid value in a Likert scale?
If we accept that the average score is interval then the standard formula for the standard error of the mean could be applied to give you an estimate of the standard deviation for the mean.  I still would not think an standard deviation for the sample responses makes sense but you could calculate something that looks like a standard deviation by multiplying the standard error of the mean by square root of n where n is the number of independent responders.
Comment: Thank you for answering but are you saying that standard deviation can not be found out for this question only something that looks something like it can be?
Comment: I am saying that there is theory to support a standard error for the mean based on what others have said.  Conceptually I do not see that a standard deviation for the response distribution to individual questions make sense. All I meant by saying square root of n times the standard error looks like a standard deviation is that if you make the analogy to independent interval data the population standard deviation is root n times the standard error.  So it is possible to make that calculation and think of it like a standard deviation by analogy.
Comment: But conceptually it doesn't make sense to me. I would defer to @gung who seems to be much more well-versed in these types of analyses.
Comment: Actually it doesn't make sense to me either. But I noticed such analyses in some other projects for each individual statements and wondered how they did it.

Standard deviation in SERVQUAL


We have $f:R\rightarrow R$ continuous with $f(x+y)=e^{3xy}f(x)f(y)$ and $f(1)=e$. Find f.

Question:
We have $f:\mathbb{R}\rightarrow \mathbb{R}$ a continuous function
with $f(x+y)=e^{3xy}f(x)f(y)$ and $f(1)=e$, Find $f$.

I showed by induction that f is strictly positive on $\mathbb{N}$, then I showed again with induction that f is strictly positive on $\mathbb{Z}$. I don't know how to show f is strictly positive on $\mathbb{Q}$. If I can show that, by the density of $\mathbb{Q}$ in $\mathbb{R}$ we can say that $f\geq0$. But if f is 0 at some point then f is 0 at all points by the relation so we get a contradiction. So f is strictly positive on $\mathbb{R}$.
Now I will take the function $g=\ln(f)$, which is continuous.
We get the relation
$g(x+y)=3xy+g(x)+g(y)$
From here we get $g(x+1)=3x+1+g(x)$
We have $g(x+1)-g(x)=3x+1$
By iteration we get  $g(x+1)-g(x-(n+1))=\frac{(n+2)(3x-3n-2)}{2}$
The iteration I took looks very bad, so I don't have an idea right now. Can anyone help me with this problem?
Comment: You know from the term mixing ($3xy$) that the function in the exponent has to be nonlinear. Can you guess a nonlinear function that eats $x+y$ and spits out a term that looks like $xy$ (plus other terms)?
Comment: $h(x+y)=e^{(x+y)^{2}}$ ?
Comment: There you go, now play around with the scaling and translation to make it match the function in the problem.
Comment: I see $h(x+y)=e^{\frac{3}{2}(x+y)^{2}}$ have the same functional equation as $f$ but how this helps me to show that $f$ is strictly positive on $Q$?
Comment: The equation $g(x+1) -g(x) = 3x+1$  can be solved easily. $g(x)$ must be equal to $Ax^2 + Bx+ C$.
Comment: Which competition is it from?
Answer: I do not see why you struggled so much to prove that $f$ is positive on $\mathbb R$, unless you are missing a hypothesis. If $f(x)=0$ for some $x$, then for any $z \in \mathbb R$, simply taking $y=z-x$ in the equation gives $$
f(z)=f(y+x)=e^{3xy}f(x)f(y) = 0
$$
so that $f(z)=0$ identically. By the intermediate value theorem, $f$ is either positive or negative on $\mathbb R$. However, $f(1)>0$ so $f>0$ on $\mathbb R$, and $g = \ln f$ is well defined and satisfies
$$
g(x+y) = 3xy+g(x)+g(y)
$$
Note : If you want to alternately show that $f(z)$ is positive without using the intermediate value theorem (which uses continuity of $f$), then for any $z$, let $x=y=\frac z2$ in the functional equation to get $$
f(z) = e^{3z^2/4}f(z/2)^2
$$
must be non-negative for all $z$. Then the logic from my first proof above tells you that $f(z) \neq 0$ for any $z$, so the above automatically implies that $f(z)>0$ for all $z$,and hence $g(z) = \ln f(z)$ is well defined.
The advantage of the above approach is that continuity of $f$ is not required. In particular,

Suppose that $f$ satisfies $f(x+y)=f(x)f(y)e^{3xy}$ and $f$ is merely Lebesgue measurable. Then, $f(x) = \exp\left(\frac{3x^2-x}{2}\right)$ for all $x \in \mathbb R$.

The idea is that we will reduce this question to the Cauchy functional equation, and that has a solution just conditioned the function being Lebesgue measurable.

The quadratic guess was a good one. Basically, you need to know how to proceed from $$
g(x+y) = g(x)+g(y)+3xy
$$
A quick idea will tell you that if $g(a)=a^2$ was the case, then $g(a+b) = g(a)+g(b)+2ab$ would have been true. However, we have $3ab$ here which is a slight change, so what do we do?
The answer is to see that if $g(a) = ka^2$ for some $k$, then $$
g(a+b) = k(a+b)^2 = ka^2+kb^2+2kab = g(a)+g(b) + 2kab
$$
and our equation corresponds to $k = \frac 32$.
Since we worked backward to find this out, we haven't got a "proper" proof yet. To get that kind of a proof, start with $$
g(x+y) = g(x)+g(y)+3xy
$$
and let $h(a) = g(a) - \frac{3}{2}a^2$. Then, substituting this into this equation gives $$
h(x+y) = g(x+y) - \frac{3}{2}(x+y)^2 = g(x)+g(y) + 3xy - \frac{3}{2}(x+y)^2 \\ = g(x) - \frac{3}{2}x^2+g(y) - \frac{3}{2}y^2 = h(x)+h(y)
$$
which implies that $h(x+y) = h(x)+h(y)$ is a solution of the Cauchy functional equation, and since $f$ is continuous(or Lebesgue measurable), so is $h$. It follows that $h(x) = \alpha x$ for some $\alpha \in \mathbb R$. Going back, $$
g(x) = \frac{3}{2}x^2+\alpha x \implies f(x) = \exp\left(\frac{3}{2}x^2+\alpha x\right)
$$
However, we know that $f(1)=e = \exp(1)$, therefore $\frac 32 + \alpha = 1$ and hence $\alpha = -\frac{1}{2}$. All in all $$
f(x) = \exp\left(\frac{3x^2-x}{2}\right)
$$
is the answer.

There are two key parts of this answer. One is the identification of how one goes from the functional equation $g(x+y)=g(x)+g(y)+2xy$ to $g(x+y) = g(x)+g(y)+3xy$ using a "perturbation" , and the other is how rigorously this is brought back to the Cauchy functional equation via the function $h$, whose solutions are completely characterized under continuity. In isolation these are good tricks to know.
Comment: Thank you for all the clear explanations!
Comment: Another idea for positivity of $f$. Use $f(x) =f((x/2)+(x/2)) $ and this is non-negative.
Comment: @StefanSolomon Of course, you're welcome!
Comment: @ParamanandSingh That's right! I'll edit the post.
Answer: $\textbf{Aliter:}$
$f(x+y+z)=f(x)f(y+z)e^{3{x(y+z)}}=f(x)f(y)f(z)e^{3xy+3xz+3yz}$.
Induct to get $$f(x_1+x_2\dots +x_k)=e^{3(\sum\limits_{i\ne j} x_ix_j)}f(x_1)\dots f(x_k)$$
Set $k=n$, $x_i=\frac1 n \forall i$ to get $$f(1)=e^{3\frac{n(n-1)}{2n^2}}f\big(\frac{1}{n}\big).$$
Once you've found $f(1/n)$, we do this for $k=m$ and $x_i=\frac1 n\forall i$ to get $f(\frac m n)$ and conclude for the reals by continuity.


Guest VMs cant reach each other on Different ESXi Servers

Question: I have two vSphere EXSI 6 servers both setup with the same vSwitchs and connected to the same physical switches
Server 1:

eth0 => vlan143 (mapped to CORE/Management vSwitch)
eht1 => vlan140 (mapped to
SAT vSwitch)
eth2 => vlan141 (mapped to ACK vSwitch)

Server 2:

eth0 => vlan143 (mapped to CORE/Management vSwitch)
eht1 => vlan140 (mapped to SAT vSwitch)
eth2 => vlan141 (mapped to ACK vSwitch)

The problem I have is that the Guest VMs on Server 1 cant reach the Guest VMs on Server 2 which are all on the same vSwitches.  Both sets of Guests can reach servers that are on vlan143.
The NICs on each host connect to a single physical switch, this switch has the ports setup as access ports.
The two guest are running Windows Server 2008
There is not any VLAN Tagging enabled on the vSwitchs or host interfaces, as when I do connectivity completely breaks down.  The Physical switchs do have Vlans.
Appreciate any help or advice offered.
UPDATE 19 April 2016...
OK I think I have found the cause to this, I have noticed that some of the VM's on either ESXI server are not displaying their MAC address's when looking at the vSwitch overview see Screen Grabs Below.
VMServer 1 vSwitch
VMServer 2 vSwitch
Now I can reach the VMs from each server that are displaying the MAC addresses, but those that are not showing MACs cant reach the VMs on the other servers.  Any help greatly appreciated.
Comment: Is each vSwitch connected to a different pNIC on the host? Are the pSwitch ports configured for the correct VLAN's? Do you have inter-VLAN routing configured? Do the virtual machines have appropriate and correct ip addresses?
Comment: Yes each vSwitch is connected to a different NIC on the host.  The pSwitch ports are configured correctly for the vlans they should be.  Intervlan routing is not configured.  The VMs do have the correct IPs setup and are both on the correct Subnets.
Comment: It sounds like you're doing EST (External Switch Tagging). So a VM on Host 1 that is connected to a vSwitch that is connected to a pSwitch port that is an access member of VLAN 141 can't communicate to a VM on Host 2 that is connected to a vSwitch that is connected to a pSwitch port that is an access member of VLAN 141? How are the two switches connected? I'm assuming the switch to switch link is configured as a trunk port and that the relevant VLAN's are allowed?
Comment: Both Hosts are connected to the same switch (no redundancy in place just yet)
Comment: And to confirm, the hosts are connected to the correct pSwitch ports for the correct VLAN's? Are the pSwitch ports configured as access ports?
Comment: Correct ports, and configured as normal access ports.
Comment: OK. Sorry, more questions... the vSwitch port groups **DO** **NOT** have a VLAN configured, correct? The VLAN ID is set to None(0)? (sorry for the emphasis).
Comment: Thats no problem at all.  Correct they are set to **None(0)**.
Answer: Hmm, I'd say VLAN tag all the port groups and configure all the pSwitch ports as trunk, then there's no risk of traffic ending up in the wrong due to untagged traffic.
Are all other vSwitches set up like the examples above? Aka. tagged traffic from a port group exiting on a physical port?
Comment: Yes all vSwitches are configure the same way.
Comment: Okay, now I get what you're doing there, you're using the core VLAN143 as your management network at the same time, threw me off a bit.
Comment: What kind of pSwitches are you using? Could you post the configuration for the ports?
Comment: It should be something along these lines if it's Cisco:
´switchport mode access´
´switchport access vlan 143´
Comment: Please See UPDATE
Answer: So it turned out that the problem was being caused by the Windows Network Load Balancer, still not 100% sure why, but we disabling NLB everything started working.


Find the number of even factors of 126000

Question: What is an easy way to solve the problem? I can solve it by trying all possible even numbers, but I don't think it is a smart way.

Find the number of even factors of 126000.
Comment: prime factorization
Comment: An even factor of 126,000 is a factor of 63,000 multiplied by 2. So you are looking for the number of factors of 63,000.
Comment: Ain't that hard to factorise, given that there are already three trailing zeroes...
Answer: An even factor of 126,000 is twice a factor of $63,000=(2^3)(3^2)(5^3)(7^1)$.  Can you find the total number of factors id 63,000 from that prime factorization?  That will count the even factors of $63,000·2=126,000$.
Answer: $126000 = 2^4*3^2*5^3*7$
Every and only numbers of the form $2^i3^j5^k7^l$ where $0 \le i \le 4; 0 \le j\le2;0 \le k\le3 ;0\le l\le1$ are factors. To be an even factor $1 \le i \le 4$.
So there a $4$ possible powers of 2, $3$ possible powers of 3 ($0, 1,$ or $2$), $4$ possible powers of 5, and $2$ possible powers of 7.  Thats $4*3*4*2 = 96$ even factors.
===
or to see this clearly:
The only possible factors are: $(1|2|4|8|16)*(1|3|9)*(1|5|25|125)*(1|7)$.  That's $5*3*4*2$ possible factors.
The even factors are: $(2|4|8|16)*(1|3|9)*(1|5|25|125)*(1|7)$.  That's $4*3*4*2$ even factors.
Answer: $$
126000 = 2 \cdot 63 \cdot 1000
= 2\cdot 9 \cdot 7 \cdot 2^3 \cdot 5^3
= 2^4 \cdot 3^2 \cdot 5^3 \cdot 7
$$
An even divisor has the form
$$
2^{p_1} \cdot 3^{p_2} \cdot 5^{p_3} \cdot 7^{p_4}
$$
with
$$
p = (p_1, p_2, p_3, p_4) \in
\{ 1, \dotsc, 4 \} \times
\{ 0,\dotsc, 2 \} \times
\{ 0,\dotsc, 3 \} \times
\{ 0,\dotsc, 1 \}
$$
so there is at least one factor $2$ in its product.
There are $4 \cdot 3 \cdot 4 \cdot 2 = 96$ different choices for the powers $p$ and the same number of resulting even divisors.


AngularJS and Sidebar

Question: I'm very new to AngularJS and I'm trying to figure out the "best practices" method for including the navigation and sidebar.
I'm guessing the approach is similar to Worpdress.  I would  have a "header" file with content that is displayed on each page, and only call a sidebar (sidebar.html) when the template needs it.  At the moment I have a main.html file and I want to include a sidebar.
Should the the sidebar be a separate html file?  And how do I call that file when it is need?
Thanks in advance.
Answer: Pretty broad question but I'll give it a go.
Angular is built for SPA (Single Page Application). Therefore, you only really need one index page that will have a sidebar + header. Your content will be in separate template files that will be loaded by Angular's $route service.
Comment: Thanks for the help. I know it's a basic question, but the docs are not that easy to use. I'll look more into the $route service.  Thanks again!
Comment: No problem, angular has a steep learning curve but it's worth it. It forces you to use the right design principles which can be frustrating at times but it's worth it in the long-run.

AngularJS and Sidebar


Webform ID not shown in debug output?

Question: I created a new module to extend the webform module for custom submission hooks:
function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_213') {
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'mywebform_extra_submit_213');
    }
}

I have the webform module installed and I created a webform that has a node id of 213.
When I try to output the $form_id variable, the value shown is nothing indicative of a webform and instead showing "search_form_block" as the form ID?
what is the error here? I pulled it straight from this example.
Answer:
Install the Devel module.
Use the dpm() function, it will print out $form_id for all forms on any page you visit.
function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id);
}

Webform ID not shown in debug output?


Galera cluster implementation questions

Question: I've just successfully created my first Galera cluster using MariaDB 10.0.20 between three servers.
I have a few questions regarding my implementation:
 1. what will happen if one server becomes isolated from the other servers but still has clients connected?
 2. What happens if two servers can't directly communicate but the third server can talk with both servers?
 3. Is it possible to upgrade one server at a time?
 4. Is it possible to make configuration changes to one server at a time (e.g enabling query cache)
Answer:
what will happen if one server becomes isolated from the other servers but still has clients connected?

The isolated server becomes not read or writeable and will when the isolation ends get itself back in sync using one of the other nodes.

What happens if two servers can't directly communicate but the third server can talk with both servers?

Its likely that those two servers will isolate themselves (non-primary mode).

Is it possible to upgrade one server at a time?

yes. Wait until one is in sync before moving to the next.

Is it possible to make configuration changes to one server at a time (e.g enabling query cache)

Yes. Be careful about changing some of the setting related to galera as these may create a writeset that the other nodes can't understand.
Comment: Perfect, thanks for answering :)
Just curious, what do the timeout for Gallera do then? Does the server immediately become isolated or only after it times out?

Lets say we use: wsrep_provider_options = "evs.keepalive_period = PT3S;
      evs.suspect_timeout = PT30S;
      evs.inactive_timeout = PT1M;
      evs.install_timeout = PT1M"

What will happen before the timeouts are reached when there is an outage? Will the whole cluster lock?

Galera cluster implementation questions


Sql query where condition and or

Question: I have the following data in my table:
id: 1, name: TOM, visible: 1, field_1: EMPTY, field_2: EMPTY, field_3: EMPTY.
SELECT id, name FROM table
WHERE name <> 'TOM' AND visible = 1
      AND field_1 <> '' OR field_2 <> '' OR field_3 <> ''

I want to select only the rows where name is different than 'name1' and at least one of the fields is not empty.
I expected no results for this query but i get: id, TOM like the where name condition is overwritten.
Comment: Define "empty". Do you mean null, blank or literally the text "EMPTY"?
Comment: Can you provide sqlfiddle with your data
Comment: blank field, field_1 2 and 3 are varchars. pardon
Answer: Your problem is precedence: bracket the ORs:
SELECT id, name
FROM table
WHERE name <> 'TOM'
AND visible = 1
AND (field_1 <> '' OR field_2 <> '' OR field_3 <> '')

Answer: The and operator has a higher precedence than or (see the documentation for extra details), so if we take your query:
SELECT id, name FROM table
WHERE name <> 'TOM' AND visible = 1
      AND field_1 <> '' OR field_2 <> '' OR field_3 <> ''

And add clarifying parentheses, we'll get:
SELECT id, name FROM table
WHERE (name <> 'TOM' AND visible = 1 AND field_1 <> '')
      OR field_2 <> ''
      OR field_3 <> ''

Which is not what you wanted. You can solve this by explicitly adding parentheses:
SELECT id, name
FROM   table
WHERE  name <> 'TOM' AND
       visible = 1 AND
       (field_1 <> '' OR field_2 <> '' OR field_3 <> '')

Answer: I suspect, that one of the field is really != '', making the condition valid for "Tom" record. You must group OR conditions, using brackets:
SELECT id, name FROM table
WHERE name <> 'TOM' AND visible = 1
      AND (field_1 <> '' OR field_2 <> '' OR field_3 <> '')

Answer: You should add ()
SELECT id, name
FROM    table
WHERE name <> 'TOM'
AND visible = 1
AND (field_1 <> ''OR field_2 <> '' OR field_3 <> '')

Answer: Please enclose empty fields comparison in one paranthesis block as show in bold
SELECT id, name FROM table
WHERE name <> 'TOM' AND visible = 1
      AND  (  field_1 <> '' OR field_2 <> '' OR field_3 <> ''  )
Answer:
You have to insert brackets
Are the empty fields really empty? Maybe the '' doesn't bring the right results

Sql query where condition and or


Loss of precision converting 'float' to NSNumber, back to 'float'

Question: I seem to be encountering a strange issue in Objective-C converting a float to an NSNumber (wrapping it for convenience) and then converting it back to a float.
In a nutshell, a class of mine has a property red, which is a float from 0.0 to 1.0:
@property (nonatomic, assign) float red;

This object is comparing itself to a value that is loaded from disk, for synchronization purposes. (The file can change outside the application, so it checks periodically for file changes, loads the alternate version into memory, and does a comparison, merging differences.)
Here's an interesting snippet where the two values are compared:
if (localObject.red != remoteObject.red) {
    NSLog(@"Local red: %f Remote red: %f", localObject.red, remoteObject.red);
}

Here's what I see in the logs:
2011-10-28 21:07:02.356 MyApp[12826:aa63] Local red: 0.205837 Remote red: 0.205837

Weird. Right? How is this piece of code being executed?
The actual value as stored in the file:
...red="0.205837"...

Is converted to a float using:
currentObject.red = [[attributeDict valueForKey:@"red"] floatValue];

At another point in the code I was able to snag a screenshot from GDB. It was printed to NSLog as: (This is also the precision with which it appears in the file on disk.)
2011-10-28 21:21:19.894 MyApp[13214:1c03] Local red: 0.707199 Remote red: 0.707199

But appears in the debugger as:

How is this level of precision being obtained at the property level, but not stored in the file, or printed properly in NSLog? And why does it seem to be varying?
Comment: Are you converting it to/from a string at any point?  If so, use `%+0.16f` instead of `%f`.  Or whatever precision you want instead of `.16`.  If not, disregard this comment ).
Comment: Might have found something here, but it didn't pop up in any previous searches unfortunately: http://stackoverflow.com/questions/5024913/issue-with-float-and-double-data-types-in-objective-c/5025021#5025021
Comment: Yea, I'm absolutely converting it to/from an NSString. I had assumed though, that creating it: **[NSString stringWithFormat:@"%f", 0.707199f]** then converting it like: **[... floatValue]** would result in the same value. I guess not. Thanks for the tip, I imagine that will clear things up. Feel free to post it as an answer.
Comment: Cool, let me know though if that doesn't fix it so I can delete my answer ).  Hope it helps though.
Comment: To be clear - does that **+0.16** precision round to the nearest 0.16? (Eg. would it round 0.35 to 0.32?) I found an example here, but it isn't really explained, under **Formatting Basics**: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html
Comment: If the number is originaly `3.14159` exactly, the string would be `@"3.14159"` (using "%0.16f"), but if you had "%0.4f", then it would round to `@"3.1416"`.
Comment: I'm having trouble seeing the link between the precision in the formatting string, and the precision that results in the returned float value. Sorry if I'm being dense. :)
Comment: @MJD has a good explanation in his answer for the *why* part of your question.
Comment: @craig -- Look up "printf formatting" on the web.  %0.16f means that 16 digits of fraction (to the right of the decimal point) should be printed.  The "0" means that the overall field is AT LEAST zero spaces wide, but the overall field size will always accommodate all the fraction digits plus whatever integer (to the left of the decimal point) digits are needed to represent the number.  A %5.2f field would represent 9.8765 as " 9.88" with the leading blank to make the field the required 5 characters wide.
Comment: @DanielRHicks Perfect, that explains it very well. Thanks!
Answer: If you are converting it to/from a string at any point try using %0.16f instead of %f (or whatever precision you want instead of .16).
For more info, see IEEE Std formatting.

Also, use objectForKey instead of valueForKey (valueForKey is not intended to be used on dictionaries):
currentObject.red = [[attributeDict objectForKey:@"red"] floatValue];

See this SO answer for a better explanation of objectForKey vs valueForKey:
Difference between objectForKey and valueForKey?
Comment: Thanks, that works! Also thanks for the objectForKey: note, I usually keep a closer eye on those things.
Comment: @craig Np, glad I could help!
Answer: The problem your are experiencing is a problem with floating point.  A floating point number doesn't exactly represent the number stored (except for some specific cases which don't matter here).  The example in the link craig posted is an excellent example of this.
In your code, when you write out the value to your file you write an approximation of what is stored in the floating point number.  When you load it back, another approximation of it is stored in the float.  However these two numbers are unlikely to be equal.
The best solution is to use a fuzzy comparison of the two floating point numbers.  I'm not an objective c programmer, so I don't know if the languages includes builtin functions to preform this comparison.  However this link provides a good set of examples on various ways to preform this comparison.
You can also try the other posted solution of using a bigger precision to write out to your file, but you will probably end up wasting space for the extra precision that you don't need.  I'd personally recommend you use the fuzzy comparison as it is more bullet proof.
Answer: You say that the "remote" value is "loaded from disk".  I'm guessing that the representation on disk is not an IEEE float bit value, but rather some sort of character representation or some such.  So there are inevitable conversion errors going to and from that representation, given the way IEEE float works.  You will not get an exact result, given that there's only about 6 digits of decimal precision in a float value, but it rarely maps to exactly 6 decimal digits but instead is sort of like representing 1/3 in decimal -- there is no exact mapping.
Answer: Read this: http://floating-point-gui.de/
Comment: While this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


How can I schedule a server restart from command line on Windows 2012?

Question: I would like to schedule a one-time server restart, e.g. to finish installing updates early in the morning. How can I do this from the command line on Windows 2012?
On Windows 2008, I would have used the at command,
at 2am shutdown -r -f -c "restart"

and taken the rest of the afternoon off.
But on Windows 2012, running this command tells me that
The AT command has been deprecated. Please use schtasks.exe instead.

So the equivalent command with schtasks.exe might be
schtasks /create /sc once /tn restart /tr "shutdown - r -f ""restart""" /st 02:00

Apart from being very forgettable, this command has another important downside: it schedules the task for 2am today—not much use unless I'm awake at 1am to run it.
According to the help for schtasks.exe, the /sd switch for setting the start date is not applicable with /sc once. So even if I wanted to type out tomorrow's date in mm/dd/yyyy format—and I don't—I can't do this.
The only possible solution I've found is here, where Kevin Traas suggests creating batch file to create a scheduled task just before midnight that waits for a couple of minutes and then creates another scheduled task to run the command that you actually want to run. Clever, but nowhere near as convenient as at.
Comment: This is just total stupidity to replace AT with unusable schtasks. Why they couldn't make both? Jerks!
Comment: @Lijo that link doesn't contain any information about how to schedule a restart.
Answer: The shutdown command itself has a delay parameter /t that delays a shutdown for a number of seconds up to 10 years.  If you want to schedule a shutdown in 14 hours, say, you might run
shutdown /r /t 50400

You might also add a reason with the /d parameter or a comment with /c; run shutdown /? for details.
Answer: Despite the documentation, the /SD parameter seems to be compatible with the /SC ONCE.  The task is successfully created to run on the date provided, at the time provided. (Tested on W8 and W7)
Additionally, the XP documentation for schtasks.exe goes so far as to say the /SD parameter is required when using /SC ONCE, so I imagine there are a fair number of scripts using the combination.
Example:
C:\Users\Mitch>schtasks /create /sc once /tn restart /tr "shutdown -r -f ""restart""" /st 23:00 /sd 2013-06-13
SUCCESS: The scheduled task "restart" has successfully been created.

C:\Users\Mitch>

If going against the documentation does not sit well with you, consider generating the XML file directly (schema is here), which is definitely supported and definitely supports a task scheduled to run once on a future date.  An easy way to get the proper file is to create it in the Task Scheduler mmc snap in and use the export command.
Example:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2013-06-12T21:20:51.004181</Date>
    <Author>FOOBAR\Mitch</Author>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <StartBoundary>2013-06-13T22:20:29</StartBoundary>
      <Enabled>true</Enabled>
    </TimeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>FOOBAR\Mitch</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>Your command here</Command>
    </Exec>
  </Actions>
</Task>

Command to import:
schtasks /CREATE /TN "Task Name" /XML filename.xml

Comment: Hmm... I additionally tested Server 2008 SP2 and Server 2008 R2 without issue.  I will note that the date format is based off of your local date/time format, and leading zeroes are required.  In the default EN-us install, this would lead to formatting like `/SD 06/14/2013`.
Comment: Thanks for the tip about `/sd` being supported. That's interesting about the XML import too—although personally I don't care about going against the documentation. So at least this is possible—just much, much more difficult than it used to be with `at`.
Comment: Mildy interesting: `/sd` doesn't work with `/sc once` on Windows Server 2008. It results in `ERROR: Incorrect Start Date.`
Answer: I ended up creating runat.ps1 to replicate some of the simple features of at, incorporating the wisdom from Mitch's answer.
The syntax is runat (time) (command), e.g.
runat 2am shutdown -r -f -c "restarting the server"
runat 10:15 msg * it`'s 10:15 everyone!

If you, too, are nostalgic for the good old days when you didn't have to type...
schtasks /create /ru system /rl highest /sc once /tn restart /tr shutdown -r -f -c \"restarting the server\" /st 02:00 /sd 06/15/2013

... then you can install it by running this powershell command:
iex (new-object net.webclient).downloadstring('https://gist.github.com/lukesampson/5779205/raw/install.ps1');install runat https://gist.github.com/lukesampson/5778559/raw

Or you can manually download runat.ps1 script here.
Comment: +1 That is a very helpful script... this is definitely going in my favorites.
Answer: I used this in a script for 2012 R2 and works nicely;
It will create a daily task that restarts the server @ 4:30am
schtasks /create /ru system /rl highest /sc DAILY /tn restart /tr "shutdown /r /f /c "Restarting" /st 04:30

Please make sure that you run this from a CMD prompt with Administrative privileges.
Andy
Answer: Just another powershell script to programatically reboot the computer the next day at specified time
$tomorrowDate = (get-date).AddDays(1).ToString("dd/mm/yyyy")

schtasks /delete /tn restart /f
schtasks /create /sc once /ru MyDomain\administrator /rp /tn restart /tr "shutdown -r -f" /st 07:13 /sd $tomorrowDate

Answer: I suggest using the schtasks command with the /f parameter.
Using /f, if there is a task with the same name, it's modified.
It's very useful for deploy tasks via scripting.
A full example of a schedule server restart:
schtasks /create /ru system /rl highest /sc DAILY /tn Reinicio /tr "shutdown /r /f /t 0 /c "Reinicio"" /st 22:30 /F

Extracted from: http://www.sysadmit.com/2016/09/windows-programar-apagado-o-reinicio-automatico.html
Answer: If the goal is simply to reboot after installing updates, then you can use the PSWindowsUpdate module to install the updates.  You can download it from here. Once installed, just open Powershell and type
Get-WuInstall -AcceptAll -AutoReboot

Answer: This  script lets you schedule the Restart of multiple servers at a specific date / time.
https://gallery.technet.microsoft.com/Schedule-restart-of-2c1131fb?redir=0


Building Tree Structure from a list of string paths

Question: I have a list of paths as in
paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6", ...]

where the actual length of the list if roughly 20,000. I want to construct a tree structure that can be printed. The tree structure would look something like this:
x1
├── x2
│   └── x3
├── x4
└── x5
    └── x6

I also want to have some data associated to each node in the Node Object that can be currently accessed through a dictionary where each node is a key e.g.
d = {"x1": [[1,2], [3,4]], "x2": [[5,6], [7,8]], ...}

Every tree node should inherit the data from its parent. Such that the data at the "x2" node would be [[1,2], [3,4], [5,6], [7,8]].
I have tried the module anytree but it requires that you define each node of the tree as a variable. Any ideas? Thanks in advance!
Comment: Well, it would help if you show how the "tree" appears when printed.
Comment: I've changed my solution. It might save you a lot of if-else if you specify a root. I assume that `x1` is the root.
Comment: Edited the post showing tree structure now.
Answer: If I understand your question correctly, one possible solution might be like this.
The tree nodes store their parents in order to construct the messy ├───
and └─── before directory/file names.
Output:
x1
├── x2
│   └── x3
├── x4
└── x5
    └── x6

Code:
class TreeNode:
    def __init__(self, name, parent):
        self.parent = parent
        self.name = name
        self.children = []

    def add_child(self, node):
        self.children.append(node)
        return node

    def print(self, is_root):
        pre_0 = "    "
        pre_1 = "│   "
        pre_2 = "├── "
        pre_3 = "└── "

        tree = self
        prefix = pre_2 if tree.parent and id(tree) != id(tree.parent.children[-1]) else pre_3

        while tree.parent and tree.parent.parent:
            if tree.parent.parent and id(tree.parent) != id(tree.parent.parent.children[-1]):
                prefix = pre_1 + prefix
            else:
                prefix = pre_0 + prefix

            tree = tree.parent

        if is_root:
            print(self.name)
        else:
            print(prefix + self.name)

        for child in self.children:
            child.print(False)

def find_and_insert(parent, edges):
    # Terminate if there is no edge
    if not edges:
        return

    # Find a child with the name edges[0] in the current node
    match = [tree for tree in parent.children if tree.name == edges[0]]

    # If there is already a node with the name edges[0] in the children, set "pointer" tree to this node. If there is no such node, add a node in the current tree node then set "pointer" tree to it
    tree = match[0] if match else parent.add_child(TreeNode(edges[0], parent))

    # Recursively process the following edges[1:]
    find_and_insert(tree, edges[1:])

paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6"]

root = TreeNode("x1", None)

for path in paths:
    find_and_insert(root, path.split("/")[1:])

root.print(True)

Comment: Thanks for the answer! Could you please give a bit of an explanation for the find_and_insert() function? I am trying to implement some data in each node that is inherit from the parent (see last edit) with your class..
Comment: @CosmicPeanutButter I added some comments. Basically `find_and_insert(parent, list_of_names)` tracks down the `list_of_names` from the tree node `parent`, and inserts a new node at the appropriate location if necessary.
Comment: @CosmicPeanutButter I forgot to mention. Since the tree has its parent stored, you can traverse upwards to get the associated data in each node.
Answer: bigtree is a Python tree implementation that integrates with Python lists, dictionaries, and pandas DataFrame.
For this scenario, there are three parts to this,

Define a new Node class that does the inheritance of data from parent nodes
Construct tree using the path list and Node class we defined earlier (1 line of code!)
Add in the data dictionary that maps the node name to data (1 line of code!)

from bigtree import Node, list_to_tree, print_tree, add_dict_to_tree_by_name

# Define new Node class
class NodeInherit(Node):
    @property
    def data(self):
        if self.is_root:
            return self._data
        return self.parent.data + self._data

# Construct tree using the path list
paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6"]
root = list_to_tree(paths, node_type=NodeInherit)

# Add in the data dictionary
d = {"x1": [[1,2], [3,4]], "x2": [[5,6], [7,8]], "x3": [[9]], "x4": [[5,6]], "x5": [[5]], "x6": [[6]]}
d2 = {k: {"_data": v} for k, v in d.items()}  # minor input format change
root = add_dict_to_tree_by_name(root, d2)

# Check tree structure with data
print_tree(root, attr_list=["data"])

This results in output,
x1 [data=[[1, 2], [3, 4]]]
├── x2 [data=[[1, 2], [3, 4], [5, 6], [7, 8]]]
│   └── x3 [data=[[1, 2], [3, 4], [5, 6], [7, 8], [9]]]
├── x4 [data=[[1, 2], [3, 4], [5, 6]]]
└── x5 [data=[[1, 2], [3, 4], [5]]]
    └── x6 [data=[[1, 2], [3, 4], [5], [6]]]

You can also export the data out to dictionary or pandas DataFrame format besides printing it out to console.
Source/Disclaimer: I'm the creator of bigtree ;)


Is there a way to get the active user permissions for a specific Azure Devops Git Branch, using REST API?

Question: I've experimented several ways, but I failed to find how to solve my problem.
Before starting an heavy process, I'd like to check if the use has proper rights to do it, for instance the "Force Push" permission.
For instance are there some undocumented parameters on this one to be more specific (at Git branch level instead of global permissions at organisation level) ?
GET https://dev.azure.com/{organization}/_apis/permissions/{securityNamespaceId}/{permissions}?api-version=7.0

Checking and changing the branch Policies works fine, but I'm stuck to retrieve Permissions of the current User.
Any help would be very welcome, thanks.
I've tried for instance:
<code>https://dev.azure.com/{organisation}/_apis/permissions/2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87/128?api-version=7.0 => global, not specific for a branch
https://dev.azure.com/{organization}/_apis/permissionsreport/2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87?api-version=7.0 => global, not specific for a branch
</code>
This page look very promising, but is missing petinent example or detailed explanations on how to do. https://learn.microsoft.com/en-us/rest/api/azure/devops/permissionsreport/?view=azure-devops-rest-7.0
Permissions reports can help administrators determine the effective permissions of users and groups upon securable resources in Azure DevOps. Generating a report for a resource (Git repository, branch, etc.) will list the effective permissions, upon that resource, for each user who has logged into the Azure DevOps organization and each group in the Azure DevOps organization.
=> Great, but how to do that?
Answer: After quite a lot of experimentations, we found out the way to do it.
In order to get the permission for a given Git branch, you have to use the poorly documented Tokens parameter on the url.
https://dev.azure.com/{organization}/_apis/permissions/{securityNamespaceId}/{permissions}?tokens=repoV2/{Project}/{RepositoryId}/refs/heads/{Branche}&api-version=7.0
Where Project is the guid for your project
RepositoryId is the Guid of your repository
And Branch is the hexa-encoded name of your branch.


Decomposition of a self-adjoint matrix

Question: Consider a self-adjoint complex matrix $A$. We are given a particular orthonormal basis $\{e_i\}$ such that $A$ can be written as $A = \sum_{i,j} \alpha_{ij}\, e_i e_i^*$ with all $\alpha_{ij} \geq 0$.
Does this necessarily mean that there exist vectors $\{x_j\}$ of the form $x_j = \sum_i \lambda_{j,i}\, e_{j,i}$ with coefficients $\lambda_{j,i} \geq 0$ in the same basis, such that
$$A = \sum_{i} \mu_i \,x_i x^*_i $$
with $\mu_i \geq 0$? The converse implication can easily be seen to be true, but I wasn't able to show this one.
Answer: No. Take $A=\left(\begin{smallmatrix}1&1\\1&0\end{smallmatrix}\right)$. Then $A$ is self-adjoint and each of its entries is greater than or equal to $0$. But one of its eigenvalues is smaller than $0$.
Comment: Thank you! Does the statement hold for positive semidefinite $A$, then?
Comment: @Luc Yes, it does.
Comment: Would you mind providing a quick proof? I still don't quite see it, even if I assume positive semidefiniteness.
Comment: @Luc It follows from the [spectral theorem](https://en.wikipedia.org/wiki/Spectral_theorem) and the definition of semidefinite positive.
Comment: How does it follow that all of the coefficients of the vectors $\{x_j\}$ are non-negative? I'm sorry if I'm being stupid about this!
Comment: @LucI was talking about the $\mu_i$'s. Wasn't your question about them?
Comment: I need both the $\mu_i$ and the coefficients $\lambda_{j,i}$ for each vector to be non-negative.
Comment: @Luc If the matrix is positive semidefinite, then the $\mu_i$'s will be $\geqslant0$, but not, in general, the $\lambda_{j,i}$'s.
Answer: The matrices for which such a decomposition exists are called completely positive. If the size if the matrix is larger than $4 \times 4$ then the things get more interesting. You can find relevant papers online.

Decomposition of a self-adjoint matrix


Cypress cucumber tests not working in GitHub Actions

Question: All the tests run successfully locally with the command npx cypress run. But the same tests fail in GitHub Actions with this error:

AssertionError: Timed out retrying after 4000ms

Appreciate your help. Please find the workflows yml file below:
name: E2e Tests
on: [push]
jobs:
  cypress-run:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Cypress run
        uses: firstname.lastname@example.com
        env:
          DEBUG: "cypress:*"
        with:
          # start: npm start
          command: npx cypress run
          # command: npx cypress run --browser chrome --spec 'cypress/e2e/**/*.feature'

Dependencies:
{
    "devDependencies": {
        "@badeball/cypress-cucumber-preprocessor": "^17.0.0",
        "@bahmutov/cypress-esbuild-preprocessor": "^2.2.0",
        "@cypress/xpath": "^2.0.3",
        "cypress": "^12.11.0",
        "cypress-cucumber-attach-screenshots-to-failed-steps": "^1.0.0",
        "cypress-cucumber-preprocessor": "^4.3.1",
        "multiple-cucumber-html-reporter": "^3.4.0",
        "ts-loader": "^9.4.2",
        "typescript": "^4.5.2"
      }
}

Answer: Are you having this issue anymore ? Why explicitly launching with "command: npx cypress run" if you use the firstname.lastname@example.com. In my case only put the snippet below will make it:
  - uses: actions/checkout@v3
  - uses: cypress-io/github-action@v5
    with:
      build: npm run build
      start: npm start


How to find a string in char Array without using string functions?(c++)

Question: I have following code:
char x[30]="computer";
char y[30]="put";

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.
Comment: `std::strstr` or `std::search` might be useful.
Comment: Use std::string, not char arrays!
Answer: Library function(c++ style)
std::string a = "computer", b = "put";
bool found = a.find(b) != std::string::npos;

Without Library function(c style)
I assume you don't hope to get terrible complexity, so KMP is what you are looking for.
Answer: In C++ you could use strings and string::find
With char arrays tho,
if (strstr(x, y) != NULL) {
    // contains
}

Answer: In C++ you have the find method on string :
 std::string str ("computer"); std::string str2 ("put");

 std::size_t found = str.find(str2);

if found = -1, 2nd string isn't in first.
http://www.cplusplus.com/reference/string/string/find/
Answer: Since you are using C++ you can use std::string:
#include <string>
#include <iostream>

const std::string stringToSearch("computer");
const std::string stringToFind("put");

if (stringToSearch.find(stringToFind) == std::string::npos) {
    std::cout << "not found\n";
} else {
    std::cout << "found \n";
}


Geometry and Physics

Question: I have to do a presentation on Geometry and Physics. I am asking it here (rather than physics.se) because I have to focus on Geometry More than Physics.
The intended audience is Undergraduate Seniors who have experience with Algebra (Linear/Abstract), Point Set Topology and everything that is usually taken before these courses but no more topics like differential geometry.
The presentation can lasts 30 minutes.
I want to make it more accessible, so it has to be broad, and not specialized. e.g. history, fields, major contributions etc are more welcome than specific theorems or examples. Of course, I would love many examples but I will focus on them at introductory level.
I am looking for topics but more than that, resources.
Comment: I find the tagging misleading: You have tagged with differential-geometry and algebra-topology but we are not allowed to use those things?
Comment: Possibly do an overview of some of the more complicated concepts they might not have come up with on their own? Symplectic geometry, Fiber bundles, and that sort of thing? Do diagrammatic calculi count as geometry? Road to Reality has a good amount of this sort of thing.
Answer: Chapter 1 of John Lee's Introduction to Topological Manifolds talks about how manifolds are used in classical mechanics, general relativity and string theory to whet your appetite for more. It is available as a free sample.
Answer: If you have access to journals through your library, the "Journal of Geometry and Physics" may give a good insight and examples.
A couple of potentially useful book resources are "Mathematical Physics, Analysis and Geometry" (deMonvel and McKean) and "The Geometry of Physics:
An Introduction" (Frankell, 2004).
I hope this helps
Answer: I'm not sure if this will help but I'll suggest some books that uses Differential Geometry in Physics. Of course, I'm not suggesting you to read them completely, it would take a lot of time, so the idea is that you just take a look on the books, see the main subjects being tackled and them see what they say about those specific subjects that you are interested in. From there you can have ideas on how to build your presentation.
The classic example of how Differential Geometry can be used in Physics is certainly General Relaitivity. So you talk a little bit about that, perhaps if you don't want to go into theoretic details, you can talk just a little bit about the history of how General Relativity developed needing Differential Geometry to succesfully model gravitation. A good place to look at this and see interesting results is the book "Semi-Riemannian Geometry" by Barret O'neill.
Also there's Michael Spivak "Physics for Mathematicians: Mechanics I". This book one part devoted to the Lagrangian Mechanics and another part devoted to Hamiltonian Mechanics. Since Spivak assumes the reader knows Differential Geometry he uses many constructions of manifolds to develop those ideas. You can take a look on the content there to see if you get good ideas  to relate geometry to mechanics in your presentation.
Finally there's a book by the Brazilian Physicist Waldyr Alves Rodrigues Jr that talks about relationships between Maxwell, Einstein and Dirac equations. This book uses many differential geometry constructions to relate those equations. The book is called "The Many Faces of Maxwell, Dirac and Einstein equations."
These of course are places that have in depth treatment of the subjects you are interested to present. It would require you to search inside the books to see which subjects you want to present and how deep you want to go.
I hope this helps you somehow. Good luck with you presentation!

Geometry and Physics