How do you calculate precision and recall for multiclass classification using confusion matrix?

Question: I wonder how to compute precision and recall using a confusion matrix for a multi-class classification problem. Specifically, an observation can only be assigned to its most probable class / label. I would like to compute:

Precision = TP / (TP+FP)
Recall = TP / (TP+FN)

for each class, and then compute the micro-averaged F-measure.
Comment: find the answer here. Very good explanation https://www.youtube.com/watch?v=FAr2GmWNbT0
Comment: The Compumine link is dead.
Comment: This [docx](http://www.cs.odu.edu/~mukka/cs795sum10dm/Lecturenotes/Day4/recallprecision.docx), *Evaluating a classification model – What does precision and recall tell me?*, from [Compumine](http://www.compumine.com/) provides a simple introduction to the confusion matrix and the measures derived from it. It helps to create the confusion matrix, precision, recall, specificity and accuracy.
Comment: For multiclass case, what I understand that along the rows (axis=0) is the recall and along the columns (axis=1) is the precision. https://rxnlp.com/computing-precision-and-recall-for-multi-class-classification-problems/#.XJobF6Qo_IU
Answer: In a 2-hypothesis case, the confusion matrix is usually:

Declare H1
Declare H0

Is H1
TP
FN

Is H0
FP
TN

where I've used something similar to your notation:

TP = true positive (declare H1 when, in truth, H1),
FN = false negative (declare H0 when, in truth, H1),
FP = false positive
TN = true negative

From the raw data, the values in the table would typically be the counts for each occurrence over the test data.  From this, you should be able to compute the quantities you need.
Edit
The generalization to multi-class problems is to sum over rows / columns of the confusion matrix.  Given that the matrix is oriented as above, i.e., that
a given row of the matrix corresponds to specific value for the "truth", we have:
$\text{Precision}_{~i} = \cfrac{M_{ii}}{\sum_j M_{ji}}$
$\text{Recall}_{~i} = \cfrac{M_{ii}}{\sum_j M_{ij}}$
That is, precision is the fraction of events where we correctly declared $i$
out of all instances where the algorithm declared $i$.  Conversely, recall is the fraction of events where we correctly declared $i$ out of all of the cases where the true of state of the world is $i$.
Comment: sry, could you explain your idea more clearly?
Comment: In my case, there are 10+ classes, so I guess the FN will mean the total count of declare class H(i), i != 1; and the same is FP?
Comment: Hi, I wonder what the values will be for the Precision and Recall, if TP+FP=0, and TP+FN=0 for some actual class in the confusion matrix.
Comment: The precision for class `i` is undefined if there are no instances where the algorithm declares `i`.  The recall for class `i` is undefined if the test set does not include class `i`.
Comment: My final goal is calculate the Macro F Measure, so I need precision and recall values for each class i; so how can I compute the Macro-F measure if the above two cases appear in some class i? In particular, what's the value for Fi, and does class i count as one of the classes M, that the number of elements in M will be count as the denominator of the formula for calculating Macro F measure.
Comment: I tend to you Bayesian logic, so I'd posit an a priori estimate; maybe the some sort of typical behaviour on your other classes.  Another, worst case, approach is to derive the precision and recall values for an algorithm that just randomly guesses.
Comment: The worst case precision and recall is $1/N_{classes}$  -- this is what you'd get if your algorithm just guessed uniformly.
Comment: I usually use Kappa coefficient for multiclass classification.
Comment: Calculating Precision is similar to calculate mean accuracy of each class for 10 experiments?
Answer: Good summary paper, looking at these metrics for multi-class problems:

Sokolova, M., & Lapalme, G. (2009). A systematic analysis of performance measures for classification tasks.  Information Processing and Management, 45, p. 427-437.  (pdf)

The abstract reads:

This paper presents a systematic analysis of twenty four performance
  measures used in the complete spectrum of Machine Learning
  classification tasks, i.e., binary, multi-class, multi-labelled, and
  hierarchical. For each classification task, the study relates a set of
  changes in a confusion matrix to specific characteristics of data.
  Then the analysis concentrates on the type of changes to a confusion
  matrix that do not change a measure, therefore, preserve a
  classifier's evaluation (measure invariance). The result is the
  measure invariance taxonomy with respect to all relevant label
  distribution changes in a classification problem. This formal analysis
  is supported by examples of applications where invariance properties
  of measures lead to a more reliable evaluation of classifiers. Text
  classification supplements the discussion with several case studies.
Comment: Welcome to the site, @JamesTaylor. Would you mind giving a summary of the info in the linked paper to help readers decide whether it's what they need & in case the link goes dead?
Answer: Using sklearn or tensorflow and numpy:
from sklearn.metrics import confusion_matrix
# or:
# from tensorflow.math import confusion_matrix
import numpy as np

labels = ...
predictions = ...

cm = confusion_matrix(labels, predictions)
recall = np.diag(cm) / np.sum(cm, axis = 1)
precision = np.diag(cm) / np.sum(cm, axis = 0)

To get overall measures of precision and recall, use then
np.mean(recall)
np.mean(precision)

Answer: @Cristian Garcia code can be reduced by sklearn.
>>> from sklearn.metrics import precision_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> precision_score(y_true, y_pred, average='micro')

Answer: Here is a different view from the other answers that I think will be helpful to others. The goal here is to allow you to compute these metrics using basic laws of probability.
First, it helps to understand what a confusion matrix is telling us in general. Let $Y$ represent a class label and $\hat Y$ represent a class prediction. In the binary case, let the two possible values for $Y$ and $\hat Y$ be $0$ and $1$, which represent the classes. Next, suppose that the confusion matrix for $Y$ and $\hat Y$ is:

$\hat Y = 0$
$\hat Y = 1$

$Y = 0$
10
20

$Y = 1$
30
40

With hindsight, let us normalize the rows and columns of this confusion matrix, such that the sum of all elements of the confusion matrix is $1$. Currently, the sum of all elements of the confusion matrix is $10 + 20 + 30 + 40 = 100$, which is our normalization factor. After dividing the elements of the confusion matrix by the normalization factor, we get the following normalized confusion matrix:

$\hat Y = 0$
$\hat Y = 1$

$Y = 0$
$\frac{1}{10}$
$\frac{2}{10}$

$Y = 1$
$\frac{3}{10}$
$\frac{4}{10}$

With this formulation of the confusion matrix, we can interpret $Y$ and $\hat Y$ slightly differently. We can interpret them as jointly Bernoulli (binary) random variables, where their normalized confusion matrix represents their joint probability mass function. When we interpret $Y$ and $\hat Y$ this way, the definitions of precision and recall are much easier to remember using Bayes' rule and the law of total probability:
\begin{align}
\text{Precision} &= P(Y = 1 \mid \hat Y = 1) = \frac{P(Y = 1 , \hat Y = 1)}{P(Y = 1 , \hat Y = 1) + P(Y = 0 , \hat Y = 1)} \\
\text{Recall} &= P(\hat Y = 1 \mid Y = 1) = \frac{P(Y = 1 , \hat Y = 1)}{P(Y = 1 , \hat Y = 1) + P(Y = 1 , \hat Y = 0)}
\end{align}
How do we determine these probabilities? We can estimate them using the normalized confusion matrix. From the table above, we see that
\begin{align}
P(Y = 0 , \hat Y = 0) &\approx \frac{1}{10} \\
P(Y = 0 , \hat Y = 1) &\approx \frac{2}{10} \\
P(Y = 1 , \hat Y = 0) &\approx \frac{3}{10} \\
P(Y = 1 , \hat Y = 1) &\approx \frac{4}{10}
\end{align}
Therefore, the precision and recall for this specific example are
\begin{align}
\text{Precision} &= P(Y = 1 \mid \hat Y = 1) = \frac{\frac{4}{10}}{\frac{4}{10} + \frac{2}{10}} = \frac{4}{4 + 2} = \frac{2}{3} \\
\text{Recall} &= P(\hat Y = 1 \mid Y = 1) = \frac{\frac{4}{10}}{\frac{4}{10} + \frac{3}{10}} = \frac{4}{4 + 3} = \frac{4}{7}
\end{align}
Note that, from the calculations above, we didn't really need to normalize the confusion matrix before computing the precision and recall. The reason for this is that, because of Bayes' rule, we end up dividing one value that is normalized by another value that is normalized, which means that the normalization factor can be cancelled out.
A nice thing about this interpretation is that it can be generalized to confusion matrices of any size. In the case where there are more than 2 classes, $Y$ and $\hat Y$ are no longer considered to be jointly Bernoulli, but rather jointly categorical. Moreover, we would need to specify which class we are computing the precision and recall for. In fact, the definitions above may be interpreted as the precision and recall for class $1$. We can also compute the precision and recall for class $0$, but these have different names in the literature.


Fractional Exponent Identity: Is the inside of a root necessarily calculated first?

Question: I know $a^{b/c}=\sqrt[c]{a^b}$, but does $a^b$ have to be calculated first, or does $a^{b/c}=(\sqrt[c]a\,)^b$ also work? Thanks.
Comment: I assume you meant to put $b$, not $n$. If so, they are equivalent for $a\ge 0$. $a^{b/c} = (a^b)^{1/c} = (a^{1/c})^b$
Answer: I am assuming that $a > 0$ is a real number, and taking
$$
a^{b/c} = \sqrt[c]{a^b}
$$
as the definition of the rational power. Let's raise the new expression $x = (\sqrt[c]{a}\,)^b$ to the power $c$ and apply exponent properties:
\begin{align}
x^c &= \bigl((\sqrt[c]{a}\,)^b\bigr)^c \\
&= (\sqrt[c]{a}\,)^{bc} \\
&= (\sqrt[c]{a}\,)^{cb} \\
&= \bigl((\sqrt[c]{a}\,)^c\bigr)^b \\
&= a^b
\end{align}
Thus, $x$ is the $c$-root of $a^b$, which was your original definition for $a^{b/c}$, hence they are all the same number.
Note: This all becomes a bit more complicated if you allow $a$ to be a negative real number or non-real complex number or any other type of number where raising to a power is not a one-to-one operation. In that case, it's not even clear how to define the root since there's potentially more than one.


Finding square of an element from a character table

Question: I'm trying to compute the alternating and symmetric squares of a $\chi_2$, from this incomplete character table:
$$
\begin{array}{c|ccccccc}
g_i & g_1&g_2&g_3&g_4&g_5&g_6&g_7 \\
|C_G(g_i)|&360&8&9&9&4&5&5\\
\hline
\chi_1 &1&1&1&1&1&1&1\\
\chi_2&5&1&2&-1&-1&0&0\\
\chi_3&5&1&-1&2&-1&0&0
\end{array}
$$
I am using the formulas
$$\chi_S(g_i)=\frac{1}{2}(\chi^2(g_i)+\chi(g_i^2))$$
and
$$\chi_A(g_i)=\frac{1}{2}(\chi^2(g_i)-\chi(g_i^2))$$
and have been given the following squares:
$$g_5^2\in g_2^G,g_6^2\in g_7^G,g_4^2\in g_4^G,\text{ and }g_3^2\in g_3^G.$$
Clearly $g_1^2=g_1$, and I can see that $g_7^2$ is either in the conjugacy class $g_6$ or $g_7$ (since the order of $g_7$ must divide $|C_G(g_7)|=5$, and cannot be $1$). It doesn't matter for my purposes which it is in, since $\chi_2(g_6)=\chi_2(g_7)$.
However, I was only able to obtain that $g_2^2 = g_1$ by means of trial-and-error; calculating the inner products $\langle \chi_S,\chi_S\rangle$ and $\langle \chi_A,\chi_A\rangle$ and ensuring that they are both integers. It seems this might not always give a unique answer for some tables. Is there a better way of seeing this from the information given? (I know that the group is $A_6$, but this is not given in the question).
Answer: Since $g_5 \in C_G(g_5)$, the order of $g_5$ is either $2$ or $4$. Consequently, $g_5^2$ has order $1$ or $2$. Since $g_5^2 \in g_2^G$, the order of $g_2$ is either $1$ or $2$. Since $g_2 \neq g_1$, the order of $g_2$ is $2$ and so $g_2^2 = g_1$.
Comment: Thanks; I'm slightly confused, is there a typo in your answer? I thought that the order of an element divides the order of it's centraliser, but $|C_G(g_4)|=9$. Do you mean that $g_5$ has order 2 or 4 and so $g_5^2 \in g_2^G$ has order 1 or 2 (and hence must have order 2)? If so I understand now!
Comment: Yes, I meant $g_5$. I shall correct it.


Limit of $\lim_{x \to 0} (\cot (2x)\cot (\frac{\pi }{2}-x))$ (No L'Hôpital)

Question:
$\lim_{x \to 0} (\cot (2x)\cot (\frac{\pi }{2}-x))$

I can't get to the end of this limit. Here is what I worked out:
\begin{align*}
& \lim_{x \to 0} \frac{\cos 2x}{\sin 2x}\cdot\frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )}
\lim_{x \to 0}\frac{\frac{\cos2x }{2x}}{\frac{\sin 2x}{2x}}\cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )}
= \lim_{x \to 0} \frac{\cos 2x}{2x} \cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )} \\
= & \lim_{x \to 0} \frac{{\cos^2 (x)}-{sin^2 (x)}}{2x}\cdot\frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )}
= \lim_{x \to 0} \left(\frac{\cos^2(x)}{2x}-\frac{sin^2 x}{2x}\right)\cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )} \\
= & \lim_{x \to 0} \left(\frac{1-\sin^2 x}{2x}-\frac{sin x}{2}\right)\cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )}
= \lim_{x \to 0} \left(\frac{1}{2x}-\frac{\sin^2 x}{2x}-\frac{sin x}{2}\right) \cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )} \\
= & \lim_{x \to 0} \left(\frac{1}{2x}-\frac{\sin x}{2}-\frac{sin x}{2}\right)\cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )}
= \lim_{x \to 0} \left(\frac{1}{2x}-2\frac{\sin x}{2}\right)\cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )} \\
= & \lim_{x \to 0} \left(\frac{1}{2x}-\sin x\right)\cdot \frac{\cos(\frac{\pi }{2}-x )}{\sin(\frac{\pi }{2}-x )}
\end{align*}
Here is where I can't seem to complete the limit, the 2x in the denominator is giving me a hard time and I don't know how to get rid of it. Any help would be appreciated. (In previous questions I got a really hard time because of my lack of context, I hope this one follows the rules of the site. I tried.)
Answer: HINT
We have that
$$\cot (2x)\cot\left(\frac{\pi }{2}-x\right)=\frac{\cos(2x)}{\sin(2x)}\frac{\sin x}{\cos x}$$
Comment: Thanks, that tan(x) identity was what saved me :D
Comment: Indeed that's the key point to recognize if you know the standard limit sinx/x. In general, it's often good to reduce to sin x and cos x the expression.
Answer: Hint: $$\lim_{x \to 0} (\cot (2x)\cot (\frac{\pi }{2}-x))=\lim_{x \to 0} {\cos (2x)\over \sin 2x}\tan (x) =\lim_{x \to 0} {\cos (2x)\over 2\sin x\cos x}{\sin x\over \cos x}$$
$$=\lim_{x \to 0} {\cos (2x)\over 2\cos^2 x} =  {1\over 2}$$
Comment: Thanks, that tan(x) identity was what saved me :D
Answer: Hint:
$$\lim_{x \to 0} \cot (2x)\cot (\frac{\pi }{2}-x)=\lim_{x \to 0} \cot (2x)\tan x=\lim_{x \to 0} \dfrac{\cos2x}{\sin2x}\dfrac{\sin x}{\cos x}=\lim_{x \to 0} \dfrac{\cos2x}{1}\dfrac{2x}{\sin2x}\dfrac{\sin x}{x}\dfrac{1}{\cos x}\dfrac12$$
Comment: Thanks, that tan(x) identity was what saved me :D
Answer: $\displaystyle  \cot 2x\cot \left(\frac{\pi }{2}-x\right)=\cot (2x)\tan (x)=\dfrac{\cos 2x\cdot \sin x}{2\sin x\cos^2 x}=\dfrac{\cos 2x}{2\cos^2x}$
$\displaystyle\lim_{x\to0} \cot 2x\cot \left(\frac{\pi }{2}-x\right)=\displaystyle\lim_{x\to0}\dfrac{\cos 2x}{2\cos^2x}=\dfrac12 $
Comment: Thanks, that tan(x) identity was what saved me :D
Answer: $$F(x)=\cot2x\cot\left(\dfrac\pi2-x\right)=\dfrac{\tan x}{\tan2x}=\dfrac{\tan x(1-\tan^2x)}{2\tan x}$$
For $\tan x\ne0,F(x)=\dfrac{1-\tan^2x}2$
As $x\to0,x\ne0\implies\lim_{x\to0}F(x)=\lim_{x\to0}\dfrac{1-\tan^2x}2=?$


Code optimization: bandwidth monitor in c# issues

Question: my question is mainly about code optimization(at the moment)
I have created a network monitor that monitors different connections on the PC, what i had done is I'm sniffing packets at the 3rd level of the stack(the network level), after capturing the packet, i am supposed to create an object on the UI for each connection, what i am doing at the moment is looking at the overall consumed bandwidth and total data sent every second the program is run. here is that part of the code:
<code>    temp= packet_rtxt.TextLength;
        tempdr = temp / 1024;
        dr_txt.Text=tempdr.ToString();
        totaldata = totaldata + temp;
        totaldatadisp = totaldata;
        packet_rtxt.Text = "";
        //unit
        if (totaldata < 10485760)
        {
            if (totaldata < 10240)
                unit.Text = "bytes";
            else
            {
                totaldatadisp = totaldatadisp / 1024;
                unit.Text = "KBs";
            }
        }
        else
        {
            totaldata = totaldatadisp / 1048576;
            unit.Text = "MBs";
        }
        test.Text = totaldatadisp.ToString();
        tds.Enabled = true;
    }
</code>
so what im doing so far is writing out the captured packets into a rich text box, taking the length of that rtxt and adding it to a counter for the total data, taking the length and using it as the data rate, then clearing the rtxt for the next bits of data.
the total data recieved part is working fine, however the BPs section works fine for low amounts of data, then it goes crazy if the data rate is over 10kbps(on my pc)
should i try optimizing the whole code, or is there some other method(keep in mind i need to monitor every single connection), or do i need to use different UI controls?
should I focus on optimization or using new ways?
thanks in advance
Comment: Are you using multithreading? Is it WPF application or WinForms?
Answer: The standard controls are not made for such a load. You need to separate the logging of data from the display of data.
I'd only show the last say 10kb of text once per second. You can still keep all of the log records in some data structure. But you don't have to push all of them to the UI.
Alternatively you can write your own text-display control but that is going to be a lot more work.
Comment: WOW I never actually though of that, that sounds like a raelly good Idea
Comment: I was only displaying it so i can read its size using the textbox.length function, should i log it in a file instead? and then calculate the size of that file?
Comment: Why don't you just store it in a string variable?
Comment: It's definitely more processor and memory friendly, but my bandwidth calculator is still not working


How to use js to dynamically add components and listen to their events in vue3?

Question: I've recently been learning Vue3. I want to add components dynamically, and the parent component can listen to the events of the added chirld components. To make it clear what I want to do, I have written the following code. I want a new button to be added when the mouse moves over any of the buttons. But only the first button actually triggers the hello function, which means that the code "v-on:addButton": hello in line 7 of App.vue doesn't work. I would like to know how to modify the code to meet my requirements, or if there is another easy way to implement this functionality.
Chirld components/Hello.vue

<template>
  <button @mouseenter="$emit('addButton')">{{text}}</button>
</template>

Father App.vue

<template>

    <Hello text="0" v-on:addButton="hello"/>

</template>

Update:
Thanks for the replies. I found that simply changing "v-on:addButton": hello to onaddButton: hello works.
Answer: Manipulating the DOM directly in most cases doesn't work with Vue since you'll loose the reactivity and other binding stuff, another approach is to use cnt variable to render the components using v-for directive ;:

<template>

    <Hello v-for="i in cnt" :text="i" v-on:addButton="addBtn"/>

</template>

How to use js to dynamically add components and listen to their events in vue3？


pandas time delta from grouped neighbors

Question: I have a group of dates.  I would like to subtract them from their forward neighbor to get the delta between them. My  code look like this:
import pandas, numpy, StringIO

txt = '''ID,DATE
002691c9cec109e64558848f1358ac16,2003-08-13 00:00:00
002691c9cec109e64558848f1358ac16,2003-08-13 00:00:00
0088f218a1f00e0fe1b94919dc68ec33,2006-05-07 00:00:00
0088f218a1f00e0fe1b94919dc68ec33,2006-06-03 00:00:00
00d34668025906d55ae2e529615f530a,2006-03-09 00:00:00
00d34668025906d55ae2e529615f530a,2006-03-09 00:00:00
0101d3286dfbd58642a7527ecbddb92e,2007-10-13 00:00:00
0101d3286dfbd58642a7527ecbddb92e,2007-10-27 00:00:00
0103bd73af66e5a44f7867c0bb2203cc,2001-02-01 00:00:00
0103bd73af66e5a44f7867c0bb2203cc,2008-01-20 00:00:00
'''
df = pandas.read_csv(StringIO.StringIO(txt))
df = df.sort('DATE')
df.DATE = pandas.to_datetime(df.DATE)
grouped = df.groupby('ID')
df['X_SEQUENCE_GAP'] = pandas.concat([g['DATE'].sub(g['DATE'].shift(), fill_value=0) for title,g in grouped])

I am getting pretty incomprehensible results. So, I am going to go with I have a logic error.
The results I get are as follows:
                               ID                DATE       X_SEQUENCE_GAP
0  002691c9cec109e64558848f1358ac16 2003-08-13 00:00:00 12277 days, 00:00:00
1  002691c9cec109e64558848f1358ac16 2003-08-13 00:00:00             00:00:00
3  0088f218a1f00e0fe1b94919dc68ec33 2006-06-03 00:00:00    27 days, 00:00:00
2  0088f218a1f00e0fe1b94919dc68ec33 2006-05-07 00:00:00 13275 days, 00:00:00
5  00d34668025906d55ae2e529615f530a 2006-03-09 00:00:00 13216 days, 00:00:00
4  00d34668025906d55ae2e529615f530a 2006-03-09 00:00:00             00:00:00
6  0101d3286dfbd58642a7527ecbddb92e 2007-10-13 00:00:00 13799 days, 00:00:00
7  0101d3286dfbd58642a7527ecbddb92e 2007-10-27 00:00:00    14 days, 00:00:00
9  0103bd73af66e5a44f7867c0bb2203cc 2008-01-20 00:00:00  2544 days, 00:00:00
8  0103bd73af66e5a44f7867c0bb2203cc 2001-02-01 00:00:00 11354 days, 00:00:00

I was expecting for exapme that 0 and 1 would have both a 0 result. Any help is most appreciated.
Comment: Maybe the error is not incomprehensible for someone. Posting the error  could help us more.
Comment: upgrade to 0.11.0rc1, and take a look at the new docs, and these recipes: http://pandas.pydata.org/pandas-docs/dev/cookbook.html#miscellaneous, guessing you are using 0.10.1, lots of good changes in timedeltas
Answer: This is in 0.11rc1 (I don't think will work on a prior version)
When you shift dates the first one is a NaT (like a nan, but for datetimes/timedeltas)
In [27]: df['X_SEQUENCE_GAP'] = grouped.apply(lambda g: g['DATE']-g['DATE'].shift())

In [30]: df.sort()
Out[30]:
                                 ID                DATE      X_SEQUENCE_GAP
0  002691c9cec109e64558848f1358ac16 2003-08-13 00:00:00                 NaT
1  002691c9cec109e64558848f1358ac16 2003-08-13 00:00:00            00:00:00
2  0088f218a1f00e0fe1b94919dc68ec33 2006-05-07 00:00:00                 NaT
3  0088f218a1f00e0fe1b94919dc68ec33 2006-06-03 00:00:00   27 days, 00:00:00
4  00d34668025906d55ae2e529615f530a 2006-03-09 00:00:00                 NaT
5  00d34668025906d55ae2e529615f530a 2006-03-09 00:00:00            00:00:00
6  0101d3286dfbd58642a7527ecbddb92e 2007-10-13 00:00:00                 NaT
7  0101d3286dfbd58642a7527ecbddb92e 2007-10-27 00:00:00   14 days, 00:00:00
8  0103bd73af66e5a44f7867c0bb2203cc 2001-02-01 00:00:00                 NaT
9  0103bd73af66e5a44f7867c0bb2203cc 2008-01-20 00:00:00 2544 days, 00:00:00

You can then fillna (but you have to do this ackward type conversion becuase of a numpy bug, will get fixed in 0.12).
 In [57]: df['X_SEQUENCE_GAP'].sort_index().astype('timedelta64[ns]').fillna(0)
Out[57]:
0              00:00:00
1              00:00:00
2              00:00:00
3     27 days, 00:00:00
4              00:00:00
5              00:00:00
6              00:00:00
7     14 days, 00:00:00
8              00:00:00
9   2544 days, 00:00:00
Name: X_SEQUENCE_GAP, dtype: timedelta64[ns]


What is the correct way to check monit status/summary success/failure

Question: I have monit utility on production for monitoring several daemons (our micro-services). I'm trying to figure the best way to unmonitor/monitor my daemons while updating them. So, basically I need something like this, pseudo-code:
has_monit = false
if `monit watches daemon-xxx` then
  has_monit = true
  monit unmonitor daemon-xxx
endif
apt-get install xxx.deb
if has_monit then
  monit monitor deamon-xxx
endif

Unfortunately it seems that monit summary daemon-xxx is always return exit code 0 regardless it was success or failure, and prints raw html about failure, e.g.
[bialix@server ~]$ sudo monit summary xxx
<title>400 Bad Request</title>
Bad Request
Service 'xxx' not found
monit 5.30.0
[bialix@server ~]$ echo $?
0

It seems exit code 1 only if monit is not running.
What is the right way here? Parsing the output of monit summary?
Comment: Can you tell me the Monit version, the html output should not be displayed.
Comment: I found the answer in the html output, it is monit 5.30.0, sorry. The html output problem was fix with monit 5.31.0, some more information are available from "https://bitbucket.org/tildeslash/monit/issues/1025/command-error-handling-does-not-work-well".
Answer: You are right. The exit code of Monit is the status of the command entered.
You get "1" if the resource is not defined, or any other internal problem only.
A suggestion,
I use "monit -B summary xxxx" to get the service status and parse the command output. The option "-B" is the batch command line mode and remove the output tables and colours.


How to play rapid 32nd notes

Question: I've almost completed John Field's Nocturne in B♭ Major that I've worked with for around 3 weeks but I cant seem to get this passage done. I've intentionally skipped this part as I cannot figure out how it works :(

The last part there where I have to fit in a descending scale leaves me a big question mark. I have tried playing this slowly with both hands but there is no way I can make this sound right in 12/8.
This is a modified version of the song I think, which you can find in the book "The Library of Piano Classics". There are no live plays of this modified version on YouTube (from what I can find).
The three notes for the left hand isn't enough to make the descending scale fit in if I'd play it in Tempo 1 (Andante, ♩. = 66 BPM) unless I do the right hand in a really fast motion.
Does anyone have any advice how I can get through this? I won't be able to contact my teacher until Monday next week unfortunately. My knowledge isn't very wide as I've only played piano for 6 months! If there are more things that you might need to know then don't hesitate to ask!
Comment: You mean "12/8" for the meter. The rhythm does actually fit, you just have to choose the right tempo and learn to play the notes fast enough. Try practicing the right hand figure in groups, where you play each group of four notes quickly, but pause between them. Gradually make the pause between shorter, or increase the number of notes in each group.
Comment: From looking online it's a *dotted quarter* for the beat, so that makes these 32nd notes being played at a rate of over 13 per second.  That's quite high, but should be manageable with practice -- for an intermediate-level player.  I would not expect you to be able to play this after 6 months.  What speed are you currently playing scales at?
Comment: In addition to patience and practice, you have to be disciplined in your technique. I couldn't play this at tempo but I know I would have to fight the urge to drop my wrist when doing the 1-3 and 1-4 fingering changes. Practice very slowly until you can play it perfectly, relaxed, and with correct technique. Then just slowly speed up that metronome (by "slowly" I mean over the course of weeks to months). Also, don't forget to include landing on that D in the next measure as part of your practice.
Comment: Usually if the question is "what shortcut(s) can I use to learn this?" the answer is "there are no shortcuts". To me there's an upside to this maxim: The only thing we can do to improve our musicianship is practice, but at the same time, all we have to do is practice and our musicianship will improve! I take it as a message of hope. Also, I see "practice" as actually "playing" and therefore it's fun. So I have fun every day for three months and then I realize I'm better than I was three months ago.
Comment: @MatthewRead Regarding the speed.. I can go down the scale in time down to the D in the next measure if I put the metronome on 115 BPM. (I wasn't sure how to explain it). 13 notes per second is sure a lot and I can barely hit 7-8 notes in a second.

I suppose it can't be avoided than to split this into sections and take it slow and steady whilst increasing the tempo bit by bit. I was hoping there'd be another way of getting through this. Thanks for the advice nonetheless!
Comment: @ToddWilcox Thanks! I've done a few sessions doing exactly that and I think its going well. I suppose I'm just impatient as I expect myself results in just a day.
Answer: To get a feeling of how it should go, sing it.  "Doo doo doo....da diddleiddle diddleiddle diddleiddle".    Play the RH seperately, slowly, WITH THE INDICATED FINGERING.  Yes, it feels a bit odd, doesn't it?  But come to terms with it, and don't increase speed until it's absolutely fluent at the slower tempo.  Now both hands, slowly.  Never fluff it, just to get up to speed - you'll just be teaching your fingers how to do it wrong.  It WILL come, I promise you!  But if you've only been playing for 6 months, it's very impressive that you're attempting this piece at all.  Maybe you'll just have to wait a bit until your technique catches up with this challenge.  (Do you play your scales at the speed of this figure?  Perhaps you should.)
Comment: Thanks! Used your method by singing how it sounds and yes, it actually helps a lot because the "diddleiddle" part divides the descent into parts. I'll pick up the whole B flat scale for both hands and work my way from there. I've previously done the C scale already and I realized not long ago that it is essentially the same 1-3 ~ 1-4. I'll give my fingers a few and steady weeks(or months) to increase my tempo then! Thanks again.
Answer: Here's a little secret about this style of music: you can use a certain amount of rubato. By that I mean you can slow down the hard parts and if you do it right you will sound like a very expressive performer. In fact, if you play those fast notes in a perfectly metronomic fashion it will sound awful.
First, imagine you are an opera singer and this is your big aria. Without playing, sing the right-hand part the way an opera singer would. Note how you slow down the F's, linger on the high C and make your way down the scale at a rate that seems natural.
Now do the same thing, pretending that you're also the conductor helping the musicians follow the singer. Conduct 8th notes with a 3/4 pattern. Note how you slow down to follow the singer and then go back to tempo in the next measure so the singer doesn't run out of breath on the long notes.
Now do the same thing but play the left-hand part to accompany your song. This will give you good sense of how a melody line can really sing with feeling by slowing down and speeding up. The pulse is very flexible but the left hand tells the listener where the beats are so it all makes musical sense.
Finally play it with both hands, recreating the feel of singing the melody. You'll find you don't need a really fast motion.
Also, listen to recordings of great pianists playing similar pieces by Chopin, who was inspired by John Field's music. You'll find similar passages. Listen to singers singing songs by Schubert, Chopin and Liszt too.
Answer: In terms of interpretation a believe the sudden pianissimo in bar 2 provides a clue. Instinctively the first thought would be that giving emphasis to a passage or group of notes requires louder playing. However a sudden pianissimo can achieve a similar purpose. Here the markings are unusual in that the second F in bar two is accented albeit at a pianissimo level and this occurs with a leap to high C - destination notes following a leap also are naturally emphasised. Here I agree with M Lutton that a certain give-and-take is required with an almost imperceptible lingering on the high C and the following notes being taken almost as a single gesture leading to the first D in bar 3. Of course in aiming for this over- sentimentality should be avoided.
I share the surprise of others here that you are playing this after only 6 months. I would expect a pupil to be playing this at or after about 2 years. I would describe such progress as precocious if true...

How to play rapid 32nd notes


Why projective varieties are non affine varieties

Question: Why the complex projective space $P^n$ and its irreducible Zariski closed subsets are examples of non-affine varieties?
I read this on Siddarth Kannan - An informal introduction to blow-ups, page 1.
Comment: Informally, the answer below says that if $X$ is affine, there are non-constant algebraic functions defined on all of it (arising from restrictions of polynomial functions on an ambient vector space). On the other hand, on a projective variety $X$, the only algebraic functions defined on all of $X$ are the constants. If you work over the complex numbers, this follows from the fact that a holomorphic function on a compact complex manifold is constant, because it is holomorphic and bounded.
Comment: You could have a look at III.5 in https://homepages.warwick.ac.uk/staff/Miles.Reid/MA4A5/UAG.pdf
Comment: @DamianRössler your comment was very helpful to me, could you explain a bit more the part "on a projective variety X, the only algebraic functions defined on all of X are the constants"? Or suggest a reference/theorem to understand this. I understood it in the context of complex numbers. Thanks.
Answer: If $X$ is an affine variety, $X = {\rm Spec} A$, then $A$ is the ring of global sections of the structure sheaf ${\mathcal O}_X$. But for a projective variety $X$, any global section of ${\mathcal O}_X$ is a constant function. The ring of global sections is just the ground field, and its spectrum is a point, not $X$.
Comment: Could you suggest a book to understand the concepts you mentioned in your answer? For example "global section" and "structure sheaf". I am new in algebraic geometry. Is Hartshorne a good reference for this concepts?


Pre-populating a Persistent Volume on OpenShift

Question: I have created a cluster on OpenShift Online for experimental use. My Deployment which I am trying to create needs to have a pre-populated data volume before use. All of the deployments should use the same volume and that means that the Persistent Volume Claim needs to be configured as ReadOnlyMany.
I have created a Persistent Volume Claim as well, but I am not sure is it possible to pre-populate a ReadOnlyMany volume on OpenShift?
Answer:
I have created a Persistent Volume Claim as well, but I am not sure is it possible to pre-populate a ReadOnlyMany volume on OpenShift?

Not really that's what ReadOnlyMany is, it's Read Only. You can use something else to pre-populate your volume prior (like a VM/Host/Container, or even another Kubernetes cluster if you remove the volume after pre-populating and Retain it). It probably won't work with the same Kubernetes cluster though unless the volume allows you to change from something else (ReadWriteOnce, ReadWriteMany) to ReadOnlyMany.
You didn't specify what type of Volume you are using but you could potentially use ReadWriteMany and manage access to write using plain *nix filesystem permissions. Then you can run your pods as a specific user using a SecurityContext.
✌


Building Smaller Sized Raspberry pi images

Question: Am trying to build small size Raspberry Pi images using packer-builder-arm (https://github.com/mkaczanowski/packer-builder-arm) community plugin.
The resulting images are still 2GB. Anybody suggestion how to reduce the image size. Thanks!
{
  "variables": {},
  "builders": [
{
  "type": "arm",
  "file_urls": [
    "http://downloads.raspberrypi.org/raspios_lite_armhf/images/raspios_lite_armhf-2020-05-28/2020-05-27-raspios-buster-lite-armhf.zip"
  ],
  "file_checksum_url": "http://downloads.raspberrypi.org/raspios_lite_armhf/images/raspios_lite_armhf-2020-05-28/2020-05-27-raspios-buster-lite-armhf.zip.sha256",
  "file_checksum_type": "sha256",
  "file_target_extension": "zip",
  "image_build_method": "reuse",
  "image_path": "custom-raspberry-pi-os.img",
  "image_size": "700M",
  "image_type": "dos",
  "image_partitions": [
    {
      "name": "boot",
      "type": "c",
      "start_sector": "8192",
      "filesystem": "vfat",
      "size": "256M",
      "mountpoint": "/boot"
    },
    {
      "name": "root",
      "type": "83",
      "start_sector": "532480",
      "filesystem": "ext4",
      "size": "0",
      "mountpoint": "/"
    }
  ],
  "image_chroot_env": [
    "PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin"
  ],
  "qemu_binary_source_path": "/usr/bin/qemu-arm-static",
  "qemu_binary_destination_path": "/usr/bin/qemu-arm-static"
}
  ],
  "provisioners": [
{
  "type": "shell",
  "inline": ["touch /tmp/test"]
}
  ]
}```

Answer: You might want to look into removing the programs you don't need in there. And then do a partition resize using something like resize2fs.
Comment: A good solution is create a custom post processor to remove unused programs and compress the image as zip file.


Sort an array of names except for one item

Question: Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?
var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];

For the sample array above, the desired result would be:
[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]

Comment: So did you write a sort function that does the other half?
Comment: check for `the others` as a value in the sort callback function, return appropriate value (-1 or 1) regardless of lexical order of the two elements being compared
Comment: I've changed the resulting array. Sorry for the confusion, but I need an array of sorted objects.
Comment: of course you do - the comment remains
Comment: It's a little hard to pick the best answer for this one. Really good stuff on the answers.
Answer: Simply check for either value in the sort callback being The others - return -1 if a is that, or 1 if it's b - otherwise return the localeCompare of a and b
friends.sort(({name: a}, {name:b}) => a == "The others" ? -1 : (b == "The others" ? 1 : a.localeCompare(b)));

The "readable" and non-ES2015+ version of that
friends.sort(function (a, b) {
  if (a.name == "The others") return -1;
  if (b.name == "The others") return 1;
  return a.name.localeCompare(b.name);
});

Answer: Sort like this:

var friends = [
   { id: 1, name: 'Paul' },
   { id: 2, name: 'Mary' },
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' }
];

friends.sort((a, b) => {
     if (a.name == "The others") {
         return -1; // a comes first
     } else if (b.name == "The others") {
         return 1;
     } else {
         return (a.name < b.name ? -1 : 1);
     }
 });

console.log(friends);
Answer: Following are steps that you need to follow

Sort : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Move : Move an array element from one array position to another

Please see following working example.

var friends = [{
    id: 1,
    name: 'Paul'
  },
  {
    id: 2,
    name: 'Mary'
  },
  {
    id: 3,
    name: 'The others'
  },
  {
    id: 4,
    name: 'John'
  }
];

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
friends.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

var indexOfTheOters = friends.reduce(function(acc, friend, index) {
  if(!acc && friend.name === 'The others') {
    acc = index;
  }
  return acc;
}, null);

// https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another
Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this; // for testing purposes
};
friends.move(indexOfTheOters, 0)
console.log(friends);
Answer: Try the following:

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
var notConsidered = friends.filter(friend => friend.name == 'The others');
var friend = friends.filter(friend => friend.name!= 'The others');
var sortedfriend = friend.sort(function (a, b) {
  if (a.name  b.name) return 1;
  return 0;
});

sortedfriend.unshift(notConsidered[0])
console.log(sortedfriend);
Answer:
copy your (The others object) and store it into a variable using filter
remove it from the array using filter
sort the array by name property.
add the (The others object) in the beginning of your array using unshift

compare function copied from this answer

var friends = [{
        id: 1,
        name: 'Paul'
    },
    {
        id: 2,
        name: 'Mary'
    },
    {
        id: 3,
        name: 'The others'
    },
    {
        id: 4,
        name: 'John'
    }
];

function compare(a,b) {
    if (a.name  b.name)
      return 1;
    return 0;
  }

// copy the others object
const theOthersObj = friends.filter(friend => friend.name === 'The others')[0];

const newFriends = friends
            .filter(friend => friend.name !== 'The others') // removing the others object
            .sort(compare) // storing the array by name
// Adding the others object in the first of the array
newFriends.unshift(theOthersObj);

console.log(newFriends);
Answer: You want to hard code your compare function so that 'The others' always has the lowest/greatest value.

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];

function compare(a, b){
  if(a.name === "The others") {
   return -1;
  } else if (b.name === "The others") {
   return 1;
  } else if (a.name > b.name){
   return -1;
  } else if (a.name < b.name){
   return 1;
  } else {
   return 0;
  }
}

console.log(friends.sort(compare))
Answer: There are some great ideas here but what I found to be the simpler solutions are the two bellow:
Using sort:
friends.sort((a, b) => a.name !== b.name ? a.name  +(!b.name.localeCompare("The others")));

Using map and sort:
friends.map(o => o.name).sort((a,b) => a=="The others" ? -1 : b=="The others" ? 1 : a > b);


Is Akaike Information Criterion a kind of loss function?

Question: I guess it probably is, but just want a confirmation. Thanks!
Answer: From Wikipedia's Loss function: "In mathematical optimization, statistics, decision theory and machine learning, a loss function or cost function is a function that maps an event or values of one or more variables onto a real number intuitively representing some "cost" associated with the event. An optimization problem seeks to minimize a loss function. An objective function is either a loss function or its negative (sometimes called a reward function, a profit function, a utility function, a fitness function, etc.), in which case it is to be maximized."
On this site we have a good explanation for what AIC is. That is, ASSUMING the residuals are Gaussian, AIC is log-likelihood is given by: "$ \log(L(\theta)) =-\frac{|D|}{2}\log(2*\pi) -\frac{1}{2} \log(|K|) -\frac{1}{2}(x-\mu)^T K^{-1} (x-\mu)$, $K$ being the covariance structure of your model, $|D|$ being the number of points in your datasets, $\mu$ the mean response and obviously $x$ being your dependent variable.
More specifically AIC is calculated to be equal to $2k - 2 \log(L)$, where $k$ is the number of fixed effect in your model and $L$ your likelihood function [1]. It practically compares trade-off between variance($2k$) and bias ($2 \log(L)$) in your modelling assumptions. As such in your case it would compare two different log-likelihood structures when it came to the bias term. That is because when you calculate your log-likelihood practically you look at two terms:
A fit term, denoted by $-\frac{1}{2}(x-\mu)^T K^{-1} (x-\mu)$ and a complexity penalization term, denoted by $-\frac{1}{2} \log(|K|)$."
Although the fit term is not called a loss function per se, it is a loss function, because log likelihood is optimized to yield an AIC value, that is, a step left out in the explanation above, and which is probably not fully characterized for general residuals that do not agree with the given Gaussian assumption. That answers your question, yes, it is a loss function. What you didn't ask is whether AIC is good for anything.
Comment: Being a nitpciker or a visionary, i disagree with the Wikipedia statement:  'An optimization problem seeks to minimize a loss function. An objective function is either a loss function or its negative (sometimes called a reward function, a profit function, a utility function, a fitness function, etc.), in which case it is to be maximized." '  While those make sense to determine how good things can be (made), it also can make sense to maximize a loss function to determine how bad things could be (what us the worst outcome). Combining the two bounds the range of outcomes. Similarly for reward.
Comment: Suggest you try to change Wikipedia. They may give you an argument. More important is that loss (or reward) functions can have local minima, be indeterminate, and be totally inappropriate to the physics of "loss" of the problems they model, which is what prompted my snide remark "you didn't ask.."
Comment: Left unsaid in my comment is for the worst case analysis, you really need the global optimum. If, for instance, the loss function is convex, possibly subject to convex constraints, then it is a (often 'easy") convex optimization problem, and therefore, there are no non-global local minima. Finding the maximum of that convex function subject to the same constraints is a concave optimization problem, for which finding the global maximum can be quite difficult (of course, if the objective function is linear, then both directions are convex optimization problems and concave optimization problems).
Comment: @MarkL.Stone It gets more complicated in with $n$-tuple independent variables in $n+1$-space, and, to make matters worse, sometimes the global optimum is not physical so that the desired solution is a local optimum for which even finding constraints can be problematic. So, how bad does it get? Blech, yuck, ack, fooey that's how.
Comment: Can you provide an example for which the global optimum is not physical so that the desired solution is a local optimum? Is such an optimization model formulation a good one? What I can tell you, is that sometimes the "nearest" local optimum ,whether or not it happens to be a global optimum, might tend to be the best solution - this could happen for instance in a sequential quadratic programming (QP) algorithm in which a QP is solved to find the step to a new point. and a nearby local optimum may be better than a distant global optimum for which the quadratic model may be less valid.
Comment: Fitting most any two density convolution to a time series has a tendency to go to negative start times.This happens for various loss functions including those that are properly modelled for measurement error.
Comment: That's what constraints are for. Is it problematic to "find" and impose non-negativity constraints? Those are "nice" constraints to have, from a computational standpoint.
Comment: Yes, it can be problematic to impose non-negativity constraints. Trivial example, problems are sometimes convergent to zero from below, even when that implies excursion into the complex field for a short distance. There are lots of other more complicated examples.


How to change port number in vue-cli project

Question: How to change the Port number in the Vue-CLI project so that it runs on another port instead of 8080.
Comment: On macOS, please remember about this https://stackoverflow.com/a/46813423/13762066
Answer: If you're using vue-cli 3.x, you can simply pass the port to the npm command like so:
npm run serve -- --port 3000
Then visit http://localhost:3000/
Comment: You saved me precious time, as the first `--` is not written in the doc: https://cli.vuejs.org/guide/cli-service.html#using-the-binary. I was typing `npm run serve --port 3000` which seems logical to me, but I got errors... Thumbs up!
Comment: That's because the first `--` escapes the parameters given to `npm run serve` and _not_ to `vue-cli-service`. If you edit `package.json` and the `serve` command directly, you enter it as shown in the documentation: `"serve": "vue-cli-service serve --port 3000",`
Comment: While this answer is good and has most up-votes (mine too ;)), I prefer `package.json` change in order not to have to give port to command every time but have it persistent and automatic in `npm run serve` command.
Answer: Late to the party, but I think it's helpful to consolidate all these answers into one outlining all options.
Separated in Vue CLI v2 (webpack template) and Vue CLI v3, ordered by precedence (high to low).
Vue CLI v3

package.json: Add port option to serve script: scripts.serve=vue-cli-service serve --port 4000
CLI Option --port to npm run serve, e.g. npm run serve -- --port 3000. Note the --, this makes passes the port option to the npm script instead of to npm itself. Since at least v3.4.1, it should be e.g. vue-cli-service serve --port 3000.
Environment Variable $PORT, e.g. PORT=3000 npm run serve
.env Files, more specific envs override less specific ones, e.g. PORT=3242
vue.config.js, devServer.port, e.g. devServer: { port: 9999 }

References:

https://cli.vuejs.org/config/#devserver
https://cli.vuejs.org/config/#vue-config-js
https://cli.vuejs.org/guide/mode-and-env.html

Vue CLI v2 (deprecated)

Environment Variable $PORT, e.g. PORT=3000 npm run dev
/config/index.js: dev.port

References:

http://vuejs-templates.github.io/webpack/
https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.dev.conf.js#L35
Comment: Looks like this changed a tad in latest vue cli (using 3.4.1), here's my "serve" line in package.json: `"serve": "vue-cli-service serve --port 4000",`. Works great!
Comment: @Ryan - This was reported yesterday in the VueJS CLI Repository Issues: https://github.com/vuejs/vue-cli/issues/4452

It is saying to install portfinder (https://github.com/http-party/node-portfinder/) as there was a breaking change which happened with that.
Comment: @RoccoB Thanks, I verified it and added it to the answer.
Comment: The answers above don't seem to work in v3 at this date. I tried the .env option, package.json, vue.config.js, and CLI command option but they all get ignored. The config file docs say "Some values like `host`, `port` and `https` may be overwritten by command line flags." https://cli.vuejs.org/config/#devserver Am I missing something? Anybody else having issues?
Comment: @RoccoB this has done the trick in my case also. Thanks wwerner for the respose.
Answer: As the time of this answer's writing (May 5th 2018), vue-cli has its configuration hosted at <your_project_root>/vue.config.js. To change the port, see below:
// vue.config.js
module.exports = {
  // ...
  devServer: {
    open: process.platform === 'darwin',
    host: '0.0.0.0',
    port: 8080, // CHANGE YOUR PORT HERE!
    https: false,
    hotOnly: false,
  },
  // ...
}

Full vue.config.js reference can be found here: https://cli.vuejs.org/config/#global-cli-config
Note that as stated in the docs, "All options for webpack-dev-server" (https://webpack.js.org/configuration/dev-server/) is available within the devServer section.
Answer: The port for the Vue-cli webpack template is found in your app root's myApp/config/index.js.
All you have to do is modify the port value inside the dev block:
 dev: {
    proxyTable: {},
    env: require('./dev.env'),
    port: 4545,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    cssSourceMap: false
  }

Now you can access your app with localhost:4545
also if you have .env file better to set it from there
Comment: In the latest vuejs version. The file is no longer used, instead using: /vue.config.js.
Comment: `"scripts": {
    "serve": "vue-cli-service serve --port 80"
  },`
Comment: Vue CLI 3 uses vue.config.js at project root. It has to be created manually IIRC.
Comment: The file `myApp/config/index.js` does not exist!
Comment: there is no vue.config.js there
Comment: Also, you can use `npm run serve -- --port 8085`
Comment: Your answer is correct, but please mention Vue version.
Comment: do you mean the vue-cli version? vue version has no effect on this
Comment: sorry, I think with the latest update it has changed, you can update the answer one you figure it out
Comment: Since this is the (un)helpful first listed response you also want to check: https://cli.vuejs.org/config/#vue-config-js under some sub section it is shown.
Answer: Another option if you're using vue cli 3 is to use a config file. Make a vue.config.js at the same level as your package.json and put a config like so:
module.exports = {
  devServer: {
    port: 3000
  }
}

Configuring it with the script:
npm run serve --port 3000

works great but if you have more config options I like doing it in a config file. You can find more info in the docs.
Comment: I like this answer as it shows that vue.config.js can be used to just change the port and leave everything else as-is which is what was asked originally.
Answer: Best way is to update the serve script command in your package.json file. Just append --port 3000 like so:
"scripts": {
  "serve": "vue-cli-service serve --port 3000",
  "build": "vue-cli-service build",
  "inspect": "vue-cli-service inspect",
  "lint": "vue-cli-service lint"
},

Answer: First Option:
OPEN package.json and add "--port port-no" in "serve" section.
Just like below, I have done it.
{
  "name": "app-name",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --port 8090",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
}

Second Option: If You want through command prompt
npm run serve --port 8090
Answer: If you want to change the localhost port, you can change scripts tag in package.json:
 "scripts": {
    "serve": "vue-cli-service serve --port 3000",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

Answer: In the webpack.config.js:
module.exports = {
  ......
  devServer: {
    historyApiFallback: true,
    port: 8081,   // you can change the port there
    noInfo: true,
    overlay: true
  },
  ......
}

You can change the port in the module.exports -> devServer -> port.
Then you restrat the npm run dev. You can get that.
Answer: Oh my God! It is not that much complicated, with these answers which also works. However, other answers tho this question also works well.
If you really want to use the vue-cli-service and if you want to have the port setting in your package.json file, which your 'vue create <app-name>' command basically creates, you can use the following configuration: --port 3000. So the whole configuration of your script would be like this:
...
"scripts": {
"serve": "vue-cli-service serve --port 3000",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
...

I am using @vue/cli 4.3.1 (vue --version) on a macOS device.
I have also added the vue-cli-service reference:
https://cli.vuejs.org/guide/cli-service.html
Comment: This answer duplicates one on this page from 3 years ago: https://stackoverflow.com/a/60727863/401467
Answer: If you use yarn:
yarn serve --port 3000

Answer:
open package.json
add script named serve, "serve": "Vue-cli-service serve --port 8081"
npm run serve
you will server run 8081

{
  "name": "app-name",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --port 8081",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  }
}

Answer: An alternative approach with vue-cli version 3 is to add a .env file in the root project directory (along side package.json) with the contents:
PORT=3000
Running npm run serve will now indicate the app is running on port 3000.
Answer: There are a lot of answers here varying by version, so I thought I'd confirm and expound upon Julien Le Coupanec's answer above from October 2018 when using the Vue CLI. In the most recent version of Vue.js as of this post - firstname.lastname@example.com - the outlined steps below made the most sense to me after looking through some of the myriad answers in this post. The Vue.js documentation references pieces of this puzzle, but isn't quite as explicit.

Open the package.json file in the root directory of the Vue.js project.
Search for "port" in the package.json file.
Upon finding the following reference to "port", edit the serve script element to reflect the desired port, using the same syntax as shown below:
"scripts": {
  "serve": "vue-cli-service serve --port 8000",
  "build": "vue-cli-service build",
  "lint": "vue-cli-service lint"
}

Make sure to re-start the npm server to avoid unnecessary insanity.

The documentation shows that one can effectively get the same result by adding --port 8080 to the end of the npm run serve command like so: npm run serve --port 8080. I preferred editing the package.json directly to avoid extra typing, but editing npm run serve --port 1234 inline may come in handy for some.
Answer: To change the port (NPM), go to package.json. In scripts write your own script, for example:
"start": "npm run serve --port [PORT YOU WANT]"

After that you can start with npm start
Comment: Please provide a detailed explanation to your answer, in order for the next user to understand your answer better. Also, provide a basic coverage of the content of your link, in case it stops working in the future.
Answer: Add the PORT envvariable to your serve script in package.json:
"serve": "PORT=4767 vue-cli-service serve",

Answer: If you want to change the port number temporarily, you can add a –port option to npm run serve command.
npm run serve -- --port 6058
Answer: You should be good with this:
"serve": "vue-cli-service serve --port 8081",
Answer: In my vue project in visual studio code, I had to set this in /config/index.js.
Change it in the:
module.exports = {
    dev: {
          // Paths
          assetsSubDirectory: 'static',
          assetsPublicPath: '/',
          proxyTable: {},

          host: 'localhost', // can be overwritten by process.env.HOST
          port: 8090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
          autoOpenBrowser: false,
          errorOverlay: true,
          notifyOnErrors: true,
          poll: false
         }
}

Comment: I almost did the same. My file's name is 'vue.config.js' and is located at the root of the vue project. The demanded port is found on path module.exports.dev.port. Here it is set to 8090. The other key-value-pairs are not necessary (for me). That's for starting with 'npm run serve' on development mode!
Answer: If you are running this via Visual Studio Community or Professional (maybe with a .Net Core project) you will find that no matter what steps you do, when you launch the solution that it uses 8080.
Well there is launch.json file you need to edit hidden in the .vscode directory.
MS don't tell you about this at all and a file search does not seem to find it.
Answer: Go to node_modules/@vue/cli-service/lib/options.js
At the bottom inside the "devServer" unblock the codes
Now give your desired port number in the "port" :)
devServer: {
   open: process.platform === 'darwin',
   host: '0.0.0.0',
   port: 3000,  // default port 8080
   https: false,
   hotOnly: false,
   proxy: null, // string | Object
   before: app => {}
}

Comment: go to node_modules/@vue/cli-service ... ? Doesn't that get overwritten on npm update?
Comment: you don't want to make code edits - should be configurable


Pipe-fitting conditions in 3D

Question: Let's we have smooth (continuous and infinitely differential) curve $f(x(t), y(t), z(t)) = 0$ in 3D. Now I want to build a tube of diameter $D$ around it.
Questions:

What are the set of conditions this curve has to satisfy to make sure tube is not self intersecting and surface area is still smooth (differential)? Checking for curvature at every point to be $\lt \frac{D}{2}$ is not sufficient.
How to estimate volume of the tube between given points on the curve?
Comment: It is regular and without self-intersections.
Comment: Are you assuming your curve is _regular_, i.e., has non-vanishing velocity?
Answer: Regarding your second point, I am quoting from the book:
ABBENA, Elsa; SALAMON, Simon; GRAY, Alfred. Modern differential geometry of curves and surfaces with Mathematica. CRC press, 2006.

A tube about a curve $\gamma$ in $\mathbb{R}^3$ has the following
  interesting property: the volume depends only on the length of
  $\gamma$ and radius of the tube. In particular, the volume of the tube
  does not depend on the curvature or torsion of $\gamma$. Thus, for
  example, tubes of the same radius about a circle and a helix of the
  same length will have the same volume. For the proofs of these facts
  and the study of tubes in higher dimensions, see [Gray]1.
1A. Gray , Tubes, 2nd Edition, Progress in
  Mathematics 221, Birkhäuser Verlag, Basel-Boston, 2004.

So, if I properly understood the above, the volume of the tube between two points $A\in \gamma$ and $B \in \gamma$ is
$\pi r^2 L(A,B)$
where $r$ is the radius of the tube and $L(A,B)$ is the length of the curve between $A$ and $B$.
A full proof is from page 5 to 7 of the above mentioned [Gray]; I found pages 5-7 available at books.google.it
Check also page 11 of Curvature and Convexity I by Erin Pearse.

Pipe-fitting conditions in 3D


Binary relations, closures and equivalences

Question: Let $R$ be the relation on $Z$ such that $xRy \iff x-y=c$.
Well, what I have so far is $R=\{ 0,-1,1,0,-1,1,0 \cdots\}$

Is $R^* $ and equivalence relation? Why not?

This is where problems start: I don't know what the definition of $R^* $. In fact, I cannot seem to find anything related to this in my notes. First off, is my relation $R$ correct at this point?
Comment: Unless $\;c=0\; $ the relation has no chance whatsoever to be reflexive and, thus, not an equivalence relation...But then you see what you get if $\;c=0\;$ , right? :)
Comment: @Dimitri : your question has several issues.  You never defined what $R^*$ is (an apparent typo).  Your "$R$" (which maybe was supposed to be $R^*$"?) should be a set of ordered pairs, and it isn't.
Comment: @DonAntonio: The question was not whether $R$ is an equivalence relation, but whether $R^*$ is -- I suppose this notation means the reflexive transitive closure of $R$.
Comment: Well, I see now...I've no idea what $\;R^*\;$ can be.
Comment: @HenningMakholm I have never seen this notation before and it has been causing me some problems.
Comment: $R^*$ for reflexive transitive closure is commonly encountered _at least_ in connection with rewrite systems (such as the $\lambda$-calculus). Since this is tagged "discrete math" which is usually a support course for computer science, I think it is likely that this is the relevant meaning here.
Comment: @HenningMakholm I see now. And you're right, it is a Computer Science course. So this is just plain notation for a transitive closure?
Comment: If $\;R^*\;$ is *only* the reflexive/transitive closure then we still have issues here with symmetry, don't we?
Comment: Dimitri: Transitive _and reflexive_ closure, I would assume. The pure transitive closure would usually be $R^+$ (by analogy with regular expressions, for example). @DonAntonio: Yes, there are still symmetry issues.
Comment: In fact, when $c=1$ the resulting $R^*$ is a well-known relation on $\mathbb Z$...
Comment: With $\;c=0\;$ we get an even more well-known relation, me thinks...and way more boring, too.
Comment: If $R \subseteq  \Bbb Z X \Bbb Z$, then the only time $c=1$ is when $x>y$, no ?
Comment: @Dimitri: Right. Or when $x=y$, since the star (called the Kleene star) is the _reflexive_ transitive closure.
Comment: @HenningMakholm So, how do I formally define what $R^*$ is?
Comment: @Dimitri: One possibility would be "the intersection of all relations that contain $R$ and are reflexive and transitive".
Comment: You might want to look at [this question](http://math.stackexchange.com/questions/578754/relation-squared-of-xry-iff-x-y-c/586076#586076) about the same relation.
Answer: Your relation is not correct. A relation is defined to be a set of ordered pairs where the ordered pair (x,y) is included if xRy.


How to to write Computed_field code?

Question: I'm testing the computed_field module on a taxonomy field. I want to get the number of nodes that have a term reference to the current term:
<code>$tid = 1;
$entity_field[0]['value'] =  db_query("
SELECT count(*)
FROM node n INNER JOIN taxonomy_index t on n.nid = t.nid
WHERE n.type = 'discussion'
and n.status = 1
and t.tid=$tid")->fetchField();
</code>
How can I get the tid of the term? Is there a better way of writing the query?
Answer: A query like that should do the trick, but if you want something more elegant, I recommend EntityFieldQuery.

How to to write Computed_field code?


Proving a Limit Involving a Square Root Function Using Epsilon and Delta

Question: The question gave me this limit to proof the result by using epsilon-delta:
$\lim_{x\to 0} \sqrt{4-x} = 2$
It seems to be using conjugate multiplication, but I got lost and I didn't know how to proceed in order to find $\delta$.
If its possible, show me your equation developtment please.
Ps.: My problem here is just to find $\delta$, I know what to do next.
All help is appreciated and adored!
Answer: $|\sqrt{4-x}-2|=|\frac{(\sqrt{4-x}-2)(\sqrt{4-x}+2)}{\sqrt{4-x}+2}|=|\frac{x}{\sqrt{4-x}+2}|$
Note that if $|x|\leq 1$ then $\sqrt{4-x}+2\geq \sqrt{3}+2$ and in that case we get $|\sqrt{4-x}-2|\leq\frac{|x|}{\sqrt{3}+2}$. We want that expression to be at most $\epsilon$, and it happens when $|x|\leq\epsilon(\sqrt{3}+2)$. Since we also had to assume $|x|\leq 1$ we take $\delta=\min\{1,\ \epsilon(\sqrt{3}+2)\}$.
Comment: Well done! Thanks for your help


How to traverse to a child object from a parent object using in test-complete tool?

Question: I am automating a mobile application using TestComplete tool. I have to get the text of an object from the UI, but the object id keep on changing while change of values. So is there any option in test complete which support -following-sibling or Child Property which exist in selenium tool. So that we can easily traverse from a parent object to track the child or sibling. Please help.
Comment: You question is too general, focus it and add the code you write up to this point.
Answer: You need to find a property or a set of properties that will uniquely identify the needed object without using its native id. Use these identification criteria to set up the corresponding Name Mapping scheme for this object.
PS. Of course, having a permanent ID for a UI object is the best way to automate tests with the object.


Log a message that changes in rust?

Question: I'm trying to log a message that can change with variables.
What I mean:

print message with vars a, b
remove message
print it again with different values for a, b

Now, it's not exactly a progress bar so I can't use something like inidcatif.
I've tried using this:
let message = format!(
    "\x1B[2K\rA: {}, B: {}",
    a, b
);

print!("{}", message);
std::io::stdout().flush().unwrap();

This just prints the line a bunch of times and doesn't change the line.
This is a docker-compose log
Comment: In which terminal do you see this problem? I have tried your code and every line is cleared and overwritten by the following message.
Comment: Oh, I forgot to add that. It's a Docker compose log
Comment: Please [edit] your question to add crucial information instead of hiding that info in comments.
Comment: I did, it just didn't submit it, so it didn't get approved...? I don't know how this platform works tbh
Answer: Does your terminal actually support ANSI escape codes? Because it works fine for me:
use std::io::Write;

fn main() {
    for (a, b) in std::iter::zip(0.., &["A", "B", "C", "D"]) {
        let message = format!("\x1B[2K\rA: {}, B: {}", a, b);

        print!("{}", message);
        std::io::stdout().flush().unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1))
    }
}

does show the line changing over time.
Incidentally the format! is unnecessary, you can format everything in print! directly
use std::io::Write;

fn main() {
    for (a, b) in std::iter::zip(0.., &["A", "B", "C", "D"]) {
        print!("\x1B[2K\rA: {a}, B: {b}");
        std::io::stdout().flush().unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1))
    }
}

Comment: Well, I forgot to mention it, it's a Docker (compose) log.

Log a message that changes in rust?


Setting up OpenVPN server: should I use tun or tap?

Question: I'm trying to set up my first OpenVPN server, and I'm having trouble figuring out whether I should use tun or tap for my particular setup.
I have an Amazon VPC with a few EC2 instances running Windows Server 2012 that will be used as workstations. In the VPC there's also a file server (also running WS2012) that workstations connect to via SMB.
Specifically, I'm trying to set up an OpenVPN server (this one on Ubuntu) to allow remote clients to connect to the VPC, and then use RDP to access the workstations themselves.
I tried using tun, but I still can't get the client to see the workstations on the network (I try to RDP to the workstations and the connection fails, ping also). I know this could be due to many reasons, so I'm trying to discard the things where I could've gone wrong. I guess tun would be the best choice since I don't need to use any non-IP protocols and it would be more efficient, but I'd like to be sure.
By the way, I've been following this guide: https://openvpn.net/index.php/open-source/documentation/howto.html
Thanks in advance.
Comment: Tunnel is probably fine. Your problem is likely that the tunnel interface gets its own subnet, it isn't on the same subnet as the server's regular network connection. You need to push routes with your  OpenVPN server config, and the server's OS needs some configuration as well. I have no idea how to tackle this with Windows though, sorry.
Answer: I use tun for this exact use-case in our VPC (we use linux rather than windows, but that aside its the same).  So I'd say tun is acceptable in this case.
Things to look for are:

Is the OpenVPN server within the VPC passing traffic? Most Linux distributions do not by default forward IP traffic. This should be easy to test by running a sniffer on the Openvpn server and looking for traffic leaving its network interface destined for another machine in the VPC
Is the OpenVPN server NATing the traffic? We use NAT on the OpenVPN server, so other servers within the VPC 'see' the traffic as if it came from the OpenVPN server. In a non AWS network this isn't a requirement, however I've never used OpenVPN with a VPC without NAT so I cannot comment if this works.
Is it the security group applied to the instance you are RDP'ing to that is preventing the traffic? Should be easy to temporarily allow all traffic to an instance as a test.
Is the local (on the RDP server) firewall blocking any traffic?

As a rule when debugging OpenVPN I find running a network sniffer on the ethernet nic of the OpenVPN box AND on the ethernet nic on a destination machine helps tremendously with identifying where the traffic is being stopped or blocked.
Comment: This answer seems accurate.  Without NAT, you'd need to disable the "IP ssource/dest check" on the tunnel server instance, and the client subnet would need to be *outside* the supernet for the VPC and routed to the tunnel servet via the VPC routing tables.


solr gives same score for different values

Question: I have field type defined in my schema.xml such as follows;
<code>    <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
        <analyzer>
            <tokenizer class="solr.StandardTokenizerFactory" />
            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.WordDelimiterFilterFactory"
                generateWordParts="1" generateNumberParts="1" catenateWords="1"
                catenateNumbers="1" catenateAll="0" splitOnCaseChange="0" />
            <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
        </analyzer>
    </fieldType>
</code>
Here is my field;
<code><dynamicField name="*_text" type="text" indexed="true" stored="true" />
</code>
When I query the value "am26" in solr admin query board, I am having following results in my document. (There are many fields exist however, I just select code_text and score fields to show)
<code>"response": {
"numFound": 6,
"start": 0,
"maxScore": 1184.7297,
"docs": [
  {
    "code_text": "AM232",
    "score": 1184.7297
  },
  {
    "code_text": "AM238",
    "score": 1184.7297
  },
  {
    "code_text": "AM266",
    "score": 1184.7297
  },
  {
    "code_text": "AM268",
    "score": 1184.7297
  },
  {
    "code_text": "AM269",
    "score": 1184.7297
  },
  {
    "code_text": "AM273",
    "score": 1184.7297
  },
]
</code>
How come score of AM232 and AM266 could be the same ? Furthermore, how come we can see values like AM232 and AM273 among the results ?  Far as I aware when we query "am26" solr first converts this string into lower case (according to definition in schema.xml) and WordDelimiterFilterFactory splits string as am,26. So I can understand the results which includes 26 and AM but I don't know why I see "AM232" and "AM273" in my document. Plus they have exact score.
Answer: As you said, your search terms will be: "am" and "26"
However, there is no wildcard involved in this search.  All of the results given match the "am" part, but none of them match "26".  For "AM266", the indexed terms are "am" and "266".  But the term "26" is still not a match for "266".  I expect if you had a document "AM26", you would indeed see that get a higher score that the others.
Comment: As I said, the term "26" matches *none* of the documents.  The term "26" matches the term "266" exactly as well as it matches "steve", which is to say, not at all.
Comment: Thanks for your answer. Although document AM266 is not exact match for the search term AM26, it has higher hit. 4 characters are matching. The main point that I am struggling to understand is  how come AM232 and AM266 has exact same score. I would expect AM232 to less score comparing with AM266.
Comment: For your: `4 characters are matching` -> this is wrong. Only `AM` will match. You can use analysis tool in solr admin page to observe that.
Comment: Thanks for your answer alexf and femtoRgon. I changed my query such as like that code_sortabletext:(am26*^150.0) and it works now. I needed to boost that field with the value of 150 because there are other fields which has some values makes noise in the search and priority is the code field for me. Thanks very much again.


Extending a continuous function by one point, is the resulting function continuous as well?

Question: Let's say I have a continuous function $f: \mathbb{R} - \{0\} \rightarrow \mathbb{R}$. Suppose I extend $f$ to a function $g$ such that  $g:\mathbb{R} \rightarrow \mathbb{R} \cup \{\infty\}$ where $g(x) = f(x)$ for all $x \neq 0$ and $g(0) = \infty$. Is the resulting function $g$ continuous?
I have an idea to use the pasting lemma somehow, but I cannot seem to convince that the part I'm pasting, $g(0) = \infty$ is actuall continuous. Thanks.
Comment: If $\lim_{x\to 0}f(x)=\infty$ then $g$ is continuous.
Comment: I think you may have a particular situation in mind which you have not fully described. But think about arbitrarily assigning a value for a function at a point (the rest of the continuous function being given) - what chance is there that the resulting function will be continuous? (See Marco's answer for detail of one possibility). This highlights the need to identify the constraints in your problem completely and with precision - but testing like this is just what mathematicians do to identify the gaps.
Answer: No. Let $f: \mathbb{R} \to \mathbb{R}$ be continuous. Then $f$ is also continuous on $\mathbb{R}-{0}$. Clearly, the corresponding function $g$ (refering to your notation) is not continuous.
Answer: You cannot apply the pasting lemma here because you are pasting the closed set $\{0\}$ with the open set given by its complement. The pasting lemma applies to sets both open or both closed.


Erro ao alterar fonte de texto - android

Question: Olá, estou a criar um app de login e quero alterar a fonte de um textView mas está me a dar o seguinte erro:

Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference

XML:
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        tools:context=".Login">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="visible"
            android:orientation="vertical">

            <TextView
                android:id="@+id/user"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10sp"
                android:layout_marginTop="10sp"
                android:text="E-Mail ou NIF"
                android:textColor="#fff"
                android:textSize="20sp" />

            <EditText
                android:id="@+id/mail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="3sp"
                android:layout_marginTop="40sp"
                android:ems="10"
                android:inputType="textPersonName"
                android:text=""
                android:textColor="#fff"
                android:textColorHighlight="#000" />

            <TextView
                android:id="@+id/pass"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10sp"
                android:layout_marginTop="20sp"
                android:text="Password"
                android:textColor="#fff"
                android:textSize="20sp" />

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20sp"
                android:ems="10"
                android:inputType="textPassword"
                android:textColor="#fff"
                android:textColorHighlight="#000" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <Button
                    android:id="@+id/button"
                    android:layout_width="318dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="20sp"
                    android:background="#09C"
                    android:onClick="entrar"
                    android:text="Entrar"
                    android:textColor="#fff" />

                <Button
                    android:id="@+id/button2"
                    android:layout_width="318dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10sp"
                    android:background="#09C"
                    android:text="Criar uma conta"
                    android:textColor="#fff" />

            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tvproc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#fff"
                android:textAlignment="center"
                android:layout_marginTop="200sp"
                android:textSize="30sp"
                android:text="A Processar" />

            <ProgressBar
                android:id="@+id/progressBar"
                style="?android:attr/progressBarStyle"
                android:layout_marginTop="30sp"
                android:indeterminateTint="#fff"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </RelativeLayout>

Java:
package imm.pt.immsmart;

    import android.content.Intent;
    import android.graphics.Typeface;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    import org.json.JSONException;
    import org.json.JSONObject;

    public class Login extends AppCompatActivity {
        public String res;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            TextView tvu = (TextView) findViewById(R.id.user);
            Typeface font = Typeface.createFromAsset(getAssets(), "fonts/open.ttf");
            tvu.setTypeface(font);
            TextView tvp = (TextView) findViewById(R.id.pass);
            Typeface fontp = Typeface.createFromAsset(getAssets(), "fonts/open.ttf");
            tvp.setTypeface(fontp);
        }

    }

Comment: Vejo o código do `onCreate()` de outra Activity e encontrará o que falta nessa. Quando encontrar a linha que falta tente perceber porque ela é necessária.
Answer: Você não está criando nenhum link da sua activity com esse xml. É necessário o setContentView(id) no onCreate. Ficaria +- assim

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.meu_xml);
            TextView tvu = (TextView) findViewById(R.id.user);
            [...]

            }


Effect of varying outcome duration in longitudinal studies

Question: I have a supervised classifier model (regularized discriminant) which predicts the probability of an event occurring within two years.
This model was developed using sensor data measured from a baseline assessment and followed up for the occurrence of an event two years later (outcome is a binary variable, 'Y' or 'N').
I wish to validate this method using a separate, independent test set. This independent test set contains the same baseline sensor data (measurements) but follow-up was recorded after one year (rather than two).
My question has two parts:

How should I excpect this shorter follow-up period to affect the models performance? (i.e. should I expect lower sensitivity for prediction of events, as events may not have happened yet within follow-up period)?
Is there a way to correct for this shorter outcome period (e.g. treat all outcome data as having equal hazard of 0.5 probability and therefore randomly label half of data points labelled 'Y' as 'N')?
Answer: If you assume your events occurs in a poisson process, then the waiting time until an event is exponentially distributed with density function
$$
    f_Y(y) = \lambda e^{-\lambda y} \qquad \text{for}~~ y>0
$$
($\lambda>0$, the expectation of $Y$ is $1/\lambda$). Then the probability of an event in no more time than $a$ years is (a simple integral)
$P(Y \le a)=1-e^{-\lambda a}$. Calculate this with $a=1$ and then with $a=2$ and you get your correction factor.
You must of course think about IF this is a defensible assumption!


How to get a shared path for dropbox node.js api when uploading a file?

Question: I am using this dropbox api library for node.js
https://github.com/dropbox/dropbox-sdk-js/blob/master/examples/node/upload.js
I am uploading a file using that code, but how do I get its shared path? The response I am getting is this which doesn't have it.
{ name: 'boo.txt',
  path_lower: '/boo.txt',
  path_display: '/boo.txt',
  id: 'id:0FFbLAVKMuAAAAAAAAAACA',
  client_modified: '2016-08-08T21:58:24Z',
  server_modified: '2016-08-08T21:58:24Z',
  rev: 'd4c5d5dc3',
  size: 3 }

Does anyone know?
Thanks
Answer: If by "shared path" you mean the shared link for the file, you'll need to call sharingCreateSharedLinkWithSettings to create a shared link for the file with path being the path to the file.
Or, if one does already exist, you can call sharingListSharedLinks with path being the path to the file and direct_only=true.
Comment: an example on how to implement would be really helpful.
Comment: @Miraz I've answered your new post here: https://stackoverflow.com/questions/74558459/get-link-to-the-uploaded-image-in-dropbox-using-js-and-sdk


Equivalent definitions of Chern classes

Question: I have met two different definitions for Chern classes and I am wondering how are they all the same?
The first one is from Jöran Schlömer's book and they define the Chern class of a complex vector bundle $E \to M$ via the coefficients of $\det\left(tI - \frac{1}{2\pi i}A\right)= \sum_{k=0}^n f_k(A)t^{n-k}$ by setting $$c_k(E) = [f_k(\Omega)]$$ where $\Omega$ is the curvature matrix. The problem I have with this one is that I think it should be $$c_k(E) = \left[f_k\left(\frac{1}{2\pi i} \Omega\right)\right]$$ instead, but I'm no longer entirely sure.
The second definition is by Tu  and he states that the Chern classes are obtained from $$\det\left(I + \frac{i}{2\pi}\Omega\right)=1+c_1(E)+\dots+c_n(E).$$
This I think is the total Chern class instead? If anyone could elaborate on why these two should give me back the same thing and whether or not it should be $$c_k(E) = [f_k(\Omega)]$$ or $$c_k(E) = \left[f_k\left(\frac{1}{2\pi i} \Omega\right)\right]$$ I would be glad. I think this might be due to some sign conventions.
Comment: The definitions agree. Note that $c_j(E)\in H^{2j}(M)$, and this "weight" corresponds to the coefficient of $t^{n-j}$. With the coefficient $i/2\pi$ of $\Omega$ you get the correct polynomial in $\Omega$; you do not want further factors. Write this out explicitly for, say, the tautological line bundle on $\Bbb CP^1$ and check.
Comment: @TedShifrin I don't have Tu's book but for what it's worth Bott and Tu use the non-standard convention in their book and just set $p(E)=c(E\otimes\Bbb C)$
Comment: The reason I'm confused is because Tu defines Pontrjagin classes as $$p_k(E) = \left[f_{2k}\left(\frac{i}{2\pi}\Omega\right)\right] \in H^{4k}(M)$$  and this has the extra $i/2\pi$ factor. Shouldn't the Chern class be nothing more than $$c_k(E) = \left[f_{k}\left(\frac{i}{2\pi}\Omega\right)\right] \in H^{2k}(M)?$$ @TedShifrin
Comment: This is definitely wrong. There's also a sign question, since $p_k(E)=(-1)^kc_{2k}(E\otimes\Bbb C)$, ordinarily.
Comment: @pancini Ah, I'd forgotten about that. I don't have Tu's book, either. But the extra $i/2\pi$ factor is clearly not compatible with that, regardless of sign. :)
Answer: The two formulas are exactly the same, with no sign difference.
For your concern of the first definition, the $\frac{1}{2\pi i}$ is contained in his definition of $f_k(A)$, so he didn't need to write it again.
Yes, the second one is the total Chern class. Just let $t=1$, you match it with the first one, note
$$
\frac{i}{2\pi} = -\frac{1}{2\pi i}.
$$
Comment: For the first question, I mean if the equation were $\det(tI-A)=\sum_{k=0}^n g_k(A)t^{n-k}$, then we have $f_k(A) = g_k(\frac{1}{2\pi i} A)$. It is this $g_k(A)$ that is algebraically the more familiar elementary symmetric functions of the eigenvalues of $A$, but $f_k(A)$ in the definition of the book has all the powers of $\frac{1}{2\pi i}$ thrown in already. Indeed, $f_k(A) = (\frac{1}{2\pi i})^k g_k(A)$.
Comment: For the Pontryagin class, I think again it goes back to the definition. There seem to be two different ways to go: either do $\det(−\frac{1}{2\pi}B)$ or $\det(−\frac{1}{2\pi i}B)$. Here $B$ is skew-symmetric, so only the even degree ones are non-zero. The first one would produce $p_k(E) = (-1)^k c_{2k}(E\otimes {\mathbb C})$. The second one would produce one without sign. It seems the first one is more standard, since in real bundles, there should not be an $i$ anyway.
Comment: Thanks for the answer. Can I ask what do you mean by $\frac{1}{2\pi i}$ being contained in his definition of $f_k(A)$? That it's actually $f_k\left(\frac{1}{2\pi i} A\right)$? I could not find this mentioned in the book. @three-aggies
Comment: It would also seem that $p_k(E)=(-1)^kc_{2k}(E\otimes\Bbb C)$ is no longer valid with this definition.
Comment: Can you explain how did you manage to factor out the $(\frac{1}{2\pi i})^k$ from $g_k(\frac{1}{2\pi i} A)$? @three-aggies
Comment: $g_k(A)$ is homogeneous of degree $k$, that is, it is a homogeneous polynomial of degree $k$ in terms of the elements of the matrix $A$. (It is the sum of the principal $k$-minors of $A$, up to a sign.)

Equivalent definitions of Chern classes


i have 4 dropdowns and how can i edit and save the data mvc2

Question: i have 4 drop-downs, insert is working  and how can i edit the data and save the data to db mvc2. I got an error while update - The ViewData item that has the key 'SelectedTimeZone' is of type 'System.String' but must be of type 'IEnumerable
My Controller

    public ActionResult Edit(int id)
            {
                return View(EventModel.Edit(id));

            }

            [AcceptVerbs(HttpVerbs.Post)]
            [ValidateInput(false)]
            public ActionResult Edit(int id, EventInfo EventInfo)
            {

                    if (ModelState.IsValid)
                    {
                        EventModel.Edit(EventInfo);
                        return RedirectToAction("Index");
                    }
                    return View(EventInfo);

            }

Model

    public SelectList TimeZones { get; set; }
            public SelectList EventType { get; set; }

            private string selectedTimeZone = "";
            public string SelectedTimeZone
            {
                get { return selectedTimeZone; }
                set { selectedTimeZone = value; }
            }

   Load Function

      myEventInfo.TimeZones = new SelectList(EventModel.getTIMEZOMES, "Key", "Value");
         myEventInfo.SelectedTimeZone = Datareader["TIMEZONE"].ToString();

    public static IList<KeyValuePair<string, string>> getTIMEZOMES
            {
                get
                {
                    Dbhelper DbHelper = new Dbhelper();
                    IList<KeyValuePair<String, String>> Timezone = new List<KeyValuePair<String, String>>();
                    DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM TMP_TIMEZONES");
                    DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
                    while (Datareader.Read())
                    {
                        Timezone.Add(new KeyValuePair<String, String>(Datareader["ABBR"].ToString(), Datareader["NAME"].ToString()));
                    }

                    return Timezone;
                }
            }

View page

     <%= Html.DropDownListFor(model => model.SelectedTimeZone, Model.TimeZones, "Select Timezone", new { style = "width:200px", @class = "textfield165" })%>
                            <%= Html.ValidationMessageFor(model => model.SelectedTimeZone)%>

I got an error while update / The ViewData item that has the key 'SelectedTimeZone' is of type 'System.String' but must be of type 'IEnumerable
Answer: In your POST action you forgot to populate the TimeZones property in case of error. Don't forget that only the selected timezone is POSTed, but not the list of timezones, so if you ever intend to redisplay the same view (for example in case of error) make sure you rebind this list (the same way you bound it in the GET action that allowed you to display the form on the first place):
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Edit(int id, EventInfo EventInfo)
{
    if (ModelState.IsValid)
    {
        EventModel.Edit(EventInfo);
        return RedirectToAction("Index");
    }

    // Here you must populate the TimeZones property before returning the view
    EventInfo.TimeZones = new SelectList(EventModel.getTIMEZOMES, "Key", "Value");
    return View(EventInfo);
}

Comment: @sathishkumar, would you mind sharing how did you solve your problem? It might be helpful to other people having the same problem.


Javascript Puro: Multiplicar valores de tds em uma tabela e retornar o valor

Question: Opa galera tudo blz? Estou com uma tabela de compras e gostaria de multiplicar a quantidade do produto com o seu valor retornando assim o resultado e somar todos os resultados.
Eu já consegui fazer isso, o problema está sendo para fazer com vários produtos ele só está multiplicando todos os valores de uma vez, preciso de ajuda.

var quant = document.querySelectorAll(".quant");
var preco = document.querySelectorAll(".preco");
var total = 1;

for (var i = 0; i < quant.length && i < preco.length; i++)
{
   total*= Number(quant[i].innerHTML) * parseFloat(preco[i].innerHTML.toString().replace(",","."));
   document.querySelector(".valor").innerHTML = total.toString().replace(".",",");

}

          Produto
          Quant
          Preço
          Valor Total

          Stawka
          3
          30,50

          Stawka
          5
          25

Answer: A forma que está usando o for talvez não seja a melhor, o melhor seria fazer o for por cada linha, para garantir que pega os valores da linha, mas primeiro vamos ver o que acontece no seu código:

está usando o índice para pegar a quantidade e valor, mas não usa o índice para por o resultado, deveria ser algo como document.querySelector(".valor")[i].innerHTML;

deve zerar o valor da soma para cada linha, por isso se quiser o total geral, deve usar outra variável.

Adaptei o código com essas duas correções, veja abaixo:

var quant = document.querySelectorAll(".quant");
var preco = document.querySelectorAll(".preco");
var valor = document.querySelectorAll(".valor");
var totalLinha = 0;
var total = 0;

for (var i = 0; i < quant.length; i++)
{
   totalLinha = Number(quant[i].innerHTML) * parseFloat(preco[i].innerHTML.toString().replace(",","."));
   valor[i].innerHTML = totalLinha.toString().replace(".",",");
   total += totalLinha;
}

document.getElementById("total").innerHTML = total.toString().replace(".",",");

          Produto
          Quant
          Preço
          Valor Total

          Stawka
          3
          30,50

          Stawka
          5
          25

Total:
Comment: Muito, muito obrigado mesmo, já tava a um tempão sem conseguir resolver isso