Connection between loss and likelihood function

Question: Simple question: Can we generally think of the loss function as the negative of the likelihood function?
For instance with regards to logistic regression, the likelihood function in a binary setting is
$\sum_i y^{i}\log(h(x^i))+\log(1-y^i)(1-h(x^i))$
while the loss function is
$- \Big[\sum_i y^{i}\log(h(x^i))+\log(1-y^i)(1-h(x^i))\Big]$
However, in Maximum-A-Posteriori (MAP) tasks I have seen that the loss function is derived by maximizing the posterior, i.e. the loss function being the differentiation of the likelihood function times the prior.
Comment: The first equation is the *log* likelihood.
Answer: In linear regression and logistic regression, without regularization, we can think the objective is to maximize likelihood.
On the other hand, we the term "loss function" is more general than likelihood.
For example, we can add regularization (See Regularization methods for logistic regression).
We can also add other constraints or use weighted loss. All of these are "add on" to likelihood.
Check this post for details
Objective function, cost function, loss function: are they the same thing?
Comment: @Pegah MAP can be viewed as a generative model and logistic regression is a discriminative model, which we only focusing on getting $P(Y|X)$. this paper may help. https://ai.stanford.edu/~ang/papers/nips01-discriminativegenerative.pdf
Comment: What I mean is this: When we optimize with MAP, we maximize the posterior, i.e. we maximize likelihood x prior. In the logisitic regression context, we maximize however the likelihood function as quoted above. This likelihood function however has class conditioned on data similar to the posterior of say a bayesian classifier. Sorry if it is not understandable, not sure how to put it differently
Comment: I agree with the things you said in your answer. Regarding the last comment, I wouldn't say that MAP is a generative model. It's an approach for estimating parameters (not a model at all), and can be used with either generative or discriminative models. For example, MAP estimation could be used to fit a logistic regression model w/ priors, which is a discriminative model.
Comment: Also, linear regression is only equivalent to MLE when we assume the error has a normal distribution.


Authentication in Express and passport authentication

Question: How I can implement API authentication on my NodeJS Express framework for a react based web framework along with option for passport authentication.
Comment: Do you mean authentication of services for React based web application developed using express and mongo?
Comment: Exactly @SureshPrajapati using Reactjs Frontend and Express Backend.
Answer: You have to implement authentication mechanism via cookie or session. After successful login you will set a cookie in the browser and on each HTTP req you will have access to cookie data to check for req from a logged in user's browser or not.
Create a middleware function which will check for valid cookie data in req object for each API requests.
If a user is not logged in and trying to access a particular resource by an API call, then request will be unauthorized (401).
You need to change your login API something like this.
function login(req, res){
    // Your logic for DB checks and to validate credentials will go here

    // On valid credentials, you can set the cookie like this
      res.cookie(cookieName, cookieData, cookieOptions);
}

and middleware function which checks for authentication can go like this
function checkSession(req, res, next) {
  if(!req.cookies || !Object.keys(req.cookies).length){
    res.send(401)
  }
  else next();
}

You can find more details on how to use cookie-parser here.
Comment: Thank you @Suresh but what about redux and passport for login form ?
Comment: Redux has no relation with authentication, it will help you in making your application's UI as a function of component state whereas passport auth is additional authentication mechanism which you have to implement. Refer online tutorials on Express authentication and passport js. Below can help in understanding passport authentication https://blog.risingstack.com/node-hero-node-js-authentication-passport-js/


Is there an easy way to find the complex roots of this polynomial?

Question: I want to find the complex roots of $1-x-x^2-...-x^k$ for some $k\in\mathbb{N}$. Alternatively, since $(1-x)(1-x-...-x^k) = 1-2x+x^{k+1}$, finding the roots for $1-2x+x^{k+1}$ would also suffice.
Comment: You already gave a good approach , I think we will need numerical methods in general. Newton could be a good approach , even in the complex numbers.
Answer: It seems likely that we'll need to use numeric methods to approximate the roots, because it isn't obvious that there's a natural factorisation for general values of $k$. However, we can make the following observation:
Let $p(x) = 1 - 2x + x^{k+1} = (1 - x)(1 - x - x^2 - \ldots - x^k)$ (you had a sign error in your question). Then $p'(x) = -2 + (k+1) x^k$. Then if we set $p'(x) = 0$ we get $x^k = \frac{2}{k+1}$. If $k$ is odd then this has a single solution $x = \sqrt[k]{\frac{2}{k+1}}$, while if $k$ is even then there are two solutions $x = \pm \sqrt[k]{\frac{2}{k+1}}$.
From the values of $p(x)$ and $p''(x)$ at these values, we can determine that for $k > 1$ we will always have two roots when $k$ is odd, and three when it's even. But we want to drop the $x = 1$ root, so that means that $1 - x - \ldots - x^k$ will always have 1 root when $k$ is odd, and 2 when $k$ is even. One of those roots will be in the interval $(0, \sqrt[k]{\frac{2}{k+1}})$.
Also, if $k$ is even then the other root can be easily confined to the interval $(-2, -1)$, and you can probably get a tighter bound fairly quickly.
Comment: Good catch on the sign error. I guess I was hoping there was a non-numerical approach to this problem. Oh well


Do access logs (from nginx) slow down a website?

Question: Does it slow down a website if your webserver (in my case, nginx) is writing to an access log?
I'm mostly wondering if it's noticeable.
Plus, what's the point of knowing the user agents / ips that have visited?
Answer: I don't believe you will notice any hit in performance.  Log writes will likely be buffered and then flushed out to disk.  So unless you have high disk load you will be fine.  If you do have high disk load than you probably want more memory (if this is only a webserver) so web data is served from a memory cache.
Nginx is programmed with an event driven methodology so log writes shouldn't block the serving of pages. I imagine threaded / forking web servers probably use a different thread or process for this as well.
You could also send logs to an external host with syslog (or perhaps even using a Nginx directive).
User-Agents help you know where the traffic comes from and the browser. Good crawlers will set a UA like "Googlebot" and browsers should be specified in the UA.  IPs also help identify traffic sources.  You will want this information if you ever want some analytics from the logs with something like awstats.
Comment: Log writes are indeed buffered by default at 64K. NGINX writes each time it has more than 64KB of log data buffered though you can set this value `access_log buffer=128k`.
Comment: @Marc, I don't think this is entirely accurate, I can do a `tail -f access_log` and see it updating in real-time.
Answer: Compared to the resources necessary to process a request, the writing of one line of log is usually not a big deal and the file is opened once (Unless you are the victim of some DOS attacks, where the log - written to the disk after a number of accesses - will keep your machine pretty busy).
Regarding the logs, I keep my Nginx outputs to make some statistics (where are the accesses, from which country, which browser etc...).
If you don't need them, and/or worry about the disk space they take, check the logrotate configuration for nginx (should be in /etc/logrotate.d, file nginx). The Ubuntu default is rotate for 52 weeks, meaning that logs older than a year are deleted.


Infinite series bounded by another infinite series

Question: Is there a way to prove that $$\left( \sum_{i=1}^{\infty} |x_{i}|^{p} \right)^{m/p} \leq \sum_{i=1}^{\infty} |x_{i}|^{m}$$
for $0 < m < p$? I'm not sure where to start and would appreciate any help!
As a side question, I was wondering if $\lim_{p \to \infty} \left( \sum_{i=1}^{\infty} |x_{i}|^{p} \right)^{m/p}$ exists. I have a hunch it does, but I'd like to prove it. Is it possible to prove it converges by using the Monotone Convergence Theorem, since we've shown it is bounded already? How would we prove it is monotone?
Answer: Raise both sides to $\frac{p}{m}$ power and get  $\sum\limits_1^\infty|x_i|^p\le (\sum\limits_1^\infty|x_i|^m)^{p/m}=\sum\limits_1^\infty|x_i|^p+$(non-negative) cross terms.
Comment: Use math. induction.  Let $S=\sum\limits_1^n a_k$  Then $(\sum\limits_1^{n+1} a_k)^c=(S+a_{n+1})^c=S^c(1+a_{n+1}/S)^c$$\ge S^c(1+(a_{n+1}/S)^c)=S^c+a_{n+1}^c$$\ge \sum\limits_1^{n +1}a_k^c$, by induction (assume true for $n$). Comment:  $a_{n+1}\lt S$, else rearrange.
Comment: Induction shows it holds for all $n$.  Convergence has to assumed.  For example $p=2$ and $m=1$ with $x_k=\frac{1}{k}$ will converge for $p$ but not for $m$.
Comment: Your argument assumes $p/m$ is an integer. How would your argument work if $m=2,p=\pi$?
Comment: @MatthewPilling that's a good point. Is there a better way to go about proving this?
Comment: For a two term sum assuming $a\gt b\gt 0$, and $c\gt 1$.  Then $(a+b)^c=$    $a^c(1+r)^c\ge a^c(1+cr^{c-1}+...\ge a^c(1+r^c+...=$    $a^c+b^c+...\ge a^c+b^c$ where $r=b/a$.  This can be generalized to arbitrary sum.
Comment: @herbsteinberg Does this need the assumption that $x_i$ is a decreasing sequence? Is that enough to prove that $\left( \sum_{i=1}^{\infty} |x_{i}|^{p} \right)^{m/p}$ is decreasing? Then we know it is bounded and it is monotone, so it must converge as well.
Comment: @herbsteinberg Thanks for your comment! I'm still struggling to use this to show that the limit exists though.
Comment: Thank you! I see that now.


To exclude a main effect that is not of interest in ANCOVA, or not?

Question:
Possible Duplicate:
Including the interaction but not the main effects in a model

I have an experimental design with pretest and posttest. Two groups, experimental and control group. I am interested in finding whether there will be a difference between experimental and control group at the posttest, controlling for pretest. Therefore, I run ANCOVA with pretest as covariate, posttest as DV, and group as IV.
I am also interested to see if there will be a gender differences for the experimental effect. Thus, I am interested in looking at the interaction term group*gender. I am not interested in looking at gender main effect alone, as it doesn't mean much to this experimental design.
I customized the model and excluded the main effect of gender, and the results showed only the main effect of group and the interaction effect of group*gender.
Is this okay, or do I need to run a full model including gender main effect? Thank you.
Comment: This question should also be of interest: [do-all-interactions-terms-need-their-individual-terms...](http://stats.stackexchange.com/questions/27724/).
Comment: I realized that excluding the gender main effect would affect the p value of both the group main effect and the interaction effect. Which is why I am unsure of whether to exclude it or not.
Answer: There's a rather extensive and interesting discussion of this issue in this thread.  To summarize, excluding a main effect makes the interpretation of your parameters tricky.  However, there are a few situations (discussed in the thread) where this makes sense, such as a pure prediction model.
Answer: I see nothing wrong with it.  Another approach (but not preferable) is to see if there is a significant change from baseline due to the intervention.
Comment: I don't think this is wrong, but I do think it's dangerous advice to tell someone it's OK to exclude the main effects terms but include the interaction. You may want to read through the questions @user1188407 & I have linked.
Comment: @gung I have been involved in some of the posts discussing including interactions without main effect terms.  Aside from the statistical dogma of it, their is no logical reasonwhy both main effects need to be included.  It could make sense to exclude them based on knowledge of the datqa.


About complex sum and modulus

Question: Let $\left(a_{n}\right)_{n},\,\left(b_{n}\right)_{n}$ two succession of non negative real numbers, $\left(c_{n}\right)_{n}$ a succession of complex numbers and $N$ a large natural number. Suppose that $$a_{n}\leq b_{n},\,\forall n.$$ My question is: is it true that $$\left|\underset{n=1}{\overset{N}{\sum}}a_{n}c_{n}\right|\leq\left|\underset{n=1}{\overset{N}{\sum}}b_{n}c_{n}\right|?$$
Answer: Let
\begin{align*}
\{a_n\}&=\{1,0,0,0,\dotsc\} \\
\{b_n\}&=\{1,1,0,0,\dotsc\} \\
\{c_n\}&=\{1,-1,0,0,\dotsc\}
\end{align*}
Then for $N\geq 2$
$$
\left|\sum_{n=1}^Na_n\cdot c_n\right|=1
$$
but
$$
\left|\sum_{n=1}^Nb_n\cdot c_n\right|=0
$$
One could also concoct a slightly more interesting counterexample. Let
\begin{align*}
a_n&=
\begin{cases}
0 & 1\leq n<M \\
1 & n\geq M
\end{cases} \\
b_n&=1 \\
\{c_n\}&=\{\zeta_1,\zeta_2,\dotsc,\zeta_M,0,0,\dotsc,\}
\end{align*}
where $\zeta_1,\dotsc,\zeta_M$ are the $M$th roots of unity.
Then for $N\geq M$
$$
\left|\sum_{n=1}^Na_n\cdot c_n\right|=1
$$
but
$$
\left|\sum_{n=1}^Nb_n\cdot c_n\right|=0
$$
Comment: Thank you! And if $\left(a_{n}\right)_{n},\,\left(b_{n}\right)_{n}$ are two monotone increasing successions?
Answer: Consider $(a_n) = (c_n) =  -1,1,-1,1...$ and $(b_n) = 2,2,2,2,2,2...$
Comment: $a_n$ and $b_n$ are given as *nonnegative*.
Comment: Ah, didn't see that

About complex sum and modulus


Why $\log xy=\log x+\log y$?

Question: It is of course well known and basic formula. I am just curious. Is there a proof for it?
How to prove that $\log xy=\log x+\log y$?
Comment: It depends on how you define the logarithm.
Comment: Some people may claim that the motivation of defining the logarithm is the functional equation $f(xy)=f(x)+f(y)$.
Comment: Still have my old slide rule...
Comment: What side rule?
Answer: We have $$\ln (xy) = \int_{1}^{xy}\frac{dt}{t}=\int_{1}^{x}\frac{dt}{t}+\int_{x}^{xy}\frac{dt}{t}=\ln(x)+\int_{x}^{xy}\frac{dt}{t}.$$ For the last integral, we substitute $u=\frac{t}{x}$ to get $du=\frac{dt}{x}$, thus reducing the last integral to $\int_{1}^{y}\frac{du}{u}=\ln (y)$. Hence, $\ln(xy)=\ln(x)+\ln(y)$.
Dividing both sides by $\log (a)$, we have $\log_{a}(xy)=\log_{a}(x)+\log_{a}(y)$ for any base $a\neq 1.$
Comment: I like this because it's cool, but I don't think this would work for the average algebra student unless they happen to know calculus...
Comment: @user140943 , the OP has himself tagged calculus.
Answer: $$e^{\ln(x)+\ln(y)}=e^{\ln(x)}e^{\ln(y)}=xy$$ so $$\ln(xy)=\ln(x)+\ln(y)$$
As noted in the comments, this works for any log. I used base $e$ out of habit/convenience.
Comment: And this of course applies to every log, but you have to change the exponent ($e$ in the example) by the base of the logarithm. Then its proven for all cases
Comment: @Mathias711: $e$ in these formulas is not an "exponent" but a "base". That's _why_ it's the base of the logarithm!
Comment: @HenningMakholm Yeah, that is what I meant. I couldn't come up with the word. Thanks for clarifying.
Answer: Let $m = \log_a(x)$ and let $n = \log_a(y)$
Express $x$ and $y$ in terms of exponents, so $x = a^m$ and $y = a^n$.
Therefore $xy = a^{m+n}$
Take the $\log$ of both sides to obtain:
$$\log_a(xy) = \log_a(a^{m+n})$$
$$\log_a(xy) = (m+n)*\log_a(a)$$
$$\log_a(xy) = m + n$$
$$\log_a(xy) = \log_a(x) + \log_a(y)$$
Answer: Under the definition of $\ln(x)$ by integration of $\frac{1}{x}$, there is another way to work with the integral
$$\int_{x}^{xy}\frac{dt}{t}$$
By splitting the integral into
$$\int_{x}^{xy}\frac{dt}{t}=\int_{1}^{xy}\frac{dt}{t}-\int_{1}^{x}\frac{dt}{t}.$$
This follows readily from the fact that the integral is in essence a signed area under a curve, or more formally, from the Riemann sum.
The rest is the same as the proof given by user Indrayudh Roy.
Answer: The logarithm of a number with respect to a certain base is just the exponent to which this vase must be raised to give the number. Thus, if we express $N>0$ as a power of a base $1\ne b>0,$ we have that $$b^{\ell}=N.$$ This $\ell$ is what is called the logarithm of $N$ to the base $b,$ usually written $\log_bN$ for short.
Thus, suppose we have two numbers expressed as powers of the same base $b,$ say $b^x$ and $b^y,$ then $x,y$ are respectively the logs of these numbers to their common base, $b.$ Now if you multiply these numbers you get (according to the basic rule of indices) $$b^xb^y=b^{x+y},$$ so that the logarithm of the product to the base $b$ is just the sum of the logarithms $x+y.$

Why $\log xy=\log x+\log y$?


Normal and Uniform Distribution, calculate $P(Y>X\mid X=x)$

Question: Let $X$ and $Y$ be independent random variables distributed as $X \sim N(0,1)$ and $Y \sim \operatorname{Unif}(0,1)$.
(a) Find $P(Y > X\mid X = x)$.
(b) Use your answer in part (a) to compute $P(Y > X)$
I'm not sure where to start...
I think the joint density is
$$
f(x,y) = \frac{1}{\sqrt{2π}}e^{-x^2/2},  \quad
0<x<1, 0<y<1
$$
And do I just integrate that? If so from where, 0 to 1 on both integrals? I'm pretty lost with this and any help would be so appreciated. Apologies if it's not formatted correctly or if my attempt at an answer is plain stupid. I don't even really understand what part (a) means...
Answer: HINT
Easier to think about it directly:

if $x \ge 1$ what is $\mathbb{P}[Y > X\mid X=x]$?
if $x \le 0$ what is $\mathbb{P}[Y > X\mid X=x]$?
if $x \in (0,1)$ what is $\mathbb{P}[Y > X\mid X=x]$?

For (b), recall the definition of conditional probability. The analog of $\mathbb{P}[X=x]$ in the continuous world is
$$\lim_{\epsilon \to 0} \mathbb{P}[X \in (x-\epsilon,x+\epsilon)] = f_X(x)$$
Comment: @a305 No. The pdf of $Y$ denoted $f_Y(y)$ looks like that though. And you need the cdf $F_Y(x)$ since you are interested in $\mathbb{P}[Y > x] = 1 - \mathbb{P}[Y \le x]$
Comment: @a305 be careful, $F_Y(x) = x$ only if $x \in (0,1)$ (answer to the 3rd bullet question). Can you answer the other 2 bullet questions in my answer? For (b) use the more direct hint in drhab's answer...
Comment: @a305 (b) is asking for a specific number, i.e. what is the probability that $Y>X$. On the other hand, (a) is asking for what that value would be depending on a parameter $x$ -- like the bullets in my answer break it down into cases. For (b) you need to "weigh" the cases to produce the "overall" probability...
Answer: Hint on a):
$$\Pr(Y>X\mid X=x)=\Pr(Y>x\mid X=x)=\Pr(Y>x)$$
The second equality because $X$ and $Y$ are independent.
Hint on b):
$$\Pr(Y>X)=\int \Pr(Y>X\mid X=x)f_X(x) \, dx$$ where $f_X$ denotes the PDF of $X$.
Comment: If e.g. $x>1$ then $\Pr(Y>X\mid X=x)=0$ because $\Pr(Y>1)=0$. This is a special case of a). The outcome depends on $x$. In b) the outcome is just a real number, i.e. the probability that random variable $Y$ will exceed random variable $X$.
Answer: $$
\Pr(Y>X\mid X=x) = \underbrace{\Pr(Y>x\mid X=x) = \Pr(Y>x)}_{\large\text{These are equal because of independence}} = \begin{cases} 1-x & \text{if } 0\le x\le 1, \\ 0 & \text{if }x>1, \\ 1 & \text{if } x<0. \end{cases}
$$
Therefore
$$
\Pr(Y>X\mid X) = \begin{cases} 1-X & \text{if } 0\le X\le 1, \\ 0 & \text{if } X>1, \\ 1 & \text{if } X<0. \end{cases}
$$
$$
\Pr(Y>X) = \operatorname{E}(\Pr(Y>X\mid X)) = 1\cdot\Pr(X<0) + 0\cdot \Pr(X>1) + \int_0^1 (1-x) \varphi(x)\,dx
$$
where $\varphi$ is the standard normal density.
$$
\int_0^1 (1-x)\varphi(x)\,dx = \int_0^1 \varphi(x)\,dx - \int_0^1 x\varphi(x)\,dx.
$$
The value of the first integral is the probability that a standard normal random variable is between $0$ and $1$, and everybody knows that's about $0.34.$ The second integral admits a closed form, thus:
$$
\frac 1 {\sqrt{2\pi}} \int_0^1 e^{-x^2/2} (x\, dx) = \frac 1 {\sqrt{2\pi}} \int_0^{1/2} e^{-u}\,du = \cdots.
$$
Comment: @a305 : You have $Y \sim \operatorname{Uniform}(0,1),$ so $\Pr(Y>x)$ is the probability that $Y$ is between $x$ and $1.$ The probability that $Y$ is within an interval that is a subset of $(0,1)$ is the length of the interval. The length of the interval from $x$ to $1$ is $1-x. \qquad$


$\mathbb {N}_{0}$ is a subset of $\mathbb{Z}$ but $\#\mathbb{N}_{0}=\#\mathbb{Z}$? Is this why set theory is "wrong"?

Question: So I was told this the other day and it kinda makes sense. All of the natural numbers and 0 are also integers, but not all integers are positive or 0. So it follows that $$\mathbb {N}_{0} \subsetneq \mathbb{Z}$$
However, there exists at least one function $f:\mathbb{N}_{0} \rightarrow \mathbb {Z}$ such that $f$ is bijective. That means that $\# \mathbb{N}_{0}=\# \mathbb{Z}$. How can this happen? What is the explanation behind this?
Comment: "Young man, in mathematics you don't understand things. You just get used to them." - John von Neumann
Comment: The set $\mathbb{N}$ has an injection $n \to n + 1$ that isn't bijective. Why is that a problem?
Comment: One motto is "counting arguments only work for finite sets" (with care over what is meant by counting - essentially the pigeonhole principle). Every infinite set can be put into bijection with a proper subset of itself. Why does this make set theory "wrong"?
Answer: So essentially this is the concept of cardinality of infinite sets. Both of the sets you listed are countably infinite, that is, by definition they can be mapped to a subset of the naturals (in this case the improper subset, because we need all of them). Sets of this size are said to be of size $\aleph_0$ (that is the first Hebrew letter "aleph"), which is classified as a transfinite number. It is notable to mention that this infinite cardinality is less than $\aleph_1$, which is associated with the size of $\mathbb{R}$, said to be uncountably infinite (can you prove this?). To denote cardinality, we use vertical bars, for example $\vert \mathbb{N} \vert = \aleph_0$.
The point is, once you are dealing with infinitely many objects, the idea of sets being equinumerous becomes harder to define and must be looked at slightly differently. As one may assume, there are also other "infinities" that can be investigate.
Food for thought: Consider the set of rational numbers, $\mathbb{Q}$. Which is true $\vert \mathbb{Q} \vert = \aleph_0$ or $\vert \mathbb{Q} \vert = \aleph_1$ and why?
Comment: I'm guessing |Q| = Aleph0 but I'm not sure how to express why. I'd say because all numbers in Q,Z and N can be expressed as fractions of finite integers
Comment: "It is notable to mention that this infinite cardinality is less than $\aleph_1$, which is associated with the size of $\mathbb{R}$." No. $\aleph_1$ is the first uncountable cardinality (see [here](https://en.wikipedia.org/wiki/Aleph_number#Aleph-one) for a bit more on this), but the reals might be quite larger than $\aleph_1$; the statement "$\vert\mathbb{R}\vert=\aleph_1$" is the [continuum hypothesis](https://en.wikipedia.org/wiki/Continuum_hypothesis), and is not provable or disprovable from the usual axioms of set theory (= ZFC).
Answer: [Too long for a comment.]
Another example you might find interesting: each sequence of distinct natural numbers $a_n$ is/induces a bijection from $\mathbb{N}$ to the set $A=\{a_n:n\in\mathbb{N}\}$. The set $A$ could seem to be way smaller than the natural numbers (particularly if $a_n$ grows fast), but both sets have the same number of elements -or the same size if you find the wording misleading-, which doesn't mean that they have the same elements.It is simply the way we define equality of cardinal numbers; two sets have the same number of elements if we can compare them, that is if we can count the elements of one of them using the elements of the other, and viceversa (check the Schröder–Bernstein theorem if this doesn't make sense to you and then read it again!).
For another example, you might like to read about Hilbert's Hotel.
Confused? I think it might be a good mental exercise to try to come up with a "better way to define equality of set sizes". I would be surprised if you don't end up thinking that the actual definition is the most natural one, if not the only reasonable one.


How can I prove that $P \neq EXP$

Question: It seems like $P\neq EXP$ is much easier than $P \neq NP$. How can I prove $P \neq EXP$?
(Well, after all I want to know any proof technique of proving there does not exist any algorithm of certain time complexity to prove a decision problem.)
It seems like we have to construct a problem where there's no way but to check all the cases which is exponential time...
Answer: I guess this is what you are looking for.

How can I prove that $P \neq EXP$


Nonlinear Relation Sequences

Question: Assume the following relation sequence:
$a_n = \sum_{i=2}^{n-2} a_{i} a_{n-i}$
for $n \geq 3$, where $a_0 = a_1 = a_2 = 1$. How can we find a closed form expression for $a_n$?
I tried to use generating function as $f(x) = \sum_{n=0}^{\infty} a_n x^n$. However, I do not know how to proceed?
I appreciate any help in this regard!
Answer: Too long for a comment.
Assuming that there is no typo in $$a_n = \sum_{i=2}^{n-2} a_{i}\,a_{n-i}$$ I see a problem already for $n=3$ since
$$a_3 = \sum_{i=2}^{\color{red}{1}} a_{i}\,a_{3-i}\qquad a_4 = \sum_{i=2}^{\color{red}{2}} a_{i}\,a_{4-i}=a_2^2$$ So, I shall suppose that $a_3=0$ and, if this is true, then $a_{2n+1}=0$ and then the sequence would be
$$\{1,1,1,0,1,0,2,0,5,0,14,0,42,0,132,0,429,0,1430,0,4862\}$$ and $a_{2n}$ seems to be the Catalan number $C_n=\frac{(2 n)!}{n! (n+1)!}$.
If this is true, we do not care about the values of $a_0$ and $a_1$ and the sequence would be
$$\left\{{a_0},{a_1},{a_2},0,{a^2_2},0,2 {a^3_2},0,5
   {a^4_2},0,14 {a^5_2},0,42 {a^6_2},0,132 {a^7_2},0,429
   {a^8_2},0,1430 {a^9_2},0,4862 {a^{10}_2}\right\}$$
Comment: Thank you very much for the prompt response. Your answer is correct under the assumption of $a_3 = 0$. However, what will be the answer if we assume $a_3 \neq 0$?
Comment: @MortezaSoltani. The problem becomes much more complex

Nonlinear Relation Sequences


Let $X$ be a topological space and $U$ be aproper dense open subset of $X$. Pick the correct statement from the following

Question: Let $X$ be a topological space and $U$ be a proper dense open subset of $X$. Pick the correct statement from the following
(A) If $X$ is connected then $U$ is connected.
(B) If $X$ is compact then $U$ is compact.
(C)If $X\setminus U$ is compact the $X$ is compact.
(D)If $X$ is compact, then $X\setminus U$ is compact.
My attempt:-
(A) The usual topology on $\mathbb R$ and $U=\bigcup_{n\in \mathbb Z}(n,n+1)$ is open as well as dense. But not connected.
(B) Let $X=[0,1]$ and $U=(0,1)\cap \mathbb Q$. $U$ is open aswell as dense. But not compact.
(D)If $X$ is compact. suppose $\{U_\alpha\}_{\alpha \in \Lambda}$ be an open cover for $X\setminus U$. Then,$\{U_\alpha\}_{\alpha \in \Lambda}\bigcup \{U\} $covers $X.$ So, It must have finite subcover. Hence the result follows.
(C)This is my attempt to create counterexample for $(C)$. Suppose $\{U_\alpha\}_{\alpha \in \Lambda}$ be an open cover for $X$. We know that $x\in U,\implies \exists \alpha \in \Lambda: x\in U_\alpha$. If $U$ is finite, the result follows. But here $U$ is arbitrary. How do I cook counterexample from here?
Comment: For (B), $(0,1) \cap \mathbb Q$ is not open in $[0,1]$. But $(0,1)$ works as a counterexample
Comment: Would $X=(0,1]$, $U=(0,1)$ work?
Comment: @DavidMitra I think your example is fine.
Comment: @YuiToCheng Thank you
Answer: For (a), your counterexample works.
For (b), $X=[0,1]$ with $U=(0,1)$ works as a counterexample.
For (c), $X=[0,1)$ with $U=(0,1)$ works again.
For (d),  the statement is correct as $X-U$ is a closed subset of $X$, hence compact.
Comment: Here in $(c)$ we have $X = [0,1]$ compact, so this does not yield a counterexample.
Comment: @GuidoA. Sorry for the sloppiness.
Answer: For $(b)$, as said in the comments $U$ should be open, so you can instead choose $U = (0,1)$. As for $(c)$, you can consider $[0,1)$ with $U = (0,1)$ once again. The space $X \setminus U = \{0\}$ is certainly compact, but $X$ is not.


Functions question help me?

Question: a) We have the function $f(x,y)=x-y+1.$ Find the values of $f(x,y)$ in the points of the parabola $y=x^2$ and build the graph $F(x)=f(x,x^2)$ .
So, some points of the parabola are $(0;0), (1;1), (2;4)$. I replace these in $f(x,y)$ and I have $f(x,y)=1,1,-1\dots$. The graph $f(x,x^2)$ must have the points $(0;1),(1;1)$ and $(2;-1)\,$ , right?
b)We have the function $f(x,y) =\sqrt x + g[\sqrt x-1]$.Find $g(x)$ and $f(x,y)$ if $f(x,1)=x$?
I dont even know where to start here :/
Comment: In b, we don't have $y$ in $f(x,y)$. Is there a typo?
Comment: I hope I didn't mangle your question while re-formatting. Please check.
Comment: No,this is how it is written.
Comment: Out of the subject,Thomas,I love programming in Java too haha!
Comment: No,it is correct..
Answer: Hints:
a) $F(x)=f(x,x^2)=x-x^2+1 =-(x-\frac12)^2+...$
b) As it stands, if I understand well, $f(x,y)=\sqrt x+g(\sqrt x-1)$ is independent from $y$. Then $f(x,1)=x$ means
$$\sqrt x+g(\sqrt x-1)=x\,.$$
To find $g$, probably the best is to introduce a new variable $z:=\sqrt x-1$, then $\sqrt x=z+1$ and $x=(z+1)^2$.
Comment: Isn't that $\,g[\sqrt x-1] = g\,$ of the integral value of $\,\sqrt x-1\,$ ?
Comment: Possibly yes, but that would make the exercise harder..
Answer: And If  the function $f(x,y)$ be like $$f(x,y)=\sqrt{y}+g(\sqrt{x}-1)$$, then the way is similar to @Berci's answer.Y ou pointed that $f(x,1)=x$ so $$1+g(\sqrt{x}-1)=x$$ Set $\sqrt{x}-1=t$ then $x=(t+1)^2$ and so $$g(t)=(t+1)^2-1=t^2+2t$$ Now you can easily find the function $f(x,y)$.
Comment: Oh, Babak, I miss you tonight! I'm doing terribly tonight! Will have to go to bed disappointed with myself :-($\quad$ Perhaps tomorrow will be a fresh, new day for me!
Comment: You can't be online at all, ever? Or now...or tomorrow?
Comment: @amWhy: I can but just for  seconds. Then I get disconnected. Again for some seconds later I come..... till tomorrow I think. It is OK Amy. ;-)
Comment: +1 For taking into account that it is highly suspicious to have a function of two variables without one of the variables playing a role...
Answer: (a)

To find points on $f(x, y)$ that are also on the parabola $y = f(x) = x^2$: Solve for where $f(x, y) = x - y + 1$ and $y = f(x) = x^2$ intersect by putting $f(x, y) = f(x)$:
$$ x^2 = x - y + 1$$ and and express as a value of $y$:

$$y = 1 + x - x^2\;\;\text{ and note}\;\; y = F(x) = f(x, x^2)\tag{1}$$

Note that this function $F(x)$ is precisely $f(x, x^2)$. Find enough points in this equation to plot it. (The points that satisfy $(1)$ will be points on $f(x,y)$ which satisfy $y = x^2$.)  You will find that $\;\;F(x) = 1 + x - x^2\;\;$ is also a parabola. (See image below.) We can manipulate $F(x)$ to learn where the vertex of the parabola is located: write $F(x): (y - \frac 54) = -(x - \frac 12)^2$, so the vertex is located at $(\frac 12, \frac 54)$. The negative sign indicates that the parabola opens downward.

$\quad F(x) = 1 + x - x^2:$

Functions question help me?


Seasonality not taken account of in `auto.arima()`

Question: I am having basically the same issue than in this thread, except one thing:
The difference, in my case, is that my data is measured weekly and not daily, so the argument of a too high seasonality (> 350) does not hold for my data, since the seasonality in my case is 52 (52 weeks in a year).
And yet, when I use auto.arima(), R returns the ARIMA model (p,d,q) = (2,1,1) and (P,D,Q) = (0,0,0), while the seasonal pattern in my data is blatant... How could you explain that R completely dismisses the seasonality in my data?
Since I'm still in a learning phase, I am using the data set cmort available in the astsa library, so everyone here can use the same data as me.
And I have done cmort <- ts(cmort,frequency=52) to be sure that the seasonality in my data is taken account of, but it didn't change anything.
Comment: It has been suggested to close this question as off-topic. I disagree and think there is a genuine statistical question in here.
Comment: There are 365.25/7 weeks in a year, which is not 52. If you have a long time series, taking the frequency as 52 will not yield a satisfactory result. Actually, if you had some 40 years of data (OK, I guess your series is shorter, but think about it anyway), the 52-week seasonality would be off by 1 year. Certainly, that would disturb the results.
Comment: Questions about errors or error messages in R, or questions about how to perform a well-defined operation in R or similar are often better posted [in the R tag at StackOverflow](http://stackoverflow.com/questions/tagged/r). Your question may be migrated there if enough people agree with the close vote. (I disagree and think it's quite on-topic here.) Incidentally, please don't just cross-post your question if you *do* think it's better at SO; instead, click on the little "flag" link and request migration - a moderator will happily assist you.
Comment: 52 "seasons" is a lot, & the seasonality's only blatant because we can see (in @StephanKolassa's plot) a smooth pattern that won't be seen so easily by separately comparing Wk1 for different years, then Wk2 for different years, & so on. You might well get better forecasts over the next year by regressing on a few Fourier terms.
Comment: @Scortchi Does "regressing on a few Fourier terms" mean to perform a linear regression of $x_t$ (my data) on $a_1 \cos(\omega t) + a_2 \cos(2\omega t) +...$ (where $\omega $ is the pulsation, of course) and find the coefficients $a_1$, $a_2$, ... that minimize the mean square error?
Comment: Does this suggestion mean that I'm not on the right community of StackExchange? If then, which community is the proper one to ask questions about R and arima forecasting?
Comment: @R.Bourgeon: Yes: you might still take the first difference of the series, & put in autoregressive & moving average components, so not necessarily an ordinary least-squares fit. That'd be fixed-coefficient regression, but you could also allow the coefficients to vary over time in a dynamic linear model.
Answer: A glance at the manual for auto.arima shows that an explanation of precisely why it found the solution it did in this case would be complicated: depending on the fitting algorithm (conditional least squares by default); on the details of the stepwise selection procedure, & the criteria used (approximate AICc by default); & on the particular configuration & the sequence of the stationarity tests carried out. Nevertheless, I daresay that ARIMA(2,1,1) is a perfectly good model for one-step-ahead forecasts, because the evident smoothness of the seasonality means that knowing the observed value from exactly one year ago will give you little more information about this week's likely value than just knowing the last couple of weeks' observations.
If you want to forecast over the next year or two, you will need to take seasonality into account. Rather than taking seasonal differences, or looking for seasonal autoregressive or moving average terms, or estimating 52 fixed seasonal effects; you might be better off taking advantage of the smoothness & regressing on a few Fourier terms, as explained by @Glen_b here. (This also makes it easy to allow for non-integer frequencies—as @RichardHardy ponts out might be appropriate in this case (if the extra day or two each year weren't simply dropped).) Your model will then have deterministic, but smoothed, seasonal effects, & you can still allow ARIMA errors:
$$
y_t = \alpha + \sum_{i=1}^k \beta_i \sin \left(i \cdot \frac{2 \pi}{\omega}\cdot t\right)
 + \sum_{i=1}^k \gamma_i \cos\left(i \cdot \frac{2 \pi}{\omega} \cdot t \right)
+ \frac{1+\sum_{i=1}^q \theta_i B^i}{(1-B)^d\left(1-\sum_{i=1}^p \phi_i B^i\right)}\cdot\varepsilon_t
$$
$$
\varepsilon\sim\mathrm{WN}(\sigma^2)
$$
The frequency $\omega$ is assumed known. The parameters you need to estimate are: $\alpha$, the intercept; the $\beta$s & $\gamma$s, the coefficients of the sine & cosine terms terms; the $\phi$s & $\theta$'s, the autoregressive & moving average coefficients; & $\sigma^2$, the variance of the white noise innovations. The orders for the $\mathrm{ARIMA}(p,d,q)$ errors & the number of harmonics $k$ can be chosen heuristically or by using significance tests/information criteria.
The forecast package has a function to create the Fourier terms; here's an illustration:
library(astsa)
library(forecast)
# make a training set & test set
window(cmort, start=c(1970,1), end=c(1977,40)) -> cmort.train
window(cmort, start=c(1977,41), end=c(1979,40)) -> cmort.test
# fit non-seasonal & seasonally-differenced models for comparison
Arima(cmort.train, order=c(2,1,1)) -> mod.ns
Arima(cmort.train, seasonal=c(1,1,0), include.drift=T) -> mod.sd
# make predictors
fourier(cmort, K=10) -> fourier.terms
fourier.terms.train <- fourier.terms[1:length(cmort.train),]
fourier.terms.test <- fourier.terms[(length(cmort.train)+1):length(cmort),]
# plot first 5 harmonics
plot(cmort.train, col="grey")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:2])), col="red")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:4])), col="darkorange")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:6])), col="green")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:8])), col="blue")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:10])), col="violet")

Up to the third harmonic seems to be enough, and you still need to difference.
# fit models
Arima(cmort.train, order=c(0,1,0), xreg=(fourier.terms.train[,1:6])) -> mod.ft3.df
acf(residuals(mod.ft3.df), ci.type="ma", lag.max=52)
acf(residuals(mod.ft3.df), type="partial", lag.max=52)
Arima(cmort.train, order=c(2,1,0), xreg=(fourier.terms.train[,1:6])) -> mod.ft3.df.ar2
acf(residuals(mod.ft3.df.ar2), lag.max=52)
acf(residuals(mod.ft3.df.ar2), type="partial", lag.max=52)

Examining correlograms suggests a couple of AR terms will do to leave the residuals looking like white noise. Or you can investigate the number of harmonics to use, as well as the ARMA structure, usng auto.arima:
# auto.arima
auto.arima(cmort.train, xreg=fourier.terms.train[,1:2], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto1
auto.arima(cmort.train, xreg=fourier.terms.train[,1:4], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto2
auto.arima(cmort.train, xreg=fourier.terms.train[,1:6], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto3
auto.arima(cmort.train, xreg=fourier.terms.train[,1:8], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto4
auto.arima(cmort.train, xreg=fourier.terms.train[,1:10], seasonal=F, d=1, allowdrift=T, stepwise=F, approximation=F) -> auto5
auto1
auto2
auto3
auto4
auto5

The ARMA(2,1) structure is found by auto.arima's minimizing the AICc for the model with 4 harmonics on differenced observations, & has the lowest AICc overall.
# look at accuracy on test set
plot(cmort.test, col="grey")
lines(forecast(mod.ns,h=length(cmort.test))$mean, col="red")
lines(forecast(mod.sd,h=length(cmort.test))$mean, col="darkorange")
lines(forecast(mod.ft3.df.ar2,h=length(cmort.test), xreg=fourier.terms.test[,1:6])$mean, col="green")
lines(forecast(auto4,h=length(cmort.test), xreg=fourier.terms.test[,1:8])$mean, col="blue")

accuracy(forecast(mod.ns,h=length(cmort.test)),cmort.test)
accuracy(forecast(mod.sd,h=length(cmort.test)),cmort.test)
accuracy(forecast(mod.ft3.df.ar2,h=length(cmort.test),xreg=fourier.terms.test[,1:6]),cmort.test)
accuracy(forecast(auto4,h=length(cmort.test),xreg=fourier.terms.test[,1:8]),cmort.test)

Summarizing the root mean square errors shows that both the harmonic models perform better on the test set, with little to choose between them:
$$
\begin{array}{l,l,l}
&\text{Training} & \text{Test}\\
\mathrm{ARIMA}(2,1,1) & 5.729 & 7.657\\
\mathrm{SARIMA}(1,1,0)_{52}\text{ with drift} & 6.481 & 7.390\\
\text{3 harmonics, }\mathrm{ARIMA}(2,1,0) & 5.578 & 5.151\\
\text{4 harmonics, }\mathrm{ARIMA}(2,1,1) & 5.219 & 5.188
\end{array}
$$
Comment: You're welcome. (1) I suspect the SARIMA model is unfairly disadvantaged on the test set by its drift - I doubt anyone can really tell whether this series is drifting, trending, or just wandering - but you get the idea. (2) Using several test sets & training sets could give a better idea of the relative out-of-sample performance of the different model-fitting procedures with this series. (3) I'd also like to show how to let the seasonality evolve in a dynamic linear model, but probably won't get around to it / remember how - in any case this series is probably too short to need that.
Comment: I think that you've reached the end of what I can understand, your suggestions outstand my knowledge in this domain (I'm quite a newbie). I'd be glad to understand them, but at least all I can say is that your answer gave me an excellent insight on what "regressing on a few Fourier terms" means in practice. If I understood correctly, `fourier(cmort, K=10)` computes the 10 first Fourier coefficients of the vector `cmort`?
 And your example with the additional argument `xreg` in `arima` made me understand that you regress on other variables in addition of the MA and the AR terms. Thanks.
Comment: Yes, type `forecast:::...fourier` to see the source code. Most of it's concerned with error-checking & other peripheral matters; there's a small loop that makes the sine & cosine terms.
Comment: Most data has some trend. If you run a simple trend model, there is a strong trend.  Even if you take the worst case scenario and just use the last 230 observations the coefficient is negative.
Comment: @TomReilly: Well the local-level model seems to do all right, even without a drift term (stochastic trend). But if I hadn't differenced - yes, I'd've needed to include a (deterministic) trend. Perhaps I'll add a little about the two approaches, but the main point was to demonstrate using Fourier terms to model seasonality. My guess would be that the series isn't long enough to distinguish them & it'd come down to which was thought more appropriate based on subject-matter knowledge. (On the other hand the autocorrelation of the differenced process was very negative at the first lag.)
Answer: (First off, cmort is already a ts object with frequency 52, so you don't need to coerce it.)
I'd say seasonality is visible, not that it is blatant:
library(forecast)
library(astsa)
seasonplot(cmort)

Per the help page (?auto.arima), auto.arima() decides whether or not to take seasonal differences by using a OCSB test. It's quite possible that this test simply got it wrong in this instance; it's a statistical test, after all. You can force a seasonal model by setting D=1, although auto.arima() runs for quite some time with forced seasonality. (Note that the information criteria are not comparable between the original and the differenced series.)
Auto-fitted model:
> auto.arima(cmort)
Series: cmort
ARIMA(2,1,1)

Coefficients:
         ar1     ar2      ma1
      0.0957  0.2515  -0.6435
s.e.  0.4302  0.2444   0.4155

sigma^2 estimated as 33.72:  log likelihood=-1609.89
AIC=3227.77   AICc=3227.85   BIC=3244.68

Model with forced seasonality:
> auto.arima(cmort,D=1)
Series: cmort
ARIMA(0,0,0)(1,1,0)[52] with drift

Coefficients:
         sar1    drift
      -0.5737  -0.0257
s.e.   0.0378   0.0041

sigma^2 estimated as 47.7:  log likelihood=-1537.6
AIC=3081.21   AICc=3081.26   BIC=3093.57

Comment: Yes, that is exactly what it means. Information criteria are calculated as the negative log-likelihood plus a penalty term that depends on the number of parameters. But the log-likelihood of a model applied to the original data and  the log-likelihood of the same model applied to *differenced* data are not comparable at all, since the data may well be on completely different scales. Therefore, information criteria cannot be compared between undifferenced and differenced series, either. Much better to use holdout samples and compare accuracy of models on those.
Comment: No, first we apply the model to the original data (yielding the nonseasonal model), and then we apply the same or a different model to the *seasonally differenced* data (yielding the seasonal model). So we cannot compare two models applied to different data (original vs. seasonally differenced) based on ICs.
Comment: Thanks Stephan, the forecasting looks indeed way better if we coerce the seasonality by forcing $D=1$ !
Comment: Stephan, what do you mean when you write "Note that the information criteria are not comparable between the original and the differenced series." ?
Does it mean that I cannot use the fact that the AIC and the BIC are lower in the second model to state : "the second model is more accurate than the first one?"
Comment: However, here, we are not in the situation of the same model applied to one set of data and then the same model applied to differenced data... I think that the situation is: we have applied two different SARIMA models (first (2,1,1,0,0,0) and then (0,0,0,1,1,0)) to the same set of data `cmort`... Haven't we? So the likelihood is computed from the same dataset, isn't it?
Answer: I say that the seasonality is blatant.
I ran this through Autobox(I am affiliated) and there is also a blatant downward trend in the data and some outliers too.


Extend UITextView height so that it fits all the content inside a JSON string (iOS7)

Question: I have a UITextView inside my Collection View Cell thats linked to a JSON String ("body") that I'm parsing with AFNetworking. The text inside that string varies (each of my "posts" has different information). I want my UITextView to extend based on the content inside my String so that all of the text shows up.
Collection View Cell
@property (weak, nonatomic, readonly) IBOutlet UITextView *body;

View Controller:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";

    PostCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    NSDictionary *newPostDictionary = [self.singlePost objectAtIndex:indexPath.row];

    cell.body.text = [newPostDictionary objectForKey:@"caption"];

    NSLog(@"@");

    return cell;
}

I tried adding this code inside my View Controller but that did nothing.
- (CGFloat)textViewHeightForAttributedText: (NSAttributedString*)text andWidth: (CGFloat)width {
    UITextView *calculationView = [[UITextView alloc] init];
    [calculationView setAttributedText:text];
    CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}

Thanks.
Answer: To get the size of any text, you should use the method of NSString: sizeWithFont:constrainedToSize: you pass as parameters the font and the maximum size can be reached from that text.
CGSize expectedLabelSize = [text sizeWithFont:[UIFont fontWithName:fontName size:fontSize] constrainedToSize:maxSize];

Comment: according to the question, he wants the UITextView to extent, not the content to shrink.
Comment: He want to resize UITextView, with this he obtain the size of the text and can change height of the textview.
Answer: Use sizeWithFont:constrainedToSize: to get size of string
If you're on iOS7 use boundingRectWithSize:options:attributes:context: instead (sizeWithFont:constrainedToSize: is deprecated on iOS7)
Comment: you may try with subclassing `UICollectionViewCell` manually adding your UITextView there, and in `layoutSubviews` method setting that textView frame to result of `boundingRectWithSize:options:attributes:context:` method
Answer: Set UITextView frame to be the same as the content inside it:
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;


Saving date in MongoDB getting offset even when providing time

Question: I'll start by saying I know there are many timezone-related questions and answers out there. Maybe I'm just missing an obvious one.
I'm trying to save a date range pair in Mongo - a from date and a to date. I'd like the from date saved at time 00:00:00:00 so if I run a query looking for >=2017-08-14 all results will show.
My problem is even though I'm sending a date with time 00:00:00.000Z Mongo is actually saving it -400, which appears to be equivalent to EDT offset right now. This leads to me either correcting a lot on the client side, or just showing and querying incorrect data. Once I get the date right, I'd like to just ignore time all together in my queries.
This is the range I'm sending to MongoDB
daterange: [ { from: 2017-08-14T00:00:00.000Z, to: 2017-08-31T00:00:00.000Z } ],

This is how that range is getting stored in Mongo
from: 2017-08-13 20:00:00.000,
to: 2017-08-30 20:00:00.000

What super silly rookie mistake am I making? Thanks for your help.
EDIT: It was a silly mistake. This post helped solve it. Query for a specific date with MongoDB and NodeJS
When I created the date with moment I Should've just done this:
moment(dateString).startOf('day')

Answer: It was a silly mistake. This post helped solve it. Query for a specific date with MongoDB and NodeJS
When I created the date with moment I should've just done this:
moment(dateString).startOf('day');


Show that for $x \in (-\pi, \pi)$ and $T(x) := \sum_{n=0}^\infty(\frac{x}{\pi})^n$ the derivation $T'(x) = \frac{\pi}{(x-\pi)^2}$

Question: $\frac{x}{\pi} < 1$ for $x\in (-\pi, \pi)$, therefore we could use the formula for geometric series to get the limit.
$$\sum_{n = 0}^\infty(\frac{x}{n})^n = \frac{1}{1-\frac{x}{\pi}} = \frac{1}{\frac{\pi}{\pi}-\frac{x}{\pi}} = \frac{1}{\frac{\pi-x}{\pi}} = \frac{\pi}{\pi-x}$$
Now, this doesn't get me any further and im stuck here, so hints would be very much appreciated.
Comment: You need to differentiate...
Answer: You have already proved that, for $x \in (-\pi,\pi)$, by using a geometric series result,
$$
T(x)= \frac{\pi}{\pi-x}
$$ then to obtain $T'(x)$ just use
$$
\left(\frac 1u\right)'=-\frac{u'}{u^2}.
$$


Prove that there is only one $y=h(x)$ so that $y+x^2y^3+x+y^5x^4=1$

Question: Prove that $\forall x\in \mathbb{R}$ there is only one $y=h(x)$ so that
$$y+x^2y^3+x+y^5x^4=1$$
I am currenty studying multi-variable calculus on my own and I have no clue how to solve this problem. Which results of multi-variable calculus do I have to study to solve it? I would appreciate if someone could solve it or share similiar problems to this one.
Comment: @dxiv sorry, I meant $\mathbb{R}$. Edited.
Answer: $\,x = 0 \implies y=1\,$ i.e. $\,h(0)=1\,$. For $\,x \ne 0\,$, let $\,z=xy\,$, then multiply by $\,x\,$, and write it as:
$$
z^5+z^3+z = x - x^2
$$
The LHS $\,f(z)=z^5+z^3+z\,$ is continuous and strictly increasing on $\,\mathbb{R}\,$, and since the limits at $\,\pm \infty\,$ are $\,\pm\infty\,$ respectively, it follows that $\,f : \mathbb{R} \to \mathbb{R}\,$ is a bijection. Then the unique solution of the equation is $\displaystyle\,z = f^{-1}(x-x^2) \iff y = \frac{f^{-1}(x-x^2)}{x} = h(x)\,$.

[ EDIT ]   Following up on the comments, such problems would be solved in the general case using the implicit function theorem. Here in particular $\,f(x,y) = y^5x^4+y^3x^2+y+x-1\,$, and $\displaystyle\,\frac{\partial{f}}{\partial{y}}(x,y)=5y^4x^4+3y^2x^2+1 \ge 1\,$ is never $\,0\,$, so the map $\,y=h(x)\,$ is defined at all points.
Comment: @codingnight In the general case, you would look at the [implicit function theorem](https://en.wikipedia.org/wiki/Implicit_function_theorem#Statement_of_the_theorem). I'll add a note to the answer about that. However, given the particular form of the equation here, my guess is that it was meant to be solved using a shortcut such as the one above, rather than the full weight of the implicit function theorem. The clue for me was that all terms in $\,y\,$ contained a power of $\,x\,$ exactly one less.
Comment: @IntegrateThis See my previous comment, and the edit added at the end.
Comment: Wow. This is an amazing answer, but I suspect like the OP I would never have come to an answer like this. If you have time, can you give some insight about what you noticed apriori that allowed you to devise this solution?
Comment: Yes please, what should I be looking for when solving this problems?


Control content access based on field value in user profile?

Question: I have two specific user types on my website: "Manager" and "Employee". I will have ten managers and 100 employees. Each Manager will manage 10 employees.
Employees will have permissions to create "Content Type A" nodes. I want their managers to be able to edit/view only those "Content Type A" nodes that were created by their employees.
I created a User Reference field in the profile form. that UR field is populated only with the names of the Managers. When a new employee is registered their manager's name will be selected from that UR field.
I feel like I should be able to control each Manager's access to Employee-created content based on that UR value in each employee's profile, but I can't quite wrap my head around how to accomplish that. Would Views be the best bet, or would I need to develop a custom permissions module that compares the logged-in Manager's UID with the UID related to the Manager selected in the UR field on the employee profile? Or perhaps some kind of Rules setup?
Thanks!
Answer: User Relationships module seems to be the answer:

User Relationship Node Access lets users control access to their content based on relationships
Comment: thanks for your input. It appears that the User Relationships module may be just what I am looking for. I will post back here with my method if it does indeed work out. Thanks!


Are semantics and syntax the same?

Question: What is the difference in meaning between 'semantics' and 'syntax'?  What are they?
Also, what's the difference between things like "semantic website vs. normal website", "semantic social networking vs. normal social networking" etc.
Comment: @John: I asked you to change the syntax of your question -- spelling, word use, etc.  The meaning of your question -- the semantics -- did not change.  Everyone's understanding of your meaning stayed the same.  The spelling of the words was the only change.
Comment: "ARE semantics and syntax the same things?" Two nouns. Plural verb form.  Plural pronouns.  Parallel structure.
Comment: That was syntax.  Semantics didn't change, did it?
Comment: i still don't get it, explain?
Answer: Syntax is the grammar. It describes the way to construct a correct sentence. For example, this water is triangular is syntactically correct.
Semantics relates to the meaning. this water is triangular does not mean anything, though the grammar is ok.
Talking about the semantic web has become trendy recently. The idea is to enhance the markup (structural with HTML) with additional data so computer could make sense of the web pages more easily.
Comment: And in HTML specifically, the "semantic web" is the idea that your HTML code should carry meaning. Don't use a table if you aren't actually showing tabular data. Use the tags that best explain the *meaning* of your document, not the ones that makes it look the way you want. That's what CSS is for.
Comment: thanks!  everyone else gave good answers too, but yours made the most sense to me
Comment: Semantic is about the bugs in the implementation logic. Right ?
Answer: Syntax is the grammar of a language - the rules by which to form sentences or expressions.
Semantics is the meaning you are trying to express with your code.
Comment: Isn't that "semantics is the meaning you're expressing with your code"? A programmer might be _trying_ to express something but not getting it right... what s/he is trying is in his/her head essentially.
Answer: A program that is syntactically correct will compile and run.
A program that is semantically correct will actually do what you as the programmer intended it to do. i.e. it doesn't have any bugs in it.
Two programs written to perform the same task in different languages will use different syntaxes, but they would be the same semantically.
Comment: Sorry for nitpicking, but "semantically they could be the same." or "would be the same" ?
Comment: > "Two programs written to perform the same task in different languages will use different syntaxes, but they would be the same semantically." . The algorithms could be different right ? Even if the algorithm is same the program written in "c++" will have a different number and order of instructions than a program written in "c" . So the semantics vary . Is this correct ?
Answer: If you are talking about web (rather than programming languages):
The syntax of the language is whatever the browser (or processing program) can legally recognize and handle, and render to you. For example, your browser can render HTML, while your API can parse XML trees.
Semantics involve what is actually being represented. There's a lot of buzz now about semantic webs and all that stuff, but it essentially means that each entity is also associated with some human-readable information or metadata, so that a certain tag would have a supposed meaning and refer you to it.
Social networks are the same story. You put knowledge in the links
Comment: thanks i like your answer too, I wish i could select TWO accepted answers
Answer: "An ant ate an aunt." has a correct syntax, but will not make sense semantically. A syntax is a set of rules that can be combined to produce infinite number of gramatically valid sentences, but few, very few of which has a semantics.
Answer: Syntax is the word order of a sentence. In English it would be the subject-verb-object form.
Semantic is the meaning behind words. E.g: she ate a saw. The word saw doesn't match according to the meaning of the sentence. but it is grammatically correct. so its syntax is correct. =)
Answer: Specifically, semantic social networking means embedding the actual social relationships within the page markup. The standard format for doing this as defined by microformats is XFN, XHTML Friends Network. In regards to the semantic web in general, microformats should be the go-to guide for defining embedded semantic content.
Answer: Semantic web sites use the concept of the semantic web, which aims to bring meaning to web content by using special annotations to identify certain concepts in a page. This makes possible the automatic (by a computer, not a human) reasoning about the content, which improves its aggregation, extraction, indexing and searching.
Answer: Explanations above are vague on the semantics side, semantics could mean the different elements at disposition to build arguments of value(these being comprehensible, to end-user man and digestible to the machine).
Of course this puts semantics and the programmer-editor-writer-communicator in the middle: he decides on the semantics that should be ideally defined to his public, comprehended by his public, general convention by his public and digestible to the machine-computer. Semantics should be agreed upon, are conceptual, must be implementable to both sides.
Say footnotes, inline and block-quotes, titles and on and on to end up into a well-defined and finite list. Mediawiki, wikitext as an example fails in that perspective, defining syntax for elements of semantic meaning left undefined, no finite list agreed upon. "meaning by form" as additional of what a title as an example again carries as textual content. Example "This is a title" becomes only semantics integrated by the supposition within agreed upon semantics, and there can be more then one set of say "This is important and will be detailed"
Asciidoc and pandoc markup is quite different in it's semantics, regardless of how each translates this by convention of syntax to output formats.
Programming, output formats as html, pdf, epub can have consequentially meaning by form, by semantics, the syntax having disappeared as a temporary tool of translation, and as one more consequence thus the output can be scanned robotically for meaning, the champ of algorithms of 'grep': Google. Looking for the meaning of "what" in "What is it that is looked for" based upon whether a title or a footnote, or a link is considered.
Semantics, and there can be more then one layer, even the textual message carries (Chomsky) semantics thus could be translated as meaning by form, creating functional differences to anything else in the output chain, including a human being, the reader.
As a conclusion, programmers and academics should be integrated, no academic should be without knowledge of his tools, as any bread and butter carpenter. Programmers should be academics in the sense that the other end of the bridging they accomplish is the end user, the bridge... much so: semantics.
m.

Are semantics and syntax the same?


Install and enable 'Real AES' module: Dependency with Defuse PHP-encryption library

Question: I downloaded the real_aes-8.x-2.2.zip file from the Real AES project page, unzipped and copied it to contrib module folder (/var/www/html/modules/contrib).
While trying to enable this module using drush en real_aes, I get below error:

Module real_aes doesn't meet the requirements to be enabled.                                                        [error]
Please install the Defuse PHP-encryption library via Composer. See README.txt (Currently using Defuse PHP-Encryption[error]
library version Not Installed)

So now I ran the command composer require defuse/php-encryption to install Defuse PHP-encryption. I could see that it is downloaded to the location /var/www/html/vendor.
After this, even though the Defuse PHP-encryption is downloaded, if I try to enable the Real AES module using Drush command and also tried Drupal module interface, it still throws the above error.

Drupal version: 8.6.5
PHP Version : 7.0.32
Drush version: 8.1.18

Any help appreciated resolving this issue.
Comment: So your site is managed with Composer? Then you `composer require drupal/real_aes` and it will also get you the library. Otherwise ensure you download the correct version of the library `composer require defuse/php-encryption:^2.2`. Flush cache and retry. Next thing: your Drush version is incompatible with Drupal 8, fix that. Next thing: Your Drupal version is out of date, fix that, too.
Comment: You need to execute `composer require defuse/php-encryption` in the correct directory, in order to let Drupal find the library. Then, since you used Composer to add the library, you could as well add the module with `composer require drupal/real_aes` as @leymannx said.
Answer: Founded solution:

Download Ludwig - https://www.drupal.org/project/ludwig
Install module and go to admin/reports/packages - https://www.drupal.org/docs/contributed-modules/ludwig/installation-and-usage
Install automatically or add manually to folders:

modules/address/lib/doctrine-collections/1.8.0
modules/address/lib/doctrine-deprecations/v1.0.0
modules/address/lib/commerceguys-addressing/v1.4.2
modules/commerce/lib/commerceguys-intl/v2.0.1

Next clear the cache - admin/config/development/performance

Now u can install all modules :)
Comment: Welcome to Drupal Answers! The OP was not trying to install the Commerce module, so this answer does not really answer the question.


Reescrever URL no .htaccess para site com perfil

Question: Tudo bem?
Estou fazendo uma plataforma em PHP com perfil público. Precisaria que meu arquivo single.php fosse reescrito na URL sempre que alguém acesse por exemplo: meusite.com/fillipe ou meusite.com/luis.
Preciso pegar por GET toda informação depois da barra e reescrever na página toda vez que alguém acessar um perfil público diferente.
Alguém manja?
Comment: Provavelmente alguém manda, mas seria bom vc compartilhar conosco o que você já tentou fazer para que possamos te ajudar :)
Answer: Então, você precisa adicionar o trecho abaixo no seu .htaccess, lembre-se de substituir o nome do arquivo e o nome do parâmetro. Faça um backup do arquivo .htaccess original, para caso der algum erro você tem como reverter.
Pesquise no google "URL amigáveis php htaccess" terá bastante vídeos e tutorias na internet.
<code>RewriteRule ^([a-z]+)\/?$ perfi.php?idPerfil=$1 [NC,L]
</code>


Angular material - Affix

Question: I'm using angular 4 with angular material 2.0.0-beta.12.
I want to achieve something that's called "affix~" on angular material website
I need to build something like this image:

that, while scrolling, these items will be "active" if the content is beeing seen on the page. Each item will have an anchor as well.
Anyone knows an easy and clean way to do it?
Thank you in advance for your time.
Comment: It's called a table of contents. For more info, see the source code for `` here: https://github.com/angular/material.angular.io/blob/b029f9108d4c89ce4dd75cffaaf4ea9d365dcc70/src/app/shared/table-of-contents/table-of-contents.ts and https://github.com/angular/material.angular.io/blob/7d0297bb64f70625b5117d999839acb14143087f/src/app/shared/table-of-contents/table-of-contents.html. It also uses `position: sticky` to make it "stick".
Comment: The Angular Material website is on Github. You can just look at its code.
Answer: If you need to create from scratch you can follow the tutorial:
https://oliverveits.wordpress.com/2017/07/18/angular-4-automatic-table-of-contents/
It explains how to create a two-level automatic Table of Contents. You can clone the code by doing the following:
# git clone https://github.com/oveits/ng-universal-demo
# cd ng-universal-demo
# git checkout 8ca27d5   # to be sure you are working with exact same that has been created in this blog

Also you can use the material angular table of contents https://github.com/angular/material.angular.io/blob/b029f9108d4c89ce4dd75cffaaf4ea9d365dcc70/src/app/shared/table-of-contents
Answer: The Solution is divided into three parts:
1. The rightmost menu which changes on scrolling. Those are links when clicked point to that position on the same page.
Nested List

Now you create the actual link. Nested List in this example.
Nested List with details

Now for highlighting the text using css or angular you can check if the div is present in the browser window. Then just highlight whichever you find first starting from the top.

Note: Name and Href have a difference of only 1 char # (pound). This is a necessity.

Angular material - Affix


Não estou conseguindo inserir submenus no menu Dropdown

Question: Problema: Não estou conseguindo criar um menu dropdown com submenus.
Ex: Quando clicar no perfil a esquerda vai abrir um menu do drop a ideia seria quando clicasse no configurações abrisse novas opções.
O que eu espero?
Quando o usuário clicar na opção de configurações, abrisse novas opções para o mesmo.
Código HTML:

                        @User.Identity.GetClaim("Nome")

                        Configurações
                        More options

1

1

1

                        <form action="@Url.Action("Logout", "Account")" id="signoutForm" method="post" novalidate="novalidate">
                            @Html.AntiForgeryToken()
                            Sair
                        </form>

Imagem de como ficou:

Imagem de como gostaria que ficasse:
Answer: Olha aqui tem um modelo, fiz baseado nesse script, e usando a navbar default do Bootstrap 3. Mas basicamente vc cria um novo link dentro do menu que vau fazer o pale de ativar o sub-menu mostrando a próxima UL caso seja clicado.
$(document).ready(function() {
    $('.dropdown-submenu a.test').on("click", function(e) {
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
    });
});

Segue o código da imagem acima

<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>
                Brand

Link (current)

Link

                        Dropdown

Action

Another action

Something else here

Separated link

One more separated link

                            Tutorials

HTML

CSS

                                    Novo Drop

2nd level

2nd level

                                            Outro dropdown

3rd level

3rd level

            resto do conteúdo


I'm trying to access my model but instead of the Html class I want to do it with a html5 input

Question:  @Html.EditorFor(m => m.FirstName, new { @id = "fnTxtBox" })

Is there a way to access the model like above but using this instead?
    <input type="text"/>

I can't seem to find a way to direct the input to a target property and thus bind it...
Thanks!
Comment: Just add the `name` attribute to match the property name `` (but why would forego all the benefits that html helpers give you?)
Comment: it worked thanks a lot! its for educational purposes :P
Answer: Isn't that just
<input type="text" id="fnTxtBox" name="fnTxtBox" value="@Model.FirstName"/>

But then you would need a fnTxtBox parameter on your POST method, instead of a model-type with a FirstName property.
EDIT
Or if the Model might be null:
<input type="text" id="fnTxtBox" name="fnTxtBox"
                  value="@(Model == null ? "" : Model.FirstName)"/>

And if the Model never exists, you can leave out that value entirely.
Comment: @David I extended my answer


How do I update the CKEditor text widget using CKEditor API

Question: I am using Drupal 8's Ajax API to update form fields in a form depending on the input in another field. One of the fields I want to update is a text_format field that uses Drupal's ckeditor.
If I understand the CKEditor API correctly, I should be able to update the text in the ckeditor widget using the setData() method (https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-setData). The ckeditor instance should be the textarea id - and that I can easily identify in my AjaxResponse function.
However, I am not sure how to use Drupal's invokeCommand() to make use of the CKEditor API?
Answer: In the end I was able to solve this using a custom Ajax command:

In our custom module (called b47_custom_authors) we created a custom ajax command in src/Ajax/B47CustomAjax.php
/**
 * @file
 * Contains \Drupal\b47_custom_authors\Ajax\B47CustomAjax.
 */

namespace Drupal\b47_custom_authors\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class B47CustomAjax implements CommandInterface
{

  /**
   * A CSS selector string.
   *
   * If the command is a response to a request from an #ajax form element then
   * this value can be NULL.
   *
   * @var string
   */
  protected $selector;

  /**
   * An optional list of arguments to pass to the method.
   *
   * @var array
   */
  protected $arguments;

  /**
   * Constructs an b47customajax object.
   *
   * @param string $selector
   *   A jQuery selector.
   * @param array $arguments
   *   An optional array of arguments to pass to the method.
   */
  public function __construct($selector, array $arguments = []) {
    $this->selector = $selector;
    $this->arguments = $arguments;
  }

  public function render(){
    return [
      'command' => 'b47customajax',
      'selector' => $this->selector,
      'args' => $this->arguments,
    ];
  }
}

The custom js (in js/b47customajax.js) is as follows:
Drupal.AjaxCommands.prototype.b47customajax = function (ajax, response) {

// response is an array with the keys
// response.command: the command called (b47customajax)
// response.selector: the selector to be used (NULL)
// response.args: the arguments to be passed as an array: 0: the ckeditor instance, 1: the text (data) to be passed

var ajaxckeditorinstance = response.args[0];
var ajaxckeditordata = response.args[1];
var editor;

var instance = CKEDITOR.instances[ajaxckeditorinstance];

if (instance) {
   // Trying to call setData method: https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-setData
   editor = instance.setData( ajaxckeditordata , {
          callback: function() {
                      this.checkDirty(); // true
                  }
          });

};

};
In my ajax callback function I call my custom ajax via:

$response->addCommand(new \Drupal\b47_custom_authors\Ajax\B47CustomAjax('textarea'.$fieldid,[$fieldid, $texttobeinserted]));
The $fieldid is the id of the textarea, and @texttobeinserted is the full html of the text I want in ckeditor.
This now allows me to update the ckeditor based on the text dynamically via my AjaxResponse. The textfield is hidden by default and depending on the input in another field I fetch the text that needs to be placed in the textarea/ckeditor. The form field is then also displayed.
This now works.


Error in plot.xy(xy, type, ...) : invalid color name 'A'

Question: I am working on a paper writing exercise and was provided the following R code to use analyze a given data set. It has worked perfectly until I reach this last step and then I receive this error and I'm not sure how/where I need to redefine the color as I need the scatter plot to be two different colors for the groups. Its the very last line that doesnt produce the needed graph. Thanks for the help.
dat<-read.table("F:/University/NSU_TEACHING/NEW_CORES/NEW_MARINE
GEOLOGY/NEW_MODULES_2015_7/Online_data/SANDS2.txt", header=F)

par(mfrow=c(1,2))
plot(dat$V2,col="blue",main="Median grain size" )
plot(dat$V3,col="red",main="Sorting Coefficient")
boxplot(dat$V2~dat$V1,main="Median grain size" )
boxplot(dat$V3~dat$V1,main="Sorting Coefficient")

hist(dat$V2,main="Median grain size")
hist(dat$V3,main="Sorting Coefficient")
hist(dat$V2,main="Median grain size",breaks=20)

qqnorm(dat$V2,main="Median Grain Size"); qqline(dat$V2)
qqnorm(dat$V3,main="Sorting Coefficient"); qqline(dat$V3)

shapiro.test(dat$V2)
shapiro.test(dat$V3)

ks.test(dat$V2[dat$V1=="A"],dat$V2[dat$V1=="B"])
hist(dat$V2[dat$V1=="A"])

hist(dat$V2[dat$V1=="B"])
fligner.test(dat$V2~dat$V1)

t.test(dat$V2~dat$V1)
boxplot(dat$V2~dat$V1,notch=T,main="Median grain size" )

plot(dat[,c(2,3)],col=dat[,1])

Data set if needed
#Group A = Beach sands, Group B = Offshore sands, Column 2 = Median grain size in mm., Column 3 = Sorting coefficient

A   0.333   1.08
A   0.340   1.08
A   0.338   1.09
A   0.333   1.10
A   0.323   1.13
A   0.327   1.12
A   0.329   1.13
A   0.331   1.13
A   0.336   1.12
A   0.333   1.14
A   0.341   1.14
A   0.328   1.15
A   0.336   1.15
A   0.327   1.16
A   0.329   1.16
A   0.330   1.16
A   0.323   1.17
A   0.328   1.17
A   0.332   1.17
A   0.331   1.18
A   0.326   1.18
A   0.333   1.18
A   0.330   1.19
A   0.336   1.19
A   0.327   1.20
A   0.324   1.21
A   0.332   1.21
A   0.322   1.22
A   0.329   1.22
A   0.325   1.24
A   0.328   1.26
A   0.322   1.27
A   0.318   1.22
A   0.330   1.17
B   0.339   1.12
B   0.346   1.12
B   0.350   1.12
B   0.352   1.13
B   0.341   1.15
B   0.347   1.15
B   0.337   1.16
B   0.343   1.16
B   0.340   1.17
B   0.346   1.17
B   0.349   1.17
B   0.339   1.18
B   0.342   1.18
B   0.346   1.18
B   0.351   1.18
B   0.340   1.19
B   0.344   1.19
B   0.333   1.20
B   0.337   1.20
B   0.339   1.20
B   0.342   1.20
B   0.339   1.21
B   0.340   1.21
B   0.341   1.21
B   0.335   1.22
B   0.337   1.22
B   0.340   1.22
B   0.343   1.22
B   0.334   1.22
B   0.348   1.22
B   0.337   1.22
B   0.342   1.23
B   0.334   1.24
B   0.340   1.24
B   0.342   1.24
B   0.331   1.25
B   0.336   1.25
B   0.341   1.25
B   0.334   1.26
B   0.337   1.27
B   0.339   1.27
B   0.330   1.28
B   0.334   1.28
B   0.332   1.29
B   0.330   1.31
B   0.334   1.31
B   0.340   1.21

Comment: I suspect this is a [stringsAsFactors=FALSE](https://developer.r-project.org/Blog/public/2020/02/16/stringsasfactors/) problem. If the guide was written for R 3.0 and you're using R 4.0 or higher, the encoding of that column will be different. Try adding `stringsAsFactors = TRUE` to your original `read.table` call, or change the last line to `plot(dat[,c(2,3)],col=factor(dat[,1]))`
Answer: From comments:
I suspect this is a stringsAsFactors=FALSE problem. If the guide was written for R 3.0 and you're using R 4.0 or higher, the encoding of that column will be different. Try adding stringsAsFactors = TRUE to your original read.table call, or change the last line to plot(dat[,c(2,3)],col=factor(dat[,1]))


Change TPL file based on taxonomy term

Question: I would like to change the tpl.php file used depending on the taxonomy term applied to a node.
There is a snippet on this page that explains how to do that. However, it is written for Drupal 6, and doesn't work for Drupal 7.
The snippet is as follows:
// Add this to your theme's template.php
// Replace "THEMENAME" with your theme's name
function THEMENAME_preprocess_node(&$vars) {
  foreach ($vars['node']->taxonomy as $term) {
    $vars['template_files'][] = 'node-term-'. $term->tid;
  }
}

I have tried to update it for Drupal 7 as follows:
function THEMENAME_preprocess_node(&$variables) {
  foreach ($variables['node']->taxonomy as $term) {
    $variables['template_files'][] = 'node-term-'. $term->tid;
  }
}

However, it still doesn't work. I just get the following error message:

Notice: Undefined property: stdClass::$taxonomy in
  THEMENAME_preprocess_node()  Warning: Invalid argument supplied for
  foreach() in THEMENAME_preprocess_node()

Any help would be appreciated.
Answer: You could probably handle it with the following code:
function mytheme_preprocess_node(&$variables) {
  if (isset($variables['node']->field_myfield[$variables['node']->language][0]['tid'])) {
    $tid = $variables['node']->field_myfield[$variables['node']->language][0]['tid'];
    $variables['theme_hook_suggestions'][] = 'node__term_'. $tid;
  }
}

Now if a term with the id 6 would be referenced from a node's 'field_myfield' Drupal would look for a template named 'node--term_6.tpl.php' and use that if available.
Answer: Here you can find everything you need to know about template suggestion in D7.
I think in your case, the template should look like page--taxonomy--term--1.tpl.php. No need for preprocess functions.
Comment: Thanks! But page--taxonomy--term--1.tpl.php changes the page.tpl.php file. I want to change the node.tpl.php file. How can I do that (The page you linked to doesn't explain it).
Answer: Try this instead:
function THEMENAME_preprocess_node(&$variables) {
  foreach ($variables['node']->taxonomy as $term) {
    $variables['theme_hook_suggestions'][] = 'node-term-'. $term->tid;
  }
}

Comment: Hi - Thanks! That code produces an error message. (It's the same error message as listed in my opening post).   Thanks for taking the time to help!
Comment: you should var_dump the `$variables['node']` and see the exact structure of the variable. I think in D7 the node structure is changed regarding the taxonomy. Locate the taxonomy related part in `$variables['node']` and make the necessary adjustments
Comment: How do I do that? Also what would I look for to make the necessary adjustments?
Comment: put this before `foreach(...` and tell me what it'll show up: `drupal_set_message('' . print_r($variables['node'], true) . '');`

Change TPL file based on taxonomy term


Extend jQuery's .val() method to non-input elements

Question: I am writing a custom jquery plugin that basically replicates the functionality of an input. I could explain why, but truthfully the explanation is quite long and I believe it to be irrelevant to the question.
The trouble comes when I try to extend jQuery's .val() method to my custom jquery plugin. Here is what I've tried:
$.fn.custom_text_input = function(options){
    return this.each(function(){
        var custom_text_input = new CustomTextInput(options, this)

        $(this)[0].val = function(){
            alert('something useful')
        }
    })
}

Ive tried a few other variations of this, all to no avail. If anyone has any ideas that will work, I would very much appreciate the wisdom!
Thanks!
Comment: BTW, `$(this)[0]` is the same as `this`. When you create a jQuery object, there is a zero-index array of DOM elements in that jQuery object. So when you access the first index (zero) you get the first element.
Comment: thanks. I tried both, but that's helpful for the future
Comment: Shouldn't the function definition go in your CustomTextInput definition?
Comment: I want to be able to call it from anywhere by using a jquery selector. example: $('#div').custom_text_input() and then somewhere else in my code $('#div').val()
Comment: the problem is i don't want to overwrite the original .val() method that applies to inputs. I really just want to write it to the elements that belong to my plugin
Answer: To overwrite the $.val() method you need to do something like $.fn.val = function () {...}. Here is a demo: http://jsfiddle.net/CRRP5. I would recommend saving the old .val() method in a variable so you can use it when .val() is called on a regular form input.
Comment: @FredGarbutt That's what I meant by the last sentence in my answer. Save the old `.val()` function to a variable and call it when your `.val()` function is called on a form input. You'll need to check the type of HTML element, and if its a form input then return the response from the original `.val()` function, otherwise return the response from your custom one. And yes, this overwrites the standard jQuery `.val()`.
Comment: Won't that overwrite the original .val() for all elements? I'm trying to avoid that unless there is no other way. Perhaps there is a way to call jquery's .val() method from within my custom .val() method if the element is not part of my plugin?
Comment: @FredGarbutt An alternative could be to return a jQuery object from your `custom_text_input` method with an updated `.val()` method. That way you'd only overwrite the `.val()` method for that single jQuery object. This would be something like, `var $this = $(this); $this.val = function () {...}`. You'd have to save the returned jQuery object as a variable so it's accessible in the future, because recreating a jQuery object by selecting the DOM node would use the global `.val()` method that you didn't update. This is untested, just came to mind.
Answer: The only way you're going to get this to work is by extending the result of jQuery's val() method.
$(function(){
  $.fn.oldVal = $.fn.val
  $.fn.val = function(value){
    //I'm assuming here that you're setting/getting a data value
    //on the object to keep track of it's "custom value"
    if(value && $(this).data('custom-input-value')){
       return $(this).data('custom-input-value', value);
    }
    else if(value = $(this).data('custom-input-value')){
      return value;
    }else{
      return value ? $(this).oldVal(value) : $(this).oldVal();
    }
  }

})

That might work for you :p
Here's a jsfiddle with it working:  http://jsfiddle.net/Z4c6d/
Comment: this is exactly what i needed! it is also what jasper was already telling me to do before though. Technically you both are saying the same thing. thanks for the clear responses!
Comment: I updated the code to work properly...and included a functioning jsfiddle.
Comment: I found an issue with the code in the jsfiddle if you try to set the value of both inputs - the code short circuits when setting via oldVal. I made an update that behaves properly in that case: http://jsfiddle.net/Z4c6d/1/


Calculate decimal exponent without nth root or logarithms

Question: I have programmed a BigDecimal class and am working on a Pow method. I am stuck on doing decimal exponents as it requires you to have a nth root method, which further requires you to have logarithms, which further requires you to have a Pow method, and it goes in a circle. What is a way to calculate a decimal exponent without going in this circle
Comment: You can precisely calculate logarithms (or nth roots directly) by Taylor series or different polynomial approximations, taking as many terms as needed.
Comment: See [this](https://rosettacode.org/wiki/Nth_root) article on Rosetta code. Also, you can use the [shifting nth root algorithm](https://en.wikipedia.org/wiki/Shifting_nth_root_algorithm)
Comment: Meta-cheating, there has to be a way out of the catch-22 cycle that you describe, otherwise no modern math oriented software could work.  So intuitively, it makes sense that the escape clause is to calculate logarithms or nth roots by other means.
Comment: @JoshuaWang Is there an article on either of those methods?
Answer: This is my first answer, I am open to feedback on how to do this better.
I learned yesterday that fractions, decimals, and improper fractions work like regular multiplication and division with a twist. In the case of an exponent (2/3) we are cutting the base into three equal pieces that if multiplied together will equal the base. The second thing is that we multiply back in 2 pieces of the base. For example:
2^0.5 or 2^1/2 is one square-root
2^1.5 or 3/2 is square-rooted, and then it takes those square roots and multiplies them by themselves 3 times. This helps when doing awkward decimals.
2^0.37 would be cut into 100 equal multipliers, and then "adding" back in the 37 pieces that are there.
I don't think I have the correct notation, but I would use (37the 100th root)numeral, as the 100th root would act more like bx +c situation but with multiplication.
For something more complicated like 12^x = 24^y
(32^2)^x = (32^3)^y
I think we can drop the *3 momentarily to focus on the similar parts
(2^2)^x = (2^3)^y
When I made the equation 4 = (2^3)^y that y was = 2/3
and also inverse for x = 3/2, I was looking for a cleaner way to deal with these without using log until the last minute, if at all.
Let me know if you have questions about my explanation, I am not comfortable with English.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: In computer programming, I would set a variable for the nth root, and make it a math variable like x, y, z or something so the program can compute the rest of the equation and leave the ugly roots for last.


Regression response and explanatory variables

Question: I am a newbie to regression, and I was trying to answer the following question using this data.

Is there a meaningful difference between the distribution of damage
  caused by hurricanes with female names and the distribution of damage
  caused by hurricanes with male names?

This link says,

The response variable is the focus of a question in a study or experiment. An explanatory variable is one that explains changes in that variable.

By using the definition, gender affects the distribution of damage caused by hurricanes, and it's the explanatory variable. Am I right?
By considering gender as an explanatory variable, does GAM regression give a good fit?
set.seed(100)
library(mgcv)
library(rio)
url = "https://www.pnas.org/highwire/filestream/616321/field_highwire_adjunct_files/0/pnas.1402786111.sd01.xlsx"
data = rio::import(url)
data = data[1:92,]
log.reg = gam(NDAM ~ Gender_MF, data = data)

Comment: It seems to me that there may be some confusion in terms.  I do not agree that the term "explanatory variable" is defined as "one that explains changes in that variable."  In regression analysis, there is no need to have an explanatory varible that explains the change in a variable.  An explanatory variable in this context is simply variable (on the RHS of a regression equation) that is *thought* to explain some of the variability in the response variable.  There needs to be no causal effect of the explanatory variable.  Regression is often carried out to ...
Comment: You should consider using a logistic regression when the outcome (dependent, left-hand-side, etc.) variable is binary. When the regressor (right-hand-side variable, explanatory variable, etc.) is binary you can do linear regression.

 `lin.model <- lm(NDAM ~ Gender_MF, data = data)`

Yours is the latter case, so logistic regression is unnecessary.
Comment: @doubletrouble I appreciate your explanation. My confusion is on the question, "Is there a meaningful difference between the distribution of damage caused by hurricanes with female names and the distribution of damage caused by hurricanes with male names?". From the question, gender is an explanatory variable. Is that right?
Comment: I've addressed your first question below, but your second question is unclear. Logistic regression would be an *appropriate* way to analyse the data if `gender` was the response variable, but what you do mean by 'give the best fit'?
Comment: (continued) determine if an explanatory variable does in fact have account for some of the variability seen in the response variable.
Answer: You are correct: gender would be an explanatory variable (or predictor/independent variable) in this case.
However, you should be aware that the paper you are presumably basing this on has received an extraordinary amount of criticism for poor analysis. For e.g.
https://www.washingtonpost.com/news/monkey-cage/wp/2014/06/05/hurricanes-vs-himmicanes/?noredirect=on&utm_term=.81faaced2590
https://scatter.wordpress.com/2014/06/03/my-thoughts-on-that-hurricane-study/
https://scatter.wordpress.com/2014/06/10/the-hurricane-name-study-gets-worse/
https://www.sciencedirect.com/science/article/pii/S2212094715300517
http://rpubs.com/oharar/19171
Not to mention 4 published responses to the paper itself: https://www.pnas.org/content/early/2014/05/29/1402786111


parallelogram law

Question: I'm need a little help here :
using the parallelogram law: $$ 2||u||^2 + 2||v||^2 = ||u + v||^2 + ||u - v||^2 $$
I'm need to show that the next norm can not be satisfy by inner product:
The norm $||A|| = sup||Av||_\mathbb{R^2}$ that defined all over the real matrixes  2 x 2 when the norm $|| . ||_\mathbb{R^2}$ is the standard norm over $\mathbb{R^2} ( ||v||_\mathbb{R^2}=\sqrt{v_1^2+v_2^2}) $ and the supermum is taken over all the vectors $ v \in \mathbb{R^2} $ that satisfy $||v||_\mathbb{R^2}=1$
I think that the good way to prove it ,is by finding example that break this law.
but my problem is that  I'm even can't understand the norm and how it function.
Thanks in advance
Answer: This norm is called the operator norm and is extremely useful. Since $A$ is a linear map, the following definition is equivalent: $\| A \| = \sup \left\{ \frac{\| Av \|}{\| v \|} : v \not= 0 \right\}$, so you can think of it as "the largest amount $A$ lengthens a vector by".
It has the property that $\| Av \|_{\mathbb R^2} \le \| A \| \| v \|_{\mathbb R^2}$, and it's the maximal value such that that inequality always holds: from this you can prove that for any matrices $A$ and $B$, $\| ABv \|_{\mathbb R^2} \le \| A \| \| Bv \|_{\mathbb R^2} \le \| A \| \| B \| \| v \|_{\mathbb R^2}$, so $\| AB \| \le \| A \| \| B \|$, so the norm plays nicely with matrix multiplication.
To get a feel for how this works, perhaps try going through the proof that it is a norm:

$\| A \| \ge 0$: this is obvious, since it is a supremum over a set of positive numbers.
$\| A \| = 0 \implies A = 0$: well, if $A$ ever has $Av \not= 0$, then $\| Av \| > 0$, so the supremum will be strictly positive.
$\| \lambda A \| = |\lambda| \| A \|$: this follows from the same property for the vector norm, and from the fact that $\sup$ lets positive constants through unchanged.
$\| A + B \| \le \| A \| + \| B \|$: intuitively this ought to be true because on the LHS we have to give the same $v$ to $A$ and $B$ whereas on the RHS we maximise each separately. See if you can work out the details just by expanding the definitions.
Comment: Sorry, you're right. I had not noticed the last sentence of the post.
Comment: The question asks whether this norm is an inner product norm, which is equivalent to the parallelogram law being satisfied.
Comment: @julien: correctly observed! But it also says "my problem is that I'm even can't understand the norm and how it function." – my hope is that once that issue is addressed, the questioner will be able to solve the problem.
Answer: First show that the norm of $\rm A$ is equal to the greatest module of the eigenvalues of $\rm A$.
Second $u = \begin{bmatrix} 0 & 0 \\ 0 & 1 \end{bmatrix} ; v = \begin{bmatrix} 1 & 0 \\0 & 0 \end{bmatrix}$ is a counter-example.
Comment: Note that the norm is equal to the spectral radius when $A$ is normal, not in general. This is fine here since your examples are normal.

parallelogram law


Quadratic Forms Orthogonal Diagonalization Existence

Question: Why does one assume that the eigenbasis for a quadratic form is orthogonal, hence orthogonal diagonalization. I understand that for hermitian and unitary maps one can show by spectral theorem an orthogonal basis of eigenvectors exists, however does this also hold true for quadratic forms? My question is basically how does one show that a quadratic form has an orthogonal basis that furthermore also leads to a diagonal matrix? Thanks in advance for any insight
Comment: In short, a quadratic form can be represented by a hermitian matrix.
Comment: Oh yes, I see the transpose of a matrix's complex conjugate is defined as the adjoint of the matrix. Therefore if one can represent the quadratic form as a matrix that is its own adjoint, we are done?
Comment: Is this why a quadratic form is constrained to a symmetric bilinear form
Answer: For a symmetric matrix the eigenvectors associated with distinct eigenvalues are orthogonal.
The eigenvectors associated to the same eigenvalues are orthogonalized by the Gram-Schmidt process.
Thus for a quadratic form we always have an orthogonal set of eigenvectors.


jquery mobile 1.4.0 ajax error

Question: So I've switch to jquery mobile 1.4.0-rc.1 and I'm having an error after changing.
And I'm having an error to this code and other similar code.
<code>$.mobile.loading("show");
$.mobile.changePage( "index.html", { changeHash: true });
</code>
I'm getting the error:
Uncaught TypeError: Cannot call method 'loading' of undefined
And I read that this is deprecated for the new version. I can't find the replacements for this.
Can anyone help me to resolve this or can someone give the fix to this?
Any help would be appreciated. Thanks in advance.
Comment: use `$.mobile.pageContainer.pagecontainer("change", "index.html");` as `$.mobile.changePage` is deprecated.
Comment: judging by your error, you seem to invoke $.mobile before it's there. You should provide some more code, so we can see when you call the loader and why `$.mobile` is not defined yet
Answer: Unfortunately, even with the release of the stable 1.4 version, the documentation is still at a very early stage, and it's quite hard to find replacements for deprecated functions.
According to the pagecontainer api (but not directly stated), it seems that the selector ':mobile-pagecontainer' can be used to access the pagecontainer object, and also execute a page change:
<code>$(':mobile-pagecontainer').pagecontainer('change', '#new_page');
</code>
Notice of this can be found in the first part of the hide event example: http://api.jquerymobile.com/pagecontainer/#event-hide
For what concerns the loader widget, if the related api is up to date (http://api.jquerymobile.com/loader/) it hasn't been deprecated with this new 1.4 version, so problems with it should be sought elsewhere.

jquery mobile 1.4.0 ajax error


How do I get debug_backtrace() to fire on the endpoint site of a Deployment process?

Question: I'm trying to work through this UUID features bug with the deploy module. On the receiving site, I see errors in that log like
<code>PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'fc661e5c-62de-fa34-2557-0f6f5a2acbfe' for column 'fid'
</code>
I've followed the example laid out here to have a backtrace show for any error on both the sending and receiving installations. However I can' seem to find a way to get the backtrace to show for the error on the receiving site after the deploy process completes. I can see the service error in /admin/reports/dblog but that's it.
Any help is greatly appreciated!
-adbo
Answer: note the following: fc661e5c-62de-fa34-2557-0f6f5a2acbfe
and then... General error: 1366 Incorrect integer value:
the number or UUID is not an integer.
therefore you'll get that sort of error message. I'm assuming deploy has either a bug in it or you've forgotten to run update.php on your DB the FID field is marked in the DB as an integer when it should be a varchar / string field.
Take a look at the schema and see what needs to change. that should at least give you an indication of where things have gone wrong.