$\lim_{x\rightarrow 0^+}(x \int ^1_x \frac{\cos t }{t^2} \, dt)$

Question: Use L'Hospital rule compute the following limit:
$$\lim_{x\rightarrow 0^+} \left(x \int ^1_x \frac{\cos t }{t^2} \, dt\right)$$
my attempt:
$$\lim_{x\rightarrow 0^+} \frac{\displaystyle \left(\int ^1_x \frac{\cos t }{t^2} \, dt\right)} x$$ ($0/0$ form)
$$=\lim _{x\to0^+}\frac{\cos x/x^2}{-x^2}=-1$$
Comment: Use integration by parts on the integral and the answer should not be difficult to obtain. You have a mistake in the use of L'Hospital's Rule,the derivative of integral is $-(\cos x) /x^{2}$ so the answer should be $1$.
Comment: @ParamanandSingh..yes i got this idea  but it some what difficult
Comment: Now you have another mistake. The denominator should be $1/x$ instead of $x$ and the form is $\text{anything} /\infty$ and not $0/0$. L'Hospital's Rule is applicable and answer is immediately arrived at as $1$.
Answer: It seems like you've almost got it! So you have
$$\lim_{x\rightarrow 0^+} \frac{\displaystyle \left(\int ^1_x \frac{\cos t }{t^2} \, dt\right)}{(1/x)}$$
Which is a good step. Then you apply L'Hopital's rule:
$$\lim_{x\rightarrow 0^+} \frac{\displaystyle \frac{d}{dx} \left(\int ^1_x \frac{\cos t }{t^2} \, dt\right)}{\displaystyle\frac{d}{dx} \left( \frac{1}{x}\right)}$$
Observe that $\frac{d}{dx} \left(\int ^1_x \frac{\cos t }{t^2} \, dt\right) = -\frac{d}{dx} \left(\int ^x_1 \frac{\cos t }{t^2} \, dt\right) = -\frac{\cos x }{x^2}$ and $\frac{d}{dx} \left(\frac{1}{x}\right) = -\frac{1}{x^2}$. This gives,
$$\lim _{x\to0^+}\frac{\cos x}{-x^2} \large/\frac{-1}{x^2} = \lim _{x\to0^+} \cos x = 1$$
So just a couple mistakes on your part. The first was writing $x$ instead of $1/x$ in the denominator, and the second when you applied the FTC to the integral which put you off by a minus sign.
Comment: You need to learn a bit more about this infamous L'Hospital's Rule. Check the proof in Wikipedia (https://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule) where it shows that the rule applies to the form $\text{anything} /\infty$. Also the rule works only when the limit of $f'(x) /g'(x) $ exists finitely or infinitely. In the example you gave the rule fails because the limit of $f'(x) /g'(x) $ does not exist.
Comment: Don't worry. You are not alone in this situation. The root cause of all this are crappy textbooks which don't highlight the intricacies of L'Hospital's Rule.
Comment: @AlkaKadri...thank you
Comment: No problem! Note that there's the technicality of showing that $\int_x^1 \frac{\cos t}{t^2}\ dt \to\infty$ as $x \to 0^+$, but that's not too hard to see I think.
Comment: @AlkaKadri: that technicality is not needed. See my comments to question. L'Hospital's Rule is applicable when denominator tends to $\infty$ and in that case there is no need to check numerator.
Comment: @ParamanandSingh That is false. You need an indeterminate form to apply L'Hopital's rule. Consider $\lim_{x \to \infty} \frac{\sin x}{x}$. Clearly the limit is equal to 0, but if we naiively apply L'Hopital's because the denominator tends to infinity then we get $\lim_{x \to \infty} \cos x$, which does not exist.
Comment: It is because of the fact that most people (including you) are unaware of the exact hypotheses under which L'Hospital's Rule works that the rule should be avoided in preference to other methods like Taylor's theorem.
Comment: @ParamanandSingh very interesting. It's surprising how many years one can go without seeing that proof (my bad). I suppose that in this case we indeed have something of the form $x \to c$ for $c \in \mathbb{R}$, whereas the counterexample up there with $x \to \infty$ that I've kept back of my mind is another beast entirely. Thank you for this!
Answer: Note that using integration by parts we have $$\int_{x} ^{1}\frac{\cos t} {t^{2}}\,dt=\frac{\cos x} {x} - \cos 1-\int_{x}^{1}\frac{\sin t} {t} \, dt$$ and multiplying by $x$ and taking limit as $x\to 0^{+}$ we can see that the limit is $1$.
Comment: @ParamanandSingh...how did u get 1
Comment: @suresh: When you multiply by $x$ the first term becomes $\cos x$ and it tends to $1$. Rest of the terms have $x$ as a factor so tend to $0$.
Comment: You forgot to point out that $\int_x^1 \sin{t}/t \,\mathrm{d}t$ converges as $x \to 0$.
Comment: @ParamanandSingh..thank you too i got it
Comment: @tristan: there is nothing to converge as the integral $\int_{0}^{1}\frac{\sin t} {t} \, dt$ exists as a Riemann integral and hence the function $g(x) =\int_{x} ^{1}\frac{\sin t} {t} \, dt$ tends to $g(0)$ as $x\to 0^{+}$.
Comment: Yes of course, but I wouldn't say this is completely trivial since one has to first extend the function $t\mapsto \sin{t}/t$ by continuity at $t=0$.
Comment: @tristan: the function under consideration is bounded in $[0,1]$ and has only one discontinuity at $0$ so it is Riemann integrable. But yes yes it is not trivial to notice this fact. I would consider is somewhere between trivial and non-trivial I terms of difficulty.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\lim_{x \to 0^{\large +}}\bracks{x\int_{x}^{1}{\cos\pars{t} \over t^{2}}\,\dd t} & =
\lim_{x \to 0^{\large +}}\bracks{%
x\int_{x}^{1}{\cos\pars{t} - 1 \over t^{2}}\,\dd t +
x\int_{x}^{1}{\dd t \over t^{2}}}
\\[5mm] & =
\lim_{x \to 0^{\large +}}\bracks{%
x\int_{x}^{1}{\cos\pars{t} - 1 \over t^{2}}\,\dd t - x + 1} =\bbx{1}
\end{align}
Comment: This one is perhaps even simpler than my answer (although it uses similar idea). +1
Comment: @ParamanandSingh I agree. They are quite close. $\left.\substack{{\Huge\bullet}\\ {\Huge \smile}}\right\}$


Linked List: error: expected initializer before '<' token

Question: I am getting the error "error: expected initializer before '<' token" when compiling, I need to create a linked list, and I need to turn one of the functions into a template for an assignment, I was wondering how I can fix the error that I am getting.
#ifndef LINK_H
#define LINK_H

class link {
public:
    int data;
    link *lnkPtr;
};

class linked
{
private:

      link  *head;
public:

        linked(){head = nullptr;}
        ~linked(){};
        void nodeEnd(link *, double num);
        template <class T>
        T nodeBeg<T>(link *, T num);
        void nodeIst(link *, double num);
        void nodeDel(link *, double num);
        link fillLst(int);
        void prntLst(link *);
        void destLst(link *);
        link endLst(link *);
        //void addlink(link *, int);
};

  template <class T>
  T linked<T>::nodeBeg(link* , T num)
{
     link *newNode; // To point to a new node
     link *nodePtr; // To move through the list

     // Allocate a new node and store num there.
     newNode = new link;
     newNode->data = num;
     newNode->lnkPtr = nullptr;

     // If there are no nodes in the list
     // make newNode the first node.
      if (!head)
         head = newNode;
      else // Otherwise, insert newNode at end.
      {
         // Initialize nodePtr to head of list.
         nodePtr = head;

         // Find the last node in the list.
         // while (!nodePtr->linkPtr)
            nodePtr = nodePtr->lnkPtr;

         nodePtr->lnkPtr = head; //inserts at beginning
      }
}
#endif /* LINK_H */

Comment: class `linked` is not a template. So `linked` doesn't make any sense.
Comment: @sam would I be able to make it a template without making all other member functions a template, or would I need to make another class for the function I need to be a template?
Comment: @Ethan_J  no that's two different things
Comment: @Ethan_J Please refer to my answer for your doubt.
Answer: Remove the <T> from T nodeBeg<T>(link *, T num); and T linked<T>::nodeBeg(link* , T num) .T nodeBeg(link *, T num) and T linked::nodeBeg(link* , T num) will tell the compiler to deduce the return type at compile time. Also neither the function nodeBeg nor the class linked are templates so you don't need the <T>.
Answer: There are some syntax errors in your code.
nodeBeg is a function template.
It's declaration should be as follows:
template <class T> T nodeBeg(link *, T num);

The definition should be as follows:
template <class T> T linked::nodeBeg(link*, T num) {/*...*/}

Here you have to attach linked:: to the function name, to tell the compiler that you are defining here the member nodeBeg of class linked.
Answer: Remove <T> after identifiers.  Parameter list after an id is a specialization is mean for template specialization.
Template of class and member template are two different things.. member can be a template within template class or it may be not, or class might be a template. if member of template class is template, it got two parameter list.
template<typename T1>
struct string {
    // member template function
    template<typename T2>
    int compare(const T2&);
    // constructors can be templates too
    template<typename T2>
    string(const std::basic_string<T2>& s) { /*...*/ }
};
// out of class definition of string<T1>::compare<T2>
template<typename T1> // for the enclosing class template
template<typename T2> // for the member template
int string<T1>::compare(const T2& s) { /* ... */ }

(from http://en.cppreference.com/w/cpp/language/member_template )


Gradient for logistic loss function

Question: I would ask a question related to this one.
I found an example of writing custom loss function for xgboost here:
loglossobj <- function(preds, dtrain) {
  # dtrain is the internal format of the training data
  # We extract the labels from the training data
  labels <- getinfo(dtrain, "label")
  # We compute the 1st and 2nd gradient, as grad and hess
  preds <- 1/(1 + exp(-preds))
  grad <- preds - labels
  hess <- preds * (1 - preds)
  # Return the result as a list
  return(list(grad = grad, hess = hess))
}

Logistic loss function is
$$log(1+e^{-yP})$$
where $P$ is log-odds and $y$ is labels (0 or 1).
My question is: how we can get gradient (first derivative) simply equal to difference between true values and predicted probabilities (calculated from log-odds as preds <- 1/(1 + exp(-preds)))?
Comment: You should use squared error loss to achieve that. Your notation is confusing and should be defined in the post. If $p$ is the predicted risk, then $(y-p)^2$ loss is what you want. I'm confused because we *never* use $p$ to mean the log-odds.
Comment: $p$ was fixed to capital $P$. It is log-odds, and it is clearly marked in the question. I know that gradient for loss function $(y-f(x))^2$ is $f(x)-y$, but it is squred loss, not logistic.
Comment: When you say the "gradient",  what gradient do you mean? The gradient of the loss? It's a simple mathematical relationship that if the derivative of an expression is a linear difference, then the expression is a quadratic difference, or squared error loss.
Comment: Yes, it is all about gradient of the loss. It is simple, when loss function is squared error. In this case loss function is logistic loss (https://en.wikipedia.org/wiki/LogitBoost), and I can't find correspondence between gradient of this function and given code example.
Answer: My answer for my question: yes, it can be shown that gradient for logistic loss is equal to difference between true values and predicted probabilities. Brief explanation was found here.
First, logistic loss is just negative log-likelihood, so we can start with expression for log-likelihood (p. 74 - this expression is log-likelihood itself, not negative log-likelihood):
$$L=y_{i}\cdot log(p_{i})+(1-y_{i})\cdot log(1-p_{i})$$
$p_{i}$ is logistic function: $p_{i}=\frac{1}{1+e^{-\hat{y}_{i}}}$, where $\hat{y}_{i}$ is predicted values before logistic transformation (i.e., log-odds):
$$L=y_{i}\cdot log\left(\frac{1}{1+e^{-\hat{y}_{i}}}\right)+(1-y_{i})\cdot log\left(\frac{e^{-\hat{y}_{i}}}{1+e^{-\hat{y}_{i}}}\right)$$
First derivative obtained using Wolfram Alpha:
$${L}'=\frac{y_{i}-(1-y_{i})\cdot e^{\hat{y}_{i}}}{1+e^{\hat{y}_{i}}}$$
After multiplying by $\frac{e^{-\hat{y}_{i}}}{e^{-\hat{y}_{i}}}$:
$${L}'=\frac{y_{i}\cdot e^{-\hat{y}_{i}}+y_{i}-1}{1+e^{-\hat{y}_{i}}}=
\frac{y_{i}\cdot (1+e^{-\hat{y}_{i}})}{1+e^{-\hat{y}_{i}}}-\frac{1}{1+e^{-\hat{y}_{i}}}=y_{i}-p_{i}$$
After changing sign we have expression for gradient of logistic loss function:
$$p_{i}-y_{i}$$
Comment: What you're calling $\hat{y}$ here is *not* a prediction of $y$, but a linear combination of predictors. In generalized linear modeling we use the notation $\nu$ and call this term the "linear predictor". Your derivative of the loglikelihood (score) is wrong, there should be a squared term in the denominator, since bernoullis form an exponential likelihood. The score should be of the form $\frac{1}{p_i(1-p_i)}(y_i - p_i)$
Answer: AdamO is correct, if you just want the gradient of the logistic loss (what the op asked for in the title), then it needs a 1/p(1-p). Unfortunately people from the DL community for some reason assume logistic loss to always be bundled with a sigmoid, and pack their gradients together and call that the logistic loss gradient (the internet is filled with posts asserting this). Since the gradient of sigmoid happens to be p(1-p) it eliminates the 1/p(1-p) of the logistic loss gradient. But if you are implementing SGD (walking back the layers), and applying the sigmoid gradient when you get to the sigmoid, then you need to start with the actual logistic loss gradient -- which has a 1/p(1-p).

Gradient for logistic loss function


Covariance Matrix

Question: Please excuse my ignorance here. It has been awhile since I have studied linear algebra. As far as I know, a covariance matrix is often written as
COV = $\frac{1}{n-1}$ A $\cdot$ A$^T$.
Is this the same thing as
COV = $\frac{1}{n-1}$ A$^T$ $\cdot$ A ?
The reason I ask, is this can be the difference between a massive matrix or a very small matrix (for Casorati style matrices).
Ultimately, I am studying PCA, which uses the covariance matrix.
Comment: You already answered your question: since the matrices $AA^\prime$ and $A^\prime A$ have different sizes, they cannot possibly be the same.  Perhaps what you want to ask should concern what PCA-related information could be extracted from the smaller of those two matrices.
Answer: Edit: Whuber answered it better: $AA^T$ and $A^TA$ have different dimensions, so they won't be equal
Your question basically asks is $A A^T = A^T A$? In general, the answer is no.
Define $C=AB$ for matrices $A,B$. The element at row $i$, column $j$ of $C$ is $C_{i,j}=\sum_k A_{i,k}B_{k,j}$, by the definition of matrix multiplication. If $AA^T=A^TA$, then element-wise they should be the same. Of course, A must have the same number of rows and columns, otherwise the two products have different dimensions, so the answer is no in that case. If $A$ is a square matrix, though, we can write the condition needed for the equality to hold:
If we let $C=AA^T$, then $C_{i,j}=\sum_k A_{i,k} (A^T)_{k,j}=\sum_k A_{i,k} A_{j,k}$ by the property of matrix transpose $A_{i,j} = (A^T)_{j,i}$.
Now, consider $C'=A^TA$. We have that $C'_{i,j}=\sum_k (A^T)_{i,k} A_{k,j}=\sum_k A_{k,i} A_{k,j}$.
Since, in general, $\sum_k A_{k,i} A_{k,j} \neq \sum_k A_{i,k} A_{j,k}$, we have that $A A^T \neq A^T A$ for $A$ a square matrix.
Some notable exceptions for which $A^TA=AA^T$ are the identity matrix and symmetric matrices where $A=A^T$, but since in PCA $A$ is usually a design matrix (rows are observations, columns are features), you won't be any of these exceptions.
Comment: Given a design matrix $X$ with $N$ rows and $M$ features, so $X\in \mathbb R^N \times \mathbb R^M$, the covariance matrix $XX^T$ will have elements $C_{i,J} = cov(x_i, x_j)$, where $x_i, x_j$ are your features. The covariance is estimated using all of the observations you have (all $N$ for each variable), so thats how it collapses down to a 20x20 matrix in your case (because you have 20 features, it seems). What do you mean when you say project the 20,000x20 matrix onto the covariance matrix?  Did you diagonalize the covariance matrix to get the principal components and just change the basis?
Comment: Perhaps I'm misunderstanding, but just multiplying $DM \times E$ doesn't do a change of basis. If you have a matrix $A$ and your matrix of eigenvectors $E$, to change the basis of $A$ you need to do $A'=E^{-1} A E$. Also, just to confirm: you only have 20 features? Whether or not the covariance matrix is given by $AA^T$ vs $A^TA$ depends on whether the rows of $A$ are observations and the columns are features, or visa versa. For the former (which is more standard), $AA^T$ is the covariance matrix, and for the later, you need to do $A^TA$. Which one are you using?
Comment: A matrix $A$ for which $A^\prime A = AA^\prime$ is called a [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix). Such matrices form the conjugacy class of the diagonal matrices: that is, the Spectral Theorem applies to them. The argument concerning why not all square matrices are normal might be made more clear by providing a simple counterexample, such as this one:$$\pmatrix{0&1\\0&0}^\prime\pmatrix{0&1\\0&0}=\pmatrix{0&0\\0&1}\ne\pmatrix{1&0\\0&0}=\pmatrix{0&1\\0&0}\pmatrix{0&1\\0&0}^\prime.$$
Comment: Sweet name btw. Essentially, I am generating eigenfaces. What I do, is calculated the $COV$ using $A^TA$, as the matrix is tiny (20x20). I then project my Casorati matrix (20,000x20) of face images onto the small $COV$ matrix. This yields 20 images, of principal components. So perhaps I am confused why I can do this?
Comment: Sorry, my math lingo is terrible. Also, I missed a step. I calculate the eigenvectors ($E$) of the 20x20 $COV$ matrix (yields 20x20 $E$ matrix). Then I take my demeaned images ($DM$) and multiply them to the $E$ matrix ($DM \times E$), which is 20,000x20 $\times$ 20x20 $\rightarrow$ my 20 images. I hope this is clear.
Comment: As stated by the higgs broson: "Whether or not the covariance matrix is given by AA$^T$ vs A$^T$A depends on whether the rows of A are observations and the columns are features, or visa versa". This answers my questions! A real duh moment for me. Thanks!

Covariance Matrix


Am I missing something about pushing a PS script via domain GPO

Question: I've got a script that works.  See here.
Now my problem is getting it to run via a domain GPO.  On my test clients, I've set the ExecutionPolicy to unrestricted.
I've tried setting it as a startup script. (preferable)
I've tried setting it as a login script.
Nothing is getting executed.  If I run it as an admin user manually, it works.  No dice via GPO.
Edit:  I just tried a test on my XP client that has the Window Management Framework Core (KB 968930) installed.  I associated .ps1 with the powershell program; it was previously associated with Notepad.  I also set a local gpo that pointed to the script.  I rebooted the computer, and it got to the running scripts portion of startup.  It hung there for about 5 minutes before getting to the login screen.  When I logged in, the program was still installed.  No errors in the eventvwr that I can see.
When I was trying to push this out from my domain controller, I went to the Computer Configuration\Window Settings\Scripts and under the Powershell Scripts tab added the file with no parameters.  I have yet to try the domain GPO with the file association added on the client.
What am I missing?
2008r2 and 2003 SP2 DC, Win7 and XP clients
Answer: Are you setting it to run directly by putting the script path as the "executable"?  Or are you setting the executable to powershell.exe and passing the script path with the -File argument (and potentially other arguments like -NonInteractive)?
I haven't actually tested this myself, but I'm pretty sure you should be doing the latter rather than the former.
Comment: I'm actually just going into the Computer Configuration\Windows Settings\Startup section on my domain controller.  There's a tab for powershell scripts and I just load it up there with no arguments.
Comment: I'll edit my question.  I just performed another test as well.
Comment: Hah, I didn't even know that tab existed.  You've taught me something new today and I thank you.  It appears it was added with Win7/2008R2.
Comment: In any case, you might try testing the old-style Scripts tab just to see if it works.  Set the Script Name to the path to powershell.exe.  Then set the Script Parameters to "-File ".
Comment: You're welcome.  And I think (read: Hope) we may be on to something here.  Will update shortly.
Comment: Crap.  No dice.  Going the old script route didn't work on either client.  Good news is though that I got Win7 to work after setting the file association. I'm thinking it'll be a no go for PS on XP.  Might have to do that one manually.
Comment: I was looking around and thinking about it, and it's probably possible to create a .bat that calls powershell and passes the -File argument.  Haven't tried this as we got around our initial issue, but something to think about.
Answer: This looks like a no-go for XP clients.  I managed to get my Win7 clients to work after setting .ps1 to associate with PS instead of Notepad.


Do re-estimated HMM parameters still need to be normalized?

Question: A few days ago I asked this question. I only got one answer and I did not really understand it. Now I think this question is a special case of a more general question I have, namely: Do re-estiamted HMM parameters still need to be normalized?
In all sources I read, it nowhere says so. However if normalizing was a necessary step after parameter re-estimation my question from the other post would be solved as well, I think.
For instance, the reestimation of a transition probability $a_{ij}$ is defined like so:
$$a_{ij}* = \frac{\text{expected count of taking } a_{ij}}{\text{expected count of going through state } i}$$
and
$$b_{i}(o)* = \frac{\text{expected count of observing $o$ while in state $i$ }}{\text{expected count of going through state } i}$$
However, as asked in my other question, I do not see where this guarantees that the sum of the emission/ transition probabilities of state $i$ still sum to one after the re-estimation:
$$\sum_{o \in O} b_i(o) = 1 \text{ with $O$ the set of observable variables}$$
Do I need to normlize the re-estiamted emissionand transition probabilities for each state like so
$$ a_{ij} ** = \frac{a_{ij}*}{\sum_{j = 1}^N a_{ij}*}$$
and
$$b_i(o)** = \frac{b_i(o)*}{\sum_{o' \in O}^N b_i(o')*} \text{ }?$$
In my implememtation I am getting for example the following result after re-estimating all transitions ot of state $0$:
(format: source state, target state, transition probability)
<code>(0)
    (0)
        0.02038692369
    (1)
        0.02827691867
    (2)
        0.1224984127
    (3)
        0.1769161212
    (4)
        0.02722449656
    (5)
        0.09686773213
    (6)
        0.06621975806
    (7)
        0.1563805179
    (8)
        0.2656531668
    (9)
        0.001414074456
        ∑ =  0.9618381222
</code>
As you can see the re-estimaeted probabilities do not sum to 1, while the original randomized distribution did sum to 1:
<code>(0)
    (0)
        0.180830546
    (1)
        0.2397926304
    (2)
        0.08390362715
    (3)
        0.0671602972
    (4)
        0.07536117849
    (5)
        0.1897902356
    (6)
        0.0579146584
    (7)
        0.0912998276
    (8)
        0.004448007786
    (9)
        0.009498991412
        ∑ =  1
</code>
Answer: It is not necessary to normalize the re-estimated parameters since it is guaranteed that they represent a valid probability distribution. Why in your implementation do the transition probabilities from state 0 not sum to one? I don't know. Maybe some implementation errors. But it is obvious that $a_{ij}$ and $b_i(o)$ sum to one for a particular $i$ without any need to normalization after estimation. For example, $a_{ij}$ is estimated as:
$$a_{ij} = \frac{\text{expected number of transitions from state i to state j}}{\text{expected number of transitions from state i}}$$
and it is obvious that the denominator acts as a normalization factor:
$$\text{expected number of transitions from state i} = \sum_j \text{expected number of transitions from state i to state j}$$
The same argument holds for $b_i(o)$.
Comment: @lotolmencre Not only $b_i(e)$ is re-estimated, but all emissions are re-estimated. In your example, $b_i(e)$ would be equal to one and all other $b_i(e')$ for $e' \neq e$ would be zero, since the numerator for re-estimating emissions would be zero for $e' \neq e$.
Comment: Sorry, I have thought about this for quite a while and tried to find the bug, but still... how the re-estimation of the emissions (in particular) is supposed to sum to 1 I still don't see. Say I want to re-estiamte the emissions for a state $s_i$. State $s_i$ has the set of emissions $E$. But assume in my current training sequence there occurs only one elememt $e \in E$. Therefore only one of the emission probabilities of $s_i$ is re-estiamted ($b_i(e)$). The value of the re-estimation will differ from the current value and thus the distribution no longer sums to one... What am I missing here?
Comment: Ah, now I see, so far I always thout only those emissiosn get re-estimated and changed out where the emissions are observed. Now it makes sense, thanks!


Como resolver problemas no upload do TIdFTP no Object-Pascal?

Question: Descobri um jeito de fazer uploads no meu server FTP, porém tento notado que arquivos com peso superior a 1 KB chegam danificados, então peço a ajuda de vocês para resolver meu problema, o modo utilizado em questão foi o da imagem abaixo, como resolver este problema?
Answer: na propriedade TransferType qual das duas opções você selecionou?
Somente selecione o ftascii quando for algum arquivo texto, pas, algo assim.
Nos demais trabalhe com ftBinary, .exe, fotos, etc.


How to change the auto-generated "Discriminator" column in EntityFramework?

Question: I am working on some code that makes use of single table inheritance via EF4.3.
There is an entity called User and another entity called Admin. Admin inherits from user.
User class
public class User
{
    public int Id {get;set;}
    public string Username {get;set;}
}

Admin class
public class Admin : User { }

EF generated the database tables with a Discriminator column. When an Admin record is added then Discriminator="Admin" and a User record would have Discriminator="User".
My question is, how do I update the Discriminator column if I want to make a User into and Admin?
I tried casting from one object type to the other and saving using EF. but that doesn't change the Discriminator column. How do I change it?
Thanks for any help.
Answer: Objects can't change their types, ever. If you intend to change the "administrator" setting for a user (reasonable), you should do that with an attribute/property, not a type name.
For example, you could have an association between a User object and an Administrator object, rather than wanting to replace the User object with an Administrator subtype.
I wrote about this idea in an old blog post:

One of the mental barriers that you have to get over when designing a good object relational mapping is the tendency to think primarily in object oriented terms, or relational terms, whichever suits your personality.  A good object relational mapping, though, incorporates both a good object model and a good relational model. For example, let's say you have a database with a table for People, and related tables for Employees and Customers.  A single person might have a record in all three tables.  Now, from a strictly relational point of view, you could construct a database VIEW for employees and another one for customers, both of which incorporate information from the People table.  When using a one VIEW or the other, you can temporarily think of an individual person as "just" an Employee or "just" a Customer, even though you know that they are both. So someone coming from this worldview might be tempted to do an OO mapping where Employee and Customer are both (direct) subclasses of Person.  But this doesn't work with the data we have; since a single person has both employee and customer records (and since no Person instance can be of the concrete subtype Employee and Customer simultaneously), the OO relationship between Person and Employee needs to be composition rather than inheritance, and similarly for Person and Customer.

To answer your question directly, there's no way to change this column using EF. You could of course, do it in straight SQL. But for the reason given above, I'd encourage you to change this design.
Comment: @quakkels: *This may require some in-depth refactoring of the application I'm working on* Unfortunately this usually happens if you incorrectly understand requirements for your application and use wrong design. Abusing inheritance is one of the worst thing people can do in their application because fixing such design error in later stages of development is always expensive.
Comment: Casting doesn't change types. It either creates a new instance (e.g., with an explicit conversion) or treats the reference as a more specific type. None of this changes the discriminator value.
Comment: This may require some in-depth refactoring of the application I'm working on.
Comment: "Objects can't change their types, ever." - But they can be cast to another type.
Comment: The first thing comes to my mind is to replace the existing user with a _new_ admin with the same data: `User user = GetUser(); Admin admin = Admin.FromUser(user); dbContext.Users.Remove(user); dbContext.Admins.Add(admin);`. Is there a reason something like this would be a bad idea?
Comment: @AhmedAbdelhameed It's not a _bad_ idea if your system is built from the outset to accommodate the notion that a "Person" record can change over time. But if you have 1000 foreign keys to that person elsewhere in the DB, simply replacing the record could be challenging. So it depends on your design. I would probably model your example as a Person with an associated history of roles.
Comment: "Objects can't change their types, ever." they can, if you provide the missing data to upcast


função mai() php não funcionando em condições

Question: Tenho uma PHP que manda email de um formulário de contato, quando esta na condição da verificação do captcha, recebo a mensagem de enviado, mas o email não é entregue, e quado eu tiro da condição o email chega normal.
Segue o código PHP (O submit é feito por ajax)
    <?php

$captcha = $_POST['captcha'];
if (!empty($_POST['captcha'])) {

    $resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SECRET-KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);

    if ($resposta.success) {
        $to = "email@example.com";
        $nome = $_POST["nome"];
        $email = $_POST["email"];
        $mensagem = $_POST["mensagem"];
        $celular = $_POST["celular"];
        $assunto = $_POST["assunto"];
        $txt = "MENSAGEM: $mensagem". "\r\n" . "CELULAR: $celular". "\r\n" . "NOME: $nome";
        $headers = "From: $email";

        if ((empty($nome))||(empty($email))||(empty($celular))||(empty($mensagem))||(empty($assunto))) {
            print('Preencha os campos');
        } else {
            $envio = mail($to,$assunto,$txt,$headers);
            if ($envio) {
                print('Enviado');
            }else{
                print('Erro');
            }
        }
    } else {
        print('Erro');
    }
} else {
    print('Marque o Captcha');
}

?>

Comment: Chega a retornar algum dos prints?
Comment: Sim, imprimi todos normais, ao não marcar o captcha, se não estiver todos os campos preenchidos e quando envia.
Comment: O que imprime? entra em qual condição?
Comment: Se marcar o captcha e preenchar todos os campos, imprimi: Enviado. Os prints saem como estivesse funcionando, mas o email não chega.
Comment: Se estiver em localhost não vai enviar, a não ser que tenha um servidor de email instalado
Comment: Está em um server. Como disse: quando retiro o mail() dessa condição, ele funciona, ou seja, eu recebo o email enviado pelo php.
Comment: Acho que sei o que está acontecer...Deve ser porque o seu email client está a ver isso como spam. Vou postar uma possível solução
Comment: Dependendo do hosting não aceita essa função, usa o PHPMail.
Answer: Dependendo do seu servidor de hospedagem (A Locaweb por exemplo), é necessário fazer a autenticação para realizar o envio de email.
Caso a autenticação seja obrigatória, use o PHPMailer para realizar o envio, a configuração mais simples do que no php.ini.
Comment: Acho que não há problema na autenticação pois quando retiro o Mail da condição, o envio funciona normalmente.
Answer: Deve ter de definir alguns headers (que não os default) para 'enganar' alguns clientes de email que possam achar que é spam, nomeadamente o From e o Reply-To, defina os seus headers assim:
$subject = 'Ajudar Vinicius a mandar email ';
$body = 'corpo da mensagem';
$to = 'EMAIL@DESTINO'; // ajustar
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\r\n";
$headers .= "From: Miguel <firstname.lastname@example.com>" . "\r\n" .
"Reply-To: firstname.lastname@example.com" . "\r\n" .
"X-Mailer: PHP/" . phpversion();

if(!mail($to, $subject, $body, $headers))
{
    echo 'Erro';
}
else {
    echo 'YAY';
}


getMonth in javascript gives previous month

Question: I am using a datepicker which gives a date in the format Sun Jul 7 00:00:00 EDT 2013.
Even though the month says July, if I do a getMonth, it gives me the previous month.
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth());//gives 6 instead of 7

What am I doing wrong?
Comment: Yep... it's [zero indexed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth).
Comment: i cant believe how real this is
Comment: Don't lose your mind with dates in javascript. Use Moment.js if you can
Comment: Wait until you try `getYear()`!! ;-)
Comment: Moment.js can't do dateDiffs correctly.  It's okay if you're doing dateDiffs within the same month, but try to do it across 2 different months (ie 27-04-2018 and 24-05-2018) and it's a day out.
Answer: Because getmonth() start from 0. You may want to have d1.getMonth() + 1 to achieve what you want.
Comment: I gotta say, to have a month number zero indexed is the dumbest thing I've seen in a while. '
Comment: why the would someone want it 0 based if getDate gives 1-31?
Comment: @DanielKhan Nope, because December would be 11, so adding 1 to it would correctly make it 12. The getMonth() function shouldn't ever return a value over 11.
Comment: @LarryBud, the reasoning is probably that contrary to other parts of the date (day of month, year, hours, minutes, seconds...) which are always used as numbers as they are, the month is often converted to text, using an array of names, which is of course 0-based. It was already the case in C standard libraries, which must be over 40 years old.
Comment: Most probably you will have to do `d1.getMonth() < 12 ? d1.getMonth() + 1 : 1` - otherwise December would be 13, not?
Comment: Ah - sorry it was late.
Comment: Another oddity is that to get the day of the month it's getDate but this is not 0 based and returns the correct day. http://momentjs.com/ is the way to go if its available to use
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
Comment: getDate should also start with '0' then. :)
Comment: again, if I was dealing with anything else that would be fine, but since this is a month it should do the logic for you and return the correct number.  It is just dumb.
Comment: The Javascript date interface was adopted directly from the C API with no changes. That propagated such unfortunate choices as getYear() returning the year minus 1900 and getMonth() returning 0..11. Using getFullYear() avoids the first landmine, but you just have to know to use getMonth()+1 if you want the standard month number instead of an index you can use with an array of month names.
Comment: It is not always zero based. `new Date("2023-01-10").getMonth() = 0` but, `new Date(2023, 01, 10).getMonth() = 1` (Firefox 108) -.-
Comment: Thank you for giving us of another reason why JavaScript is just the absolute worst
Answer: getMonth() function is zero indexed based. You need to do d1.getMonth() + 1
Recently I used Moment.js library and never looked back. Try it!
Comment: Can you say how did you use?
Comment: `dayjs` is also a good alternative.
Answer: Presuming you use your variable
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");

Month requires a +1 to be accurate, it starts counting at 0
d1.getMonth() + 1 // month

In contrast.... these methods DON'T need a plus 1
d1.getSeconds()   // seconds
d1.getMinutes()   // minutes
d1.getDate()      // date

And notice it is .getDate() NOT .getDay()
d1.getDay()       // day of the week as a

Hope this helps
I suspect these methods lack consistency for historical reasons
Comment: "In contrast.... these methods DON'T need a plus 1" -> it's very nice when you have developers that are consistent...
Comment: AHHHHHHHHHHHHHHHHHHHHHHHH
Answer: const d = new Date();
const time = d.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second:'numeric', hour12: true });
const date = d.toLocaleString('en-US', { day: 'numeric', month: 'numeric', year:'numeric' });

OR
const full_date = new Date().toLocaleDateString(); //Date String
const full_time = new Date().toLocaleTimeString(); // Time String

Output
Date = 8/13/2020
Time = 12:06:13 AM
Answer: you can also find current month in this way

const today = new Date()
const getMonth = (today.getMonth() + 1).toString().length === 1 ? `0${today.getMonth() + 1}`:today.getMonth() + 1
Comment: How is this answer any different from the accepted answer... you are still using `getMonth() + 1`???


Can I use a differences-in-differences (DID) model to identify when treatment starts?

Question: I am analyzing the impact of a policy, but I have found that if I set the time of treatment to the time the policy was introduced, then a negative DiD coefficient does not return a significant result. But if I set the time of treatment to the periods after the policy was first introduced, then I the model returns significant results.
I know that the DiD model is used to analyze treatment effects, but can the process be reversed? For example, if I don't know when the treatment was administered and I find the time when the DiD coefficient is negative by trying different times, wouldn't this prove the effectiveness of the treatment and at the same time find the time when the treatment worked?
Comment: So you want to use the period in which a treatment effect is realized to tell you *when* it was administered/implemented?
Comment: @ThomasBilach Yes, or to determine what time the treatment took effect
Comment: You can allow the treatment effect to vary over time by replacing post with a set of time dummies and replacing post x treated variable with post x time dummies.
Answer: The first paragraph of your post suggests you know the "timing" of the intervention. In your first DiD equation you set the post-treatment indicator equal to 1 in the first (i.e., immediate) adoption period and the model returned an insignificant, negative program effect. In your second DiD equation, however, you set the post-treatment indicator to 1 in a period(s) after the immediate adoption period and the model returned a significant, negative program effect. This suggests, to some degree, a delayed onset of treatment. It's often worthwhile to partition the temporal sequence into different 'timing epochs' to observe how effects evolve over time. If the post-treatment indicator simply 'turns on' (i.e., switches from 0 to 1) and 'stays on' in all periods after the start of the policy then it might obscure important intertemporal effects. As suggested in the comments, interact a treatment/control dummy with separate time indicators for all periods post-policy. This allows the treatment effect to vary with time since exposure.
Now I will address your other inquiry regarding the reverse-engineering of a policy's effective date.

I know that the DiD model is used to analyze treatment effects, but can the process be reversed?

Yes, but it's inadvisable.

For example, if I don't know when the treatment was administered and I find the time when the DiD coefficient is negative by trying different times, wouldn't this prove the effectiveness of the treatment and at the same time find the time when the treatment worked?

It appears you want the results of a significance test to advise you on when a treatment was administered. There are two potential problems with this approach. First, it suggests you cannot reliably distinguish between the pre-/post-treatment epochs. If so, then how do you know the observed effect isn't occurring in a period before the exposure? It would be hard to rule this out if you don't know the precise timing of the policy. It also precludes any assessment of an anticipatory response to the policy.
Second, this approach may ignore a relevant time dependency in your outcome's response to the intervention. For example, suppose the negative effects of your policy accumulate over time and the full effect is realized a few periods after the policy's effective date, say by the third lag. Since the start of the policy is largely unknown, the first emergence of a significant program effect (i.e., third lag) is taken as evidence of punctual change when, in fact, there was a growing policy influence materializing slowly over time. In practice, it may be inappropriate to assume units (e.g., individuals, families, firms, etc.) respond instantaneously to a stimulus (i.e., treatment). Investigating "how long" a policy takes to phase-in and effectuate meaningful change may be of substantive interest.
The reverse-engineering approach is inherently a-theoretical. In essence, you're inferring a treatment's start date in the period (i.e., day/week/month) when the DiD coefficient is significantly bounded away from 0. Note how this implies that the policy will eventually produce the intended result. But say the policy doesn't yield a significant treatment effect in any period. Does this suggest the policy never took place? And how far into the future will you go to look for evidence of a treatment effect? If not obvious, the farther downstream you go to look for evidence of a policy effect the more and more your research endeavor becomes a mere data dredging exercise.


Which statistical test can I run to making a stacked bar chart in SPSS of the means of two time measures for one IV?

Question: Hypothetical experiment:
I want to determine the "best" method of cooking chips - oven or fryer.
I have ten bags of chips, each bag I split in two, cook half in the oven, half in the fryer. for each bag, I rate the cooked chips out of ten for quality. I also time how long each method of cooking takes over all, as well as how long I physically spend cooking for each method.
I now have 6 columns X 10 rows of data. I want to compare the average quality score for each cooking method, and each length of time for each method.
But what test do I run, to compare the average time of cooking in conjunction with the average time I spend cooking, between the two methods? I have manually created a clustered bar chart, but really want to understand which statistical test to use.
Thanks!
Comment: Would it be possible to provide an image of your data table? I think it can be helpful.
Answer: The underlying statistical methodology is a hypothesis test.
In your situation, the simplest method is to run regressions separately for each method. Then after you obtained the coefficient and 95% confidence interval, you could indicate if the methodologies are significantly different from each other by checking if the coefficients are in the interval.
Consider a situation with two methods:
$$\beta_{1}= 1.05, and\ the\ confidence\ interval\ is\ [1.0,1.1]$$
$$\beta_{2}= 1.02, and\ the\ confidence\ interval\ is\ [0.97, 1.07]$$
Since $\beta_{2}$ fall into the interval of [1.0,1.1], they are the same statistically.


Principal component (PC) as a substitute for colinear covariates?

Question: I am working on a spatial linear regression and I can tell there is collinearity between covariates. Can I use PCA (Principal Component Analysis) images instead of original covariates to estimate the dependent variable? I am assuming PC1=Variable 1, PC2=Variable 2, etc. Or are there any other methods to solve the collinearity problem?
Comment: What is your goal in fitting the regression model? Collinearity is only a problem in some cases.
Comment: To be more specific: are you interested in the magnitudes and directions of the coefficients, or making accurate predictions, or both?
Comment: Yes, why not? This is called principal components regression.
Comment: I am trying to estimate the response variable from covariates using spatial linear regression.
Comment: **@ssdecontrol** .Both the coefficients and sign of the predictors as well as accurate estimation of response variable using these PC's of covariates.
Comment: Thanks for clarifying, that will help me write a more helpful answer.
Comment: How correlated?  Usually only a problem if the correlation is above .95.
Answer: There is a method called partial least square that is something very close to what you are trying to do.
https://en.wikipedia.org/wiki/Partial_least_squares_regression
The choice to use the PCA transformation of the data can lead to a better estimation of the output $y$ but to understand the role of the original variables  will be more difficult.
I suggest you to start with  the lasso estimator https://en.wikipedia.org/wiki/Lasso_%28statistics%29#Lasso_method


data type argument cannot be null in data profiling viewer

Question: I am new to Data Profile Viewer. I just created a package in SSIS which contains a Data Profiling Task Component. I am using the Sample database of Adventureworks2012 and I am creating an XML file through it using Employee table. But when I am trying to view the XML in Data Profile Viewer and selecting the Candidate profile Key it is showing me the below error:
Drill down query completed with error: The error message is:
 System.ArgumentNullException: 'dataType' argument cannot be null.
Parameter name: dataType
   at System.Data.DataColumn..ctor(String columnName, Type dataType, String expr, MappingType type)
   at Microsoft.SqlServer.DataProfileViewer.QueryDrillDownWorker.DoWork(DoWorkEventArgs e)
   at Microsoft.SqlServer.DataProfileViewer.DrillDownControlContainer.backgroundWorker_DoWork(Object sender, DoWorkEventArgs e)
   at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
   at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
Anyone having a knowledge on this how to resolve it. I am not able to find on Google.
Thanks for your help.
Answer: Try to add Polybase feature to your instance.
Comment: Go to installation, check if the Polybase feature is installed in your current instance. I had the exact same problem and this works for me.


Generating probability distribution parameters using a neural network

Question: I am new to neural network therefore, my question might be super basic. I am reading this article:
https://arxiv.org/pdf/1609.09869.pdf
In this article they've made a deep Markov Model in which they use recurrent neural network to generate the probability distribution parameters (mu and sigma). That is they have a string of observables (X) and which they feed to a bi-directional neural network and they use these networks to produce mu and sigma which in turn gives them latent variable (z). I've attached the image as well.

My question is how can you train your network to give distribution parameters?
I know how a neural network works generally. So, for each label we have a corresponding input and with that input we get let's say a probability of whether its a cat or a dog in the final softmax layer. But how can we get mu and sigma for distribution parameters?
Answer: This is given in the paper
$$\begin{align}
\mu_r &= W_{\mu_r}^\text{right} h_t ^\text{right}  + b _{\mu_r}^\text{right} \\
\sigma_r^2 &= \operatorname{softplus}(W_{\sigma_r}^\text{right} h_t ^\text{right}  + b _{\sigma_r}^\text{right}) \\
\mu_l &= W_{\mu_l}^\text{left} h_t ^\text{left}  + b _{\mu_l}^\text{left} \\
\sigma_l^2 &= \operatorname{softplus}(W_{\sigma_l}^\text{left} h_t ^\text{left}  + b _{\sigma_l}^\text{left}) \\
\mu_t &= \frac{\mu_r\sigma^2_l + \mu_l\sigma^2_r }{\sigma^2_l + \sigma^2_r} \\ \sigma^2_t &= \frac{\sigma^2_l \sigma^2_r }{\sigma^2_l + \sigma^2_r} \\
\end{align}$$
They are calculated using dense layers, as a function of the outputs of previous layers. What they are assuming in here is that there the parameters are some complicated, possibly non-linear, function of the inputs
$$
y_t \sim \mathcal{N}(\mu(x), \sigma(x))
$$
You can notice that the last two lines are the update rule for Gaussian distribution given the conjugate priors.
Comment: but how do we use these to get latent variables?
Comment: @Peter get what exactly? The above formulas show how to get them, to estimate the parameters you maximize the likelihood, as described in the paper. The estimated parameters are the latent variables.
Comment: I think I get it now. Thank you @Tim


Problema com o atributo "match" de um campo de texto

Question: Estou usando o atributo match de um
, mas ele não funciona apropriadamente.

Quando eu envio o formulário via commandButton, uma mensagem de erro surge, dizendo que as senhas não combinam, mesmo eu tendo colocado os caracteres iguais.
Como posso resolvê-lo?
Comment: Você recebe os valores na sua Controller, se recebe poderia postar o método que recebe? Já tentou ver se estão vindo nulo? Poderia postar qual erro dá?
Comment: Não recebo nada no controle, quero dizer, não atribuo nenhum atributo ao `p:password` com o *match*. O PrimeFaces não faz isso automaticamente?
Comment: Não, ele não faz, você tem que mandar para sua Controller, veja [aqui](http://www.primefaces.org/showcase/ui/input/password.xhtml), você precisa setar no campo value sua ManagedBean.Password. Considerando "Password" um atributo
Comment: Ah, só para confirmar: os dois usam o mesmo atributo como valor?
Comment: Sim, de uma lida no artigo em que eu comentei, é sempre bom voce ler o ShowCase do PrimeFaces
Answer: Segue o exemplo @Patrick
<h:panelGrid columns="2" id="matchGrid" cellpadding="5">
    <h:outputLabel for="pwd1" value="Password 1: *" />

    <h:outputLabel for="pwd2" value="Password 2: *" />

</h:panelGrid>

Na verdade a propria API verifica com o match o que falta no seu código é o atributo que a senha receberá em sua View
Comment: Não funcionou, continua a dar o mesmo erro.
Comment: como está o codigo na sua View e no seu XHTML?


SQL query for matching a column across two tables

Question: I have two SQL tables: users & userGroup with data like:
users:
 user      | age | gender

    testUserA,  25,   Male
    testUserB,  30,   Female
    testUserC,  35,   Male

userGroup:
user     | group

testUserA, groupA
testUserB, groupA
testUserC, groupB

How would I phrase a query to list the male users in groupA?
Comment: You would use `JOIN` and `WHERE`.  This is pretty basic SQL.
Comment: Please show us what you've tried, and tell us which database you're using.
Comment: Which RDBMS are you using? (MySQL, SQL Server, Oracle, etc?)
Answer: All you need is a join and a where clause to filter gender and group:
select u.user
from user u
join userGroup ug on u.user = ug.user
where u.gender = 'Male'
  and ug.group = 'groupA'

Comment: Awesome, thanks!  I haven't used SQL in a couple years and couldn't find the right command.  (I was trying to UNION it.)
Answer: This query would join the two tables together and also filter by gender.
SELECT u.User, u.Gender, ug.Group
FROM user u
INNER JOIN userGroup ug
ON u.user = ug.user
WHERE u.gender = 'Male'
AND ug.Group = 'groupA';

Comment: You forgot the group restriction in the `WHERE` clause.
Answer: Here's one way to do it:
select a.user, a.age, a.gender, b.group from users as a
inner join userGroup as b on a.user=b.user
where a.gender='Male' and b.group='groupA'


how i stop orientation in Android device?

Question: i make a application on Titanium. whose work on cross platform (android or iphone).
i want to stop orientation in android device how i can do?
because, android have default orientation change. and iphone have not default.
Answer: win.orientationModes = [Ti.UI.PORTRAIT];

This is working ...
Answer: For any kind of android application you can use below in android manifest.
<activity android:screenOrientation="landscape" android:name="org.appcelerator.titanium.TiActivity" android:configChanges="keyboardHidden"/>

For any kind of IOS application you can use below in main plist file in xcode
<key>UIInterfaceOrientation</key>
<string>UIInterfaceOrientationLandscapeRight</string>

For Titanium Mobile specific; please check below link from Titanium dev center
http://developer.appcelerator.com/question/22241/is-there-a-way-to-disable-orientation-change-on-the-ipadiphone


Trying to get property 'name' of non-object?

Question: Hi Guys i am new to laravel and i am trying to retrieve category names for each formation and i am getting this error

Trying to get property 'name' of non-object (0)

The "name" i am trying to retrieve is the name of category that my formation belongs to.
This is My Category Model
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    function formations()
        {
            return $this->hasMany('App\Formation');
        }

    protected $fillable =['name','description'];
}

And This is My Formation Model
class Formation extends Model
{
   function category()
       {
           return $this->belongsTo('App\Category',"category_id");
       }
   protected $fillable =['name','price','durations','category_id'];
}

And here is my view page where i am trying to retrieve the category name
@foreach($formations as $formation)

        {{$formation->name}}
        {{$formation->price}}
        {{$formation->category->name}}
        td>{{$formation->durations}}

@endforeach

This is My Controller
    public function index()
{
    //$formations = Formation::all();
    $formations = Formation::with('category')->paginate('4');
    $categories = Category::all();
    return view('formation.index',compact('categories','formations'));
}

Any Suggestion about where i might be wrong ? And thanks in Advance !
Comment: like `$this->belongsTo('App\Category',"category_id","category_id");`
Comment: Can you add foreign key and local key to the relationship and try...
Comment: for being sure that your relation functions in model are correct or not, you can test them in controller, like this in your controller: `dd($formations[0]->category);` , if this shows you a collection from category so this is ok else your relations method is not ok
Comment: @Rezash That's didn't work for me
Comment: @MohamedMidou so your relation methods are incorrect, read this https://laravel.com/docs/6.x/eloquent-relationships
Comment: `dd($formations)` in your controller and show us the response.
Answer: This error usually comes when you have removed one or more row from database, but trying to access that row with an id. Make sure that you have all the category in the category table with the id which is mentioned in the formation table category_id field.
Comment: that's exactly the problem i have deleted one row from database and i forgot that, silly me thanks man
Answer: The Problem was that i have deleted a row from my category table in database that's why the name wasn't recognized.
Answer: Try changing the relationship
class Formation extends Model
{
function category()
   {
       return $this->belongsTo('App\Category',"id","category_id"); //if your categories id is id
   }
protected $fillable =['name','price','durations','category_id'];
}

In your view
  @foreach($formations as $formation)

    {{$formation->name}}
    {{$formation->price}}
    {{$formation->category->name}}
    {{$formation->durations}}

  @endforeach

Answer: In your view
@foreach($formations as $formation)
 {{$formation->name}}
 {{$formation->price}}
  {{ $formation->categories()->pluck('name')->implode(' ') }}
 {{$formation->durations}}
@endforeach


How can I write SelectQuery for SELECT LAST_INSERT_ID()?

Question: Is it possible to run the following query with SelectQuery ?
SELECT LAST_INSERT_ID();

I would do this with db_query(), but I'm finding a way to use the query builder.
$last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();

Comment: Is your computer broken?! Can you not test to see if it works yourself? Drupal Answers isn't a code debugger/IDE after all :)
Comment: @Clive, Ok, then. At least, you have known it :) I asked this for the sake of future visitors.
Comment: Why can't you use PDO, cause execute function in PDO will return you the inserted ID?
Comment: @Mathankumar, What do you mean about PDO? AFAIK, PDO is extension used by the Drupal database layer.
Comment: @Clive, Somebody might have tried this. I will submit an answer after I tested. Have you thought of it or tried it? Sometimes, I wrote codes for others in Drupal Answers because I believe it builds up my Drupal skill :)
Comment: Yes it works perfectly, I'll let you test for yourself and put the answer in though :)
Comment: Great stuff, thanks for trying to make the site a better place :)
Comment: @Clive, you're welcome. BTW, you said "code debugger". I think this question is just looking for the usage of db_select() for the query, not for debugging purpose.
Comment: @Clive, check my answer.
Answer: Although the original query has no table name, db_select() would expect the table name.
The following works perfectly assuming the insert operation took place in another hook and the last insert id is not available into my hook:
$query = db_select('mytable');
$query->addExpression('LAST_INSERT_ID()', 'last_id');

$result = $query->execute()->fetch();
print $query;
echo '
';
echo 'Insert ID: '.$result->last_id;

Query output:
SELECT LAST_INSERT_ID() AS last_id FROM {mytable} mytable

Answer: If you need the last insert ID, after you executed an INSERT with the InsertQuery class, InsertQuery::execute() returns that value.

The last insert ID of the query, if one exists. If the query was given multiple sets of values to insert, the return value is undefined. If no fields are specified, this method will do nothing and return NULL. That makes it safe to use in multi-insert loops.

Differently, UpdateQuery::execute() returns the number of affected rows.
Comment: Thank you, kiamlaluno. This question is somehow related to [the other question](http://drupal.stackexchange.com/questions/58991/how-to-retrieve-last-mysql-insert-id-from-drupal-7-db-merge) which uses db_merge(), not db_insert().
Comment: I just used `db_insert()` for testing purpose only.
Comment: The answer is still correct: After executing an `INSERT` with `db_insert()`, there is no need to execute a new query to get the value of the last insert ID.
Comment: The question is intended for "How to use `db_select()` for `SELECT LAST_INSERT_ID()`. It is not for "How to get the last insert ID". Please assume that the insert operation just took place in another hook and I cannot get the value of the last insert ID in my hook. Anyway, I really appreciate your answer. I did not mean yours is not correct. Thank you. I just updated my question and answer to make this more clear. I was also curious to know how to write such kind of odd queries with `db_select()`.


Show that $g:X\to Z$ where $g((x,n)) = ((x,nx))$ is not a quotient.

Question:
Suppose that $X$ is the set of all lines
  $$L_{n} = \mathbb R \times \{n\} \quad\textrm{ for $n\in\mathbb Z^+$}$$
  and $Z$ is the set of all lines that cross the center of plane and its slope is positive:
  $$(L_n)' = \{(x,nx) :\, n \in \mathbb Z^+\}.$$
  Show that $g:X \to Z$ defined by $g((x,n)) = ((x,nx))$ it is not a quotient map.

By definition, If I show that for some subset of $Z$ like $W$, $p^{-1}(W)$ is open in $X$, but $W$ is not open in $Z$, then it is not quotient.
I don' know how to show it.
Answer: Let us do it for closed $p^{-1}(W)$. For $n \in \mathbb Z_+$ let $R_n = \{ x \mid \lvert x \rvert \ge 1/n^2 \} \subset \mathbb R$, $M_n = R_n \times \{n\} \subset L_n$ and $M'_n = \{ (x,nx) \mid x \in R_n \} \subset L'_n$. Note that $p$ maps $M'_n$ bijectively onto $M'_n$ so that we have $p^{-1}(M'_n) = M_n$.
Now let $W  = \bigcup_{n \in \mathbb Z_+} M'_n$. This set is not closed because $(0,0) \notin W$, but $(0,0) \in \overline{W}$. Note that $(1/n^2,1/n) \in M'_n  \subset W$. We have $p^{-1}(W) = p^{-1}(\bigcup_{n \in \mathbb Z_+} M'_n) = \bigcup_{n \in \mathbb Z_+} p^{-1}(M'_n) = \bigcup_{n \in \mathbb Z_+} M_n$. This set is closed, thus $p$ is not a quotient map.


Clustering by same random projection

Question: I have $N$, $1024$-dimensional vectors. I want to cluster them by some similarity. Given the high dimensionality, standard metrics won't work. I tried a few Approximate Nearest Neighbor implementations which use randomized kd-trees or priority search k-means to find nearest neighbors. I don't trust their results either, because they depend a lot on parameter configuration.
Now, I know the number of clusters in this dataset because I know the number of classes , which is 55. As I was thinking, I had this idea, that I could just take a random weight matrix $W$ of size $1024$ x $55$, that will take as input my vectors and output a $55$ dimensional vector, and I'll apply $argmax$ on this $55$ dimensional vector and just use that value as the cluster $id$ . The $W$ , once randomly selected, remains the same for every input vector. Because I only care about clustering similar vectors and not about their exact class, I think this should work well. I guess this is very similar to cosine similarity, but instead of distance, I get a cluster id, because I use this random $W$ as a "judge" of similarity...Similarity w.r.t $W$, in other words.
Now, I'm an engineer and while this looks at first glance to be okay, I know things can't be that easy..I mean people have been researching high-dimensionality clustering and search for a very long time, and it is a hard problem. So I know I either made some stupid logical flaw above, or that there is some good theoretical reason not to do it this way. I want to know what I'm thinking wrong here, and why.
Thanks.
Comment: Sounds like a great idea! High-D clustering is still a wide open field. There are way more ideas than researchers. Give your idea a shot and let us know the results. Try 2 or 3 instead of 55 first. Consider the possibilities of inverting the op.
Answer: While I can't guarantee this is well-suited to your data, the following approach is pretty standard for when you want to cluster high-dimensional data.
You basically want to dimensionally reduce your data and then apply a clustering algorithm which would perform poorly in high dimensions but works well in low-dimensions.
PCA, TSNE, UMAP and AutoEncoders are all dimensionality reduction algorithms which you might consider using. All of these algorithms have hyperparameters whose performance greatly affects the output. There is, in all cases, a hyper parameter related to the dimension you want to project into, so one thing you could try is to project into 2- or 3-d and plot what your data looks like. For PCA, you can see what fraction of the variance is retained as a function of dimension and for AutoEncoders, you could plot your divergence as a function of dimension (although this will be computationally costly).
Once your data is dimensionally reduced, you can try the usual suspects (e.g. KMeans), although most likely you'll want to use DBscan or HDBScan.
I'm intrigued as to how you know you have 55 clusters. If, as you say, there are 55 classes, does this mean your data is labelled? If so, why do you want to cluster? Regardless of this, if you know you have 55 clusters, this is something you can harness very nicely in this approach.
I'm not an expert on (H)Dbscan, but I don't believe you set the cluster number, you set a density parameter and it will find the clusters and tell you the cluster number. Consequently, if for some reasonable combination of dimensionality reduction hyperparameters and (H)Dbscan hyperparameters, you are getting 55 clusters (or close to), you're probably on the right track.
Documentation for your dimensionality reduction implementation and your clustering algorithm should give you an idea for what constitutes reasonable ranges of parameter values.

Clustering by same random projection


Using context in KMM shared library (Manually)

Question: I am building a common library module in KMM that requires android application context.
How can I pass it to common module manually?
I have seen answers using androidx.startup.InitializationProvider which requires separate dependency.
I don't want any dependency.
Comment: You can't use android application context in common source set of your shared library. It is platform specific code, you should place it in android source set. Could you share more context what you are going to implement?
Comment: I am building a KMM library which is going to have an initialising method like `MyLib.init(context, secret_key)` I need context for many purpose. First of all is SQLite database initialisation then others.
Answer: We can get the Android context using Koin in the shared module.
Initialise the Koin from the Android application or activity class.
initKoin {
    androidLogger()
    androidContext(applicationContext)
}

Now inside the androidMain package of the shared module get the context
actual fun createDriver(): SqlDriver {
    val context: Context = getKoin().get()
    return AndroidSqliteDriver(AppDatabase.Schema, context, "cache.db")
}

For the Koin integration please check the official documentation
Answer: As you're building a multiplatform library, and Context is an Android-specific detail, it's not possible to refer to it in the commonMain source set.
As a solution, it's possible to declare your library's functionality under commonMain as:
interface MyLib {

  fun featureA()

  fun featureB()
}

// This method is a way to get platform-specific implementation of your library
expect fun getMyLib(): MyLib

Then, androidMain source set is a place where Context-dependent implementation should go. For example:
class AndroidMyLib(private val context: Context): MyLib {

  override fun featureA() {
    //context is accessible
  }

  ...
}

actual fun getMyLib() = AndroidMyLib(context)

Please note that an iOS-specific implementation of MyLib would be needed under iosMain as well.
More info on the expect / actual mechanism of dealing with platform details is in the KMP docs.
Comment: As we're not receiving context from getMyLib so how we can pass it to the AndroidMyLib to instantiate the class ? And also we can't add the context in the expect function signature as context is android platform related.
Answer: Found a good solution using expect/actual mechanism of object.

Create an expect object in commonMain

expect object AppContext

Create actual object in androidMain

import android.content.Context
import java.lang.ref.WeakReference

actual object AppContext {

    private var value: WeakReference<Context?>? = null

    fun set(context: Context) {
        value = WeakReference(context)
    }

    internal fun get(): Context? {
        return value?.get()
    }

}

Leave iOS AppContext empty as we don't need context there

actual object AppContext

Create another class in commonMain

class MyLibConfig(
    val appContext: AppContext,
    val isTestDevice: Boolean = false,
    val isLogsEnabled: Boolean = false,
)

Create your commonMain public API object

object MyLib {
    fun initialize(config: MyLibConfig) {
        val commonContext = config.appContext
    }
}

Pass this context to your native platform specific methods as argument. For example

override fun getMyLibDatabase(appContext: AppContext): SqlDriver {
        return AndroidSqliteDriver(
            my_lib_db.Schema,
            appContext.get()!!,
            "my_lib_db.sqlite"
        )
    }

Initialize your library from ViewModel or Application class. Much more clear way

MyLib.initialize(
            MyLibConfig(
                appContext = AppContext.apply { set(application.applicationContext) },
                isTestDevice = true,
                isLogsEnabled = true,
            )
        )

Comment: Seems to me like @Alex neatly answered your question, you should accept his answer.


What is meant by "quarter = half" when changing tempo?

Question: What is meant by the following indications when changing tempo:
" In 4 quarter = 126"
and later
"In 2 quarter = half"
Answer: We may miss some details depending on the particular musical example, but in general these indications are telling you two things: the meter and the tempo.

In 4 quarter = 126

This is saying that the meter is "in 4"; in other words, you should conceptualize each measure as having four beats. Furthermore, the quarter note will appear at a tempo of 126 beats per minute (bpm). If you're in 4/4 time, just put a metronome at 126 and that will be every beat of the measure.

In 2 quarter = half

This is saying that the meter is "in 2"; there are only two large beats in each measure. Furthermore, it says that the tempo of the new half note is equivalent to the the tempo of the prior quarter note. Assuming this indication comes right after the previous one, this is saying that the new half note is equal to 126 beats per minute.


Menu settings does not change menu

Question: I have created a new menu called new-menu.  I go to Admin > Structure > Menus > Settings
And I choose "New Menu"  for the "Source for the Main links" option.
However, on my site, it still shows the Main Menu links (instead of New Menu links).
What am I missing?
Note: I am running a custom "Drupal core" from my university, and I've never worked with Vanilla Drupal, so I'm not sure if something is missing that should be there.
Comment: What theme are you running? How are you printing your menu in your page.tpl?
Comment: I'm running Zen theme, but using a custom core from my university (which I mention because it's been the answer to other issues I've had like this)
Answer: You need to change the menu under Structure > Blocks. Find the Main Menu block that is active and click its "Configure" link. The third option is Menu... change this to dropdown to your new-menu.
Comment: I don't have a "Main Menu" block.  I have a "Navigation" block, which does not list the "main-menu" listed in it.

Menu settings does not change menu


DLLs missing, application gets 0xc00007b error code

Question: On running my VC++ application doesn't run and stops with 0xc00007b error code, which is STATUS_INVALID_IMAGE_FORMAT. I understand that this means I have problems with some x86 - x64 architecture compatibility issues on DLLs.
I have checked with Dependency Walker and I get the following:
There is no 64 indicator on any dependency. On double-click on any of the 3 not found files it says it's looking for them in the app folder, although I've copied them there, as well as having all of them in C:\Windows\System32.
I already have Visual C++ Redistributables installed for:

2005 - x86 & x64
2008 - x86 & x64
2010 - x86 & x64

I've run sfc /scannow but everything is fine.
The application is 32bit and it was originally written in VS2006, XP.
What should I do to fix this?
Comment: You have a dependency on a Debug MFC DLL, which is not redistributable. You should also try with a Release build to see if you get the same problem.
Comment: Use SysInternals' Process Monitor.  Towards the end of the trace you get, you'll see your program loading the DLL and taking a nose-dive.
Comment: If you need to debug, then you need to install Visual Studio. That's the only way you will (legally) get the debug runtimes on your system. There are other ways of debugging release builds, for example like analysing crash dumps against a Release build PDB, but we'd need to know what the problem is you're trying to solve.
Comment: Release runs without errors, but I still need to be able to debug.
Comment: Will try procmon next.
Answer: In  ol der versions of vs (there is no vs2006) the dlls had to be installed in a formal way, not just present.  And, there is no redistibutal package for debug dlls.  You have to install visual studio, or update to vs2010.


$A= \begin{bmatrix}-1 & 1 & 1 &1\\ 1 & -1 & 1 &1\\ 1 & 1 & -1 &1\\ 1 & 1 & 1 &-1\\ \end{bmatrix}$ $A$ is a symmetric matrix.Find its eigenvalues?

Question: $A= \begin{bmatrix}-1 & 1 & 1 &1\\
1 & -1 & 1 &1\\ 1 & 1 & -1 &1\\ 1 & 1 & 1 &-1\\
\end{bmatrix}$
$A$  is a symmetric matrix.Find its eigenvalues ?
I saw this question in my book. I know that it can be solved using the cofactor definition of determinant and its eigenvalues are $+2,-2$
However, this process is cumbersome . I wonder that whether there is any trick or shortcut for finding its eigenvalues .
Comment: By inspection, $\pmatrix{1\\1\\1\\1}$ is an eigenvector
Comment: Columns are independent eigenvectors, also pairwise orthogonal  $$
\left(
\begin{array}{rrrr}
  1  &  -1  &  -1  &  -1    \\
  1  &  1  &  -1  &  -1     \\
  1  &  0  &  2  &  -1     \\
  1  &  0  &  0  &  3     \\
\end{array}
\right).
$$
Comment: @WillJagy when we do operation over the rows , doesnt it affect eigen values ?
Comment: Bulb, please just multiply the two matrices; yours is called $A,$  if my matrix is called $E$  please calculate $AE.$   You will  will see quickly, as all elements are integers, that each column of $AE$ is a specific multiple of the original column in $E$
Comment: @WillJagy oh, i see .thank you
Answer: Hints: If the eigenvalues of $A+2I$ are $\lambda_1,\lambda_2,\lambda_3,\lambda_4$, then the eigenvalues of $A$ are $\lambda_1-2,\lambda_2-2,\lambda_3-2,\lambda_4-2$. Do you see why this is true?
The matrix $A+2I$ is a $4 \times 4$ matrix of all ones. Hence, the rank of $A+2I$ is one, and it has at most one non-zero eigenvalue (so three of its eigenvalues are $0$). You can find the non-zero eigenvalue by finding the corresponding eigenvector by inspection like J. W. Tanner suggested.
Comment: but $-2$ is eigenvalue ,as well. How can i obtain it ?
Comment: ^I revised my hints to make them a bit more clear. Let me know if you still need help.
Comment: Turns out this fits easily in a comment box: Columns are independent eigenvectors, also pairwise orthogonal  $$
\left(
\begin{array}{rrrr}
  1  &  -1  &  -1  &  -1    \\
  1  &  1  &  -1  &  -1     \\
  1  &  0  &  2  &  -1     \\
  1  &  0  &  0  &  3     \\
\end{array}
\right).
$$
Comment: yes , it helped me .Thank you. However , i hoped to find any magical trick or rule for large symmetric matrices
Answer: There is a cool argument borrowed from representation theory to calculate the eigenvectors of a circulant matrix $A$: in these matrices, each column is obtained from the previous one by shifting to the right its elements. In the shift, the last element goes back to the beginning. Formally, let $R$ by the permutation matrix that sends $e_i$ to $e_{i+1}$ for $i=1, 2,3$ and $e_4$ to $e_1$. Let also $A_i$ be the $i$-th column of $A$. The fact that $A$ is circulant formally writes as $A_{i+1} = RA_i$ for $i=1,2,3$ and $A_1 = R A_3$.
Recipe. Suppose $A$ is a 4x4 circulant matrix. Suppose the first row is $(v_1, v_2, v_3, v_4)$. If $i^2 = -1$, then its complex eigenvalues are:
$$ v_1+v_2+v_3+v_4$$
$$(v_1-v_3) +i(v_2-v_4) $$
$$v_1-v_2+v_3-v_4$$
$$(v_1- v_3) -i(v_2-v_4) $$
In your case you get $2,-2,-2,-2$.
Upshot. By the end of the answer you will know how to generalize this to higher dimensions, and I highly recommend you to do this exercise.
Proof. The key observation is the following: being circulant implies $AR = RA$. Indeed, for any $i = 1,2,3$ we have
$$ A R e_i = A e_{i+1} = A_{i+1} = R A_i = RA e_i $$
and the same holds for $i=4$. Since $AR,RA$ coincide on a basis, they are equal.
How the hell this fits into the eigenvalue problem? Firstly, notice that $R$ is diagonalizable, and its eigenvectors are
$$z_1  =(1,1,1,1)$$
$$z_2 = (1,i,i^2, i^3)$$
$$z_3 =(1,-1, 1, -1)$$
$$z_4 = (1,-i,-1, i)$$
where $i^2=-1$.Indeed:
$$ Rz_1 = R(1,1,1,1) = (1,1,1,1) = \lambda_1 z_1 = z_1$$
$$ Rz_2 = R(1,i,-1,-i) = (-i,1,i,-1) = -i(1,i,-1,-i) = \lambda_2 z_2 = -i z_2 $$
$$ R z_3 = R(1,-1,1,-1) = (-1,1,-1,1) = - (1,-1,1,-1) = \lambda_3 z_3 = - z_3 $$
$$ R z_4 = R(1,-i,-1, i) = (i,1,-i,-1) = i(1,-i,-1,i) = \lambda_4 z_4 = i z_4$$
Secondly, if we compute $AR =RA$ in $z_i$ we get that $\lambda_i Az_i = R(A z_i)$. This means that $Az_i$ is an eigenvector of $R$ relative to $\lambda_i$; but there is essentially just one eigenvector relative to $\lambda_i$, so $A z_i$ must be a multiple scalar of $z_i$! This is a very tricky passage. We conclude that $z_i$ is also an eigenvector of $A$, and since we have found a basis of eigenvectors we are done with our search.
We finish with the explicit computation. Since $z_i$ has a 1 in the first component, if we have that $A z_i = \mu_i z_i$, then by looking at the first component we get that $v \cdot z_i = \mu_i$, where $v=(v_1, v_2, v_3, v_4)$. If you look closer to the expressions in the recipe, you will see that the formulas are exactly $v \cdot z_1, v \cdot z_2, v \cdot z_3, v \cdot z_4$.


max of limit cardinals smaller than a successor cardinal bigger than $\aleph_\omega$

Question: This is the statment i want to proove :
if $k$ is a successor cardinal bigger than $\aleph_{\omega}$ then there is a max of $\{\lambda < k | \lambda \text{ is a limit cardinal}\}$.
Assuming (AC), if $k \geq \omega$ then $k^{+}$ is regular, so we can assume that $k$ is regular. I've found this argument but i'm not sure that it's correct :
By contradiction, if there is no max, then the union of all $\lambda$ limit smaller than $k$ is a successor cardinal $\leq k$. But a successor cardinal is regular, so it cannot be reach by this union : a contradiction. So there must be a max. Am I right?
Comment: As phrased, it's not at all clear that this union is not regular. Hence your argument is incomplete/doesn't work.
Comment: Elaborating on Stefan's comment, it is (hopefully) consistent with ZFC that there are [uncountable regular limit cardinals](https://en.wikipedia.org/wiki/Inaccessible_cardinal). There is a crucial property that a union of limits with no maximal element has, though, which a successor cardinal doesn't ...
Answer: Hint: Let $\rho = \bigcup \{ \lambda < \kappa \mid \lambda \text{ is a limit cardinal } \}$. $\rho$ is a nonempty union of cardinals and hence itself a cardinal. If you can show that $\rho$ is a limit cardinal, you're done.
Comment: Note that $\rho \le \mu$, where $\mu^+ = \kappa$. (The proof that $\rho$ is a limit cardinal doesn't depend on this. But if $\kappa$ where not a successor cardinal, we could have that $\rho = \kappa$.)
Comment: if i suppose, by contraddiction, that $\rho = \lambda_1^{+}$ i.e. $\rho$ is a successor cardinal, then $\lambda_1 \in \rho = \cup \{\lambda < k | \lambda limit cardinal \} $ there must be a $\lambda_2$ such that $\lambda_1 < \lambda_2 < \rho$, so there is a cardinal between $\lambda_1$ and $\lambda_1^{+} = \rho$. contraddiction! So $\rho$ is a limit cardinal. Am I right?
Comment: @M.Bailetti That nearly works. We don't know that $\lambda_1$ is a limit cardinal but that isn't needed at all. No matter what $\lambda_1$ is, there must be a limit cardinal $\lambda_1 < \lambda_2 < \rho$ (as $\rho$ is the supremum, as an ordinal, of these limit cardinals) -- which is, of course, absurd.
Comment: Got it! Thank you so much! In this proof we don't need AC, do we?
Comment: @M.Bailetti That's right. We don't need choice, as long as we assume that $\kappa$ is an ordinal, i.e. well-orderable. In particular, the proof would work even if $\kappa$ were singular (which is possible in the abscence of choice).
Comment: Are there cardinals that are not ordinals ? The definition that i have for "$k$ is a cardinal" is " an ordinal that is not in bijection with any ordinal $\alpha < k$".
Comment: @M.Bailetti Without choice, there are sets which are in no bijection to an ordinal. They are, modulo bijection, also considered cardinals. The $\aleph$-numbers are then those cardinals which are in bijection to some ordinal (or equivalenty those that can be well-ordered).
Comment: Ok, i wasn't considering those sets as cardinals. Thank you, again.
Answer: Choice has nothing to do with this. The $\aleph$ numbers are defined the same. Of course, for non-$\aleph$ cardinals there is an issue for what would be a successor, or limit, and so on. So let's ignore that issue and focus on $\aleph$ cardinals.
You can easily prove this by induction, noting that successor cardinals are exactly those whose $\aleph$ index is a successor ordinal. So the question is reduced to limit ordinals below infinite successor ordinals, and this question is easier to grasp.


What are the ideals of $\mathbb{Z}/n\mathbb{Z}$?

Question: I am trying to find all the ideals of $\mathbb{Z}/2 \times \mathbb{Z}/4$. I've just proven that the ideals of $R$ × $S$ are precisely the sets of the form $\{(x,y):x \in I,y \in J\}$ for $I\subset R,J \subset S$ ideals.
I can see that I need to find the ideals of $\mathbb{Z}/2$ and $\mathbb{Z}/4$ but I'm struggling how to do this. I think that a proper ideal can't contain 1 otherwise the ideal is the whole ring. Does this mean that the ideal of $\mathbb{Z}/2$ is $\{0\}$ and the ideal of $\mathbb{Z}/4$ is $\{0,2\}$?
I think this is the case since if 3 was in the ideal of $\mathbb{Z}/4$ we would have 3+2=1 meaning that 1 would need to be in the ideal.
Comment: Rings without unity can act differently. For example let $R = 2\mathbb{Z}/4\mathbb{Z} = \{0,2\}$ where $2^2 = 0$. In $R \times R$, $I = \{(x,y) \mid x=y\} = \{(0,0) , (2,2)\}$ is an ideal.
Comment: I can recall that for finite products the ideals are of the form $I \times J$, where either $I$ can be $R$ or $J$ can be $S$, one should see this by projection of some ideal to $R$ and $S$. In your example $(1,1) \in I$, $(1,1)(x,y) = (x,y)$ and therefore $I = R \times R$. Edit: I see, you mean that an ideal of $R \times S$ can be a proper subset of $I \times J$, that sounds right...
Comment: Indeed @user028230 my counterexample is not one, abd actually the property I thoughy false is true. My apologies
Comment: @user028230 If $R_1$ and $R_2$ are rings with unity then each ideal $I \subseteq R_1 \times R_2$ is of the form $J_1 \times J_2$. Let $J_i$ be the image of $I$ in the projection to $R_i$. For $(x,y) \in J_1 \times J_2$, there are $(x,y'),(x',y) \in I$; then $(x,y) = (1,0)(x,y')+(0,1)(x',y)$, so $(x,y) \in I$.
Comment: Can you explicitly fix what you mean in your title? It is not clear. I just added the backslashes.
Answer: Let $\pi : \mathbb{Z}\to \mathbb{Z}/n\mathbb{Z}$ be the canonical projection.
Then by the lattice-isomorphism theorem, all ideals of $\mathbb{Z}/n\mathbb{Z}$ are of the form $\pi(I)$ for $I$ ideal of $\mathbb{Z}$ containing $n\mathbb{Z}$.
Those $I$ are precisely the $d\mathbb{Z}$ for $d\mid n$.
Therefore the ideals of $\mathbb{Z}/n\mathbb{Z}$ are the $d\mathbb{Z}/n\mathbb{Z}$ for $d\mid n$
Comment: For your second line, you can use the more general, and (maybe?) easier "correspondence theorem."
Comment: @AndresMejia : maybe what you call "correspondence theorem" is what I call the lattice-isomorphism theorem. What is the statement you're referring to ?
Comment: Thanks for the help Max, I appreciate you putting it in general for any n.
Answer: You are right: there are two ideals in $\mathbb{Z}/2\mathbb{Z}$, the zero ideal $(0) = \{0\}$ and the unit ideal $(1) = \{0,1\} = \mathbb{Z}/2\mathbb{Z}$. There are three ideals in $\mathbb{Z}/4\mathbb{Z}$, the zero ideal $(0) = \{0\}$, the ideal $(2) = \{0,2\}$, and the unit ideal $(1) = \{0,1,2,3\} = \mathbb{Z}/4\mathbb{Z}$.
(This is just the same thing that Max said: there are two positive divisors of $2$, $d \mid 2$ for $d=1,2$; and there are three positive divisors of $4$, $d \mid 4$ for $d=1,2,4$.)
So there are $6$ ideals in $\mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/4\mathbb{Z}$, including the zero and unit ideals.
Comment: Hi @Zach, sorry for the slow reply I've been busy with a computing assignment so had to put this to one side for a while! Thanks for clearing this up for me, your answer has really helped. So for it to be a proper ideal, does this mean the unit ideals don't count? Otherwise the ideal is the ring.


Proper grip of blade for shakehand

Question: When holding the paddle, where should I grip the most tightly?
I've been told to hold the paddle loosely because it makes it easier to switch from various stance. Are the main pressure points around the thumb and middle finger? The thumb having the higher pressure?
Answer: The main pressure points are your index finger and thumb, because they hold the paddle. The fingers on the grip are just holding it in place and should be just tight enough to keep the paddle from moving around in your hand. So yes, you can hold it loosely.
How tight you have to hold it depends on your play style, how comfortable you are with it and which stance you're playing with (the pressure points move a bit in forehand or backhand grips when the wood doesn't fit exactly between index finger and thumb anymore).
If you're just learning the shakehand grip you can simply put a small coin under the tip of your index finger and play without losing the coin. This should give you a proper feeling of how tight you need to hold your paddle. And it helps to keep the finger where it belongs.

Proper grip of blade for shakehand


Is $\frac{0}{\pi}$ rational?

Question: In math lesson, our teacher showed this formula.
$Q = \{\frac{a}b\}\land (a\land b\in Q)\land (b\neq 0)$
According to this formula, $\frac{0}\pi$ is... strange.
You know, $\frac{0}\pi$ is 0 and 0 is rational. But $\pi$ is irrational. That means $b$ is irrational.
So...  Is $\frac{0}\pi$ rational?
Comment: A number is rational if it has a representation of the form $\frac{a}{b}$ where $a,b$ are integers. It doesn't mean it can't have any other representations. Your number can be written as $\frac{0}{1}$, so it is rational. And by the way, please denote the set of rationals by $\mathbb{Q}$, and not $Q$.
Comment: $\frac{\pi}{\pi}$ is also rational, there is no contradiction here
Comment: The set of all numbers of the form $a/b$ where $a$ and $b$ are integers and $b \neq 0$ contains $0/1$, for example.
Comment: Frustratingly, there are many numbers we could write that we simply don't know one way or another whether the number is rational or irrational.  For instance, $\dfrac{e}{\pi}$ we still don't know if it is rational or irrational.  Knowing whether a number is rational or not is, again, knowing whether there exists a representation of that number which is a ratio of integers or knowing that no such representation exists.  Other types of representations of the numbers are often times irrelevant.
Comment: As an aside, don't use the tag [Education] just because a question about mathematics came up during your education.  That tag is meant to be used for questions about the action of educating and the pedagogy of teaching such as "*How frequently should tests or quizzes be administered to gauge student's progress*" etc...
Answer: It happens that $\dfrac0\pi=\dfrac01(=0)$. So, $\dfrac0\pi$ is rational.
Also, $\dfrac{\sqrt2}{\sqrt8}$ is rational (in spite of the fact that $\sqrt2$ and $\sqrt8$ are irrational), since it's equal to $\dfrac12$. It's a similar situation: the fact that I can write a number as a quotient of two numbers such that at least one of them is not an integer doesn't allow me to deduce that that number is irrational.
Comment: Thanks! This answer is helpful!

Is $\frac{0}{\pi}$ rational?


How to compute feature-space distance?

Question: some CV research papers use nearest neighbors techniques to compare images, such as PROGRESSIVE GROWING OF GANS FOR IMPROVED QUALITY, STABILITY, AND VARIATION

Next five rows: Nearest neighbors found from the training data, based on feature-space distance.

What is "feature-space distance" in this context? How to compute the feature-space distance" in this context?
Could someone please give a hint?
Answer: They mean that there's some kind of distance measurement$^{\dagger}$ on their feature space, and that allows them to determine how far two points are from each other. However, the paper should specify somewhere what kind of distance function they use: Euclidean distance $(l_2)$, taxicab distance $(l_1)$ etc. If it doesn't, shame on the authors for failing to give this important information, not on you for failing to guess what they did. (The distance function may be given in a reference.)
Perusing the article, there are several explicit references to particular types of distance. They seem particularly interested in Wasserstein distance.
$^{\dagger}$I mostly mean a metric space, though there may be exotic situations where some distance measure is useful but lacks some properties of a true metric. (KL divergence, which lacks symmetry, comes to mind.)

How to compute feature-space distance?


Proving uniform convergence of a function+

Question: Let $f_{n},g_{n}:[0,1]\rightarrow\mathbb R$ be given by $g_{n}(x)=\frac{2nx}{1+n^3x^2}$ and $f_{n}(x)=\frac{\log(1+n^3x^2)}{n^2}$
Show that $g_{n}(x)$ converges uniformly to $0$. (Completed)
Now use this this to show that $f_{n}(x)$ also converges uniformly to $0$
Obviously I need to make use of $f_{n}(x)=\frac{\log(2nx)-\log(g_{n}(x))}{n^2}$, just not sure where to go from here.
Answer: Regarding using $f_n$, here's a hint. Note that $g_n=f_n'$. We have
$$ |f_n(x)| = \left|f(0) + \int_0^x g_n(y)dy\right|\le |f(0)| + \int _0^1 |g_n(y)| dy $$
Though the other answer was pretty simple
Comment: So how do I conclude? The term on the far right tends to zero as $n\rightarrow \infty$? And $f(0)=0$? Which shows $f_{n}(x)$ converges uniformly?
Comment: @Loobear23 yeah. I guess I gave more of a sketch than a hint


Error: Could not find or load main class with Spark in Eclipse

Question: Facing issue while running a spark application from Eclipse (scala). However I'm able to run Scala from eclipse without any issue; the issue seems to appearing only with spark app.

Error: Could not find or load main class com.sidSparkScala.RatingsCounter*

package com.sundogsoftware.spark

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.log4j._

/**
  * Count up how many of each star rating exists in the MovieLens
  * 100K data set.
  */
object RatingsCounter {

  /** Our main function where the action happens */
  def main(args: Array[String]) {

    // Set the log level to only print errors
    Logger.getLogger("org").setLevel(Level.ERROR)

    // Create a SparkContext using every core of the local machine, named RatingsCounter
    val sc = new SparkContext("local[*]", "RatingsCounter")

    // Load up each line of the ratings data into an RDD
    val lines = sc.textFile("../ml-100k/u.data")

    // Convert each line to a string, split it out by tabs, and extract the third field.
    // (The file format is userID, movieID, rating, timestamp)
    val ratings = lines.map(x => x.toString().split("\t")(2))

    // Count up how many times each value (rating) occurs
    val results = ratings.countByValue()

    // Sort the resulting map of (rating, count) tuples
    val sortedResults = results.toSeq.sortBy(_._1)

    // Print each result on its own line.
    sortedResults.foreach(println)

  }

}

Comment: Have you added scala nature to your project in eclipse ide???
Comment: Sorry for the naive question, but is the `package` statement actually missing or did you just forget to paste it here?
Comment: Have you given the proper package name. i guess there is some mismatch in the package name.
Comment: Actually there is a mismatch in the package name. It worked well once i gave the correct name. Not sure how i overlooked such a small thing and spent whole day to figure out the issue :). Great catch. Thank you so much.
Answer: It seems like the package name you originally created is this com.sidSparkScala.RatingsCounter and the package name mentioned in the script is com.sundogsoftware.spark (at the top). All you have to do is replace the package com.sundogsoftware.spark with com.sidSparkScala.RatingsCounter.
Answer: Your class is not compiled properly, otherwise eclipse could find this class. Please check, is there any compilation error.
Answer: You must change the package name to yours, not the courses provided.
I guess you import this scala file from external, based the code above, the package is com.sundogsoftware.spark , just change it to yours would be fine.


PHP - checking file type using exif_imagetype error

Question: I am trying to check that an uploaded image is a PNG, JPG or GIF and not just check the file extension. I am trying the following:
<code>$allowed_types = array (IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['file_to_upload']['tmp_name']);
    if ( !in_array($detectedType, $allowed_types) ) {
        die ( 'Please upload a pdf or an image ' );
    }

//code to handle image
</code>
However I am receiving an alert even if it is an image. Can anyone point me towards why?
Comment: Why downvote without any comment?
Comment: Possible duplicate of [php check file extension in upload form](http://stackoverflow.com/questions/10456113/php-check-file-extension-in-upload-form)
Comment: @shaggy i was trying to find out the extension from exif data, not by stating the names of the allowed extensions in an array so not duplicate
Comment: using mime type [is not accurate](http://stackoverflow.com/questions/7349473/php-file-upload-mime-or-extension-based-verification), why do you want to use it?
Comment: @shaggy, to be suer that the files are actual image files and not a malicious file that has been given the extension .jpg, .png etc. How would you suggest the correct way if this is wrong?
Comment: Your code is the way how you get uploaded malicious file. Look at my previous comments, there is the right solution (both links).
Answer: should have been:
<code> $allowed_types = array (IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
 $detectedType = exif_imagetype($_FILES['file']['tmp_name']);
    if ( !in_array($detectedType, $allowed_types) ) {
    die ( 'Please upload a pdf or an image ' );
  }
</code>


On press of a Card button should direct to new page to display some information using React Routers : router, link, route

Question: I have few cards on my home page each one with some info and read button so if a user presses the button should be directed to a new page to read the details inside the card but I'm not sure how to achieve this. I tried using react-router but on pressing the button, it rendered the new page inside my home page. Please guide me through the steps that need to be taken.
Answer: Use the useHistory hook from react-router-dom.
import React from 'react';
import {useHistory} from 'react-router-dom';
import Card from './Components/Card.js';

// The parent component of "Card"
    const Home = () => {
       const history = useHistory();

       return (

            <Card {...props} onClick={() => history.push('/path/to/article')} />

       );
    }

This is the card component:
    const Card = ({...props, onClick}) => {
        return (

             ...

        )
    }


Change on every other row

Question: I have problem with that the first row misses a
 and then there is one line and then there is a
 and then it works perfect with one
 and two lines and
 and so on. How to change the code to make that work?
Any ideas to use "div" instead of "table"?

<?
            $query = mysql_query("SELECT * FROM pages ORDER BY id ASC");
            while($r = mysql_fetch_array($query))

            {
                if(++$s % 2 == 0) { echo '
'."\r\n"; }
                echo ' · '.$r['domain'].' 	'."\r\n";
                if(++$i % 2 != 0) { echo '
'."\r\n"; }
                }
?>

Answer: Use $s++ instead of ++$s, so you test the value before you increment it. And there's no need to use a separate $i variable, you can just use the same $s variable without incrementing it.
$s = 0;
while ($r = mysql_fetch_array($query)) {
    if ($s++ % 2 == 0) {
        echo "
\r\n";
    }
    echo ' · '.$r['domain'].' 	'."\r\n";
    if ($s % 2 == 0) {
        echo "
\r\n";
    }
}
// If we ended loop without closing the row, do it now
if ($s % 2 == 0) {
    echo "
\r\n";
}

Answer: Sounds like you're trying to build a 2-column table? You don't need two counters for that, one will do:
$cells = 0;
while(...) {
   if (($cells % 2) == 0) {
      echo '
';   // start a new row for cells 0, 2, 4, etc...
   }
   echo ' ....';
   if (($cells % 2) == 1) {
     echo '
'; // close the row after outputting cells 1,3,5,etc...
   }
   $cells++;
}

Change on every other row