Product of infinite terms $\lim_{n\to\infty}\left(\frac{(n+1)(n+2)...(3n)}{n^{2n}}\right)$

Question: Let there be a series
$$\lim_{n\rightarrow \infty}\left(\frac{(n+1)(n+2)...(3n)}{n^{2n}}\right)$$
is equal to?
For this type of problem I am unable to approach.The numerator starts from $(n+1)$ to $3n$ where as the denominator has ${n^{2n}}$ terms
Comment: Thank for editing, this question is correct
Answer: There are $2n$ factors in the numerator.  Of them, the first $n$ are each greater than $n$, and the next $n$ are each greater than $2n$.  Thus, the numerator is greater than $n^n (2n)^n$.  The denominator is $n^{2n}$ and so the ratio is greater than $2^n$, which of course tends to $\infty$ as $n\to\infty$.
Comment: $\infty$ for $n\to\infty$ is not the answer, i presume that we can arrive by using log and definite integral concept
Comment: That's what you think.
Comment: @SamarImamZaidi As you can see from other answers, the limit indeed is $+\infty$. Comparing with the answers posted so far, I consider *this* approach the most elegant, +1 from me.
Answer: Hint:) With Stirling's approximation
$$n!\sim\sqrt{2\pi n}\left(\dfrac{n}{e}\right)^n$$
we have
$$\lim_{n\rightarrow \infty}\left(\frac{(n+1)(n+2)...3n}{n^{2n}}.\dfrac{n!}{n!} \right)=\lim_{n\rightarrow \infty}\dfrac{(3n)!}{n!n^{2n}}=\lim_{n\rightarrow \infty}\sqrt{3}\left(\dfrac{27}{e^2}\right)^n=\color{blue}{\infty}$$
Answer: One possibility that I usually do for products is to take logarithms. For any finite $n$, we have
$$
\ln\left(\frac{(n+1)\dots(3n)}{n^{2n}}\right)=\sum_{k=1}^{2n}\ln\left(\frac{n+k}{n}\right)=\sum_{n=1}^{2n}\ln\left(1+\frac{k}{n}\right)=n\sum_{k=1}^{2n}\frac{\ln(1+\tfrac{k}{n})}{n}
$$
In the limit, the sum
$$
\sum_{k=1}^{2n}\frac{\ln(1+\tfrac{k}{n})}{n}
$$
approaches a positive, nonzero definite integral, whereas $n$ approaches infinity. Thus the logarithm approaches infinity, so the original product does as well.
Comment: Can be converted into Integral form using the property of Definite Integral
Comment: I want to confifm with you whether the answer is $\int_{0}^{2} log(1+x)dx$
Comment: @SamarImamZaidi Yes, that is the correct integral
Answer: Let us denote
$$a_n=\frac{(n+1)(n+2)...(3n)}{n^{2n}}.$$
Then you have
$$\frac{a_{n+1}}{a_n} =
\frac{(3n+1)(3n+2)(3n+3)}{(n+1)^3}  \left(\frac{n}{n+1}\right)^{2n}.$$
I should be relatively easy to check that
$$\lim\limits_{n\to\infty} \frac{a_{n+1}}{a_n} > 1.$$
(In fact, the limit is equal to $27/e^2$ unless I missed something.)
Can you tell something about $a_n$ combining the facts that it is positive and starting from some $n_0$ you have $a_{n+1}/a_n>1+\varepsilon$ (for some $\varepsilon>0$)?
In the other words, can you show this: If $a_n>0$ for each and $\lim\limits_{n\to\infty} a_{n+1}/a_n>1$, then $\lim\limits_{n\to\infty} a_n=\infty$?
Comment: Very elegant solution without using Stirling. +1


Selecting a value from another row: mysql

Question: I have a table called Post:
title (NULL), content, parent_id (NULL)

The title is null because I use this for threads and replies (replies do not have a title and threads do not have a parent).
Say I want to select all the replies to post x, or an n number of replies:
SELECT * FROM post
WHERE title IS NULL
AND parent_id = x

or,
SELECT * FROM post
WHERE title IS NULL
AND parent_id IS NOT NULL
LIMIT 0, 30

How can I also select the title of a reply? Say for example if I select reply number 5 and it's a reply to post id# 2 (i.e has parent_id of 2), how can I select the title of number 2?
I don't want to use a foreach loop in mysql.
Hope this makes sense.
Thank you.
Comment: Do you know if this would be more than one level deep? As is already discussed, a single join would solve your problem if replies can only be added to a Post with a title (i.e. not another reply).
Answer: Assuming your Post table structure looks like:
+-----+------------+-----------------+----------+
| id  | parent_id  | title           | content  |
+-----+------------+-----------------+----------+
| 1   |  NULL      | Post #1 Title   | ...      |
+-----+------------+-----------------+----------+
| 2   |  NULL      | Post #2 Title   | ...      |
+-----+------------+-----------------+----------+
| 3   |   1        |                 | ...      |
+-----+------------+-----------------+----------+
| 4   |   2        |                 | ...      |
+-----+------------+-----------------+----------+

You need to use a join:
SELECT
   *, parent.title AS parent_title
FROM
   post
LEFT JOIN
   post as parent ON parent.id = post.parent_id
WHERE
   post.id = 4

That would select post id=4 and also get you the title of post id=2 stored in the field parent_title
Comment: `#1052 - Column 'id' in where clause is ambiguous`
Answer: COALESCE returns first value of an argument list that is not null.
   SELECT post.content, COALESCE(post.title, parent.title) AS title
     FROM post
LEFT JOIN post AS parent
       ON post.parent_id = parent.id
    WHERE post.parent_id = 123

Answer: I'd join from your post table into your post table. It's fun. (This assumes that your post table has an id column, which corresponds to parent_id)
SELECT child.*, parent.title FROM post child JOIN post parent ON (child.parent_id=parent.id)


Alternatives to logistic regression in R

Question: I would like as many algorithms that perform the same task as logistic regression.  That is  algorithms/models that can give a prediction to a binary response (Y) with some explanatory variable (X).
I would be glad if after you name the algorithm, if you would also show how to implement it in R.  Here is a code that can be updated with other models:
set.seed(55)
n <- 100
x <- c(rnorm(n), 1+rnorm(n))
y <- c(rep(0,n), rep(1,n))
r <- glm(y~x, family=binomial)
plot(y~x)
abline(lm(y~x), col='red', lty=2)
xx <- seq(min(x), max(x), length=100)
yy <- predict(r, data.frame(x=xx), type='response')
lines(xx, yy, col='blue', lwd=5, lty=2)
title(main='Logistic regression with the "glm" function')

Comment: This isn't really too broad to be answerable--it currently has 6 answers (5 upvoted). Moreover, the question is highly upvoted & highly favorited, & is CW. It should remain open, IMO.
Comment: Do we have to assume that you are considering a fixed set of predictors, i.e. you are interested in getting a reliable prediction given $k$ predictors, or are you also interested in some kind of penalization on the $X_j\quad (j=1\dots k)$?
Comment: I admit that for my personal interest, penalization wouldn't be necessary, and for the sake of knowledge here I would say both are relevant answers :)
Comment: For future reference: you might have been able to phrase this question in such a way that we would have allowed it as a non-CW question.  See http://meta.stats.stackexchange.com/questions/290/what-is-community-wiki
Comment: Thank you for the link Shane.  A very interesting discussion you opened there.  After reading Thomasas answer, I believe this should still be a community wiki, since my intention was to find as many alternatives as possible (something i doubt any one person would be able to supply).
   Yet, again, thank you for directing me to that thread!
Comment: [Here](https://gist.github.com/galenseilis/163fba52015ff2b52258b9c3be57a58a) is a Python gist making a similar plot as the question.
Answer: Popular right now are randomForest and gbm (called MART or Gradient Boosting in machine learning literature), rpart for simple trees.  Also popular is bayesglm, which uses MAP with priors for regularization.
install.packages(c("randomForest", "gbm", "rpart", "arm"))

library(randomForest)
library(gbm)
library(rpart)
library(arm)

r1 <- randomForest(y~x)
r2 <- gbm(y~x)
r3 <- rpart(y~x)
r4 <- bayesglm(y ~ x, family=binomial)

yy1 <- predict(r1, data.frame(x=xx))
yy2 <- predict(r2, data.frame(x=xx))
yy3 <- predict(r3, data.frame(x=xx))
yy4 <- predict(r4, data.frame(x=xx), type="response")

Comment: [Here](https://gist.github.com/galenseilis/0788823ef65d05035e220cd6d8bbf4cf) is a Python gist training similar models.
Answer: Actually, that depends on what you want to obtain. If you perform logistic regression only for the predictions, you can use any supervised classification method suited for your data. Another possibility : discriminant analysis ( lda() and qda() from package MASS)
r <- lda(y~x) # use qda() for quadratic discriminant analysis

xx <- seq(min(x), max(x), length=100)
pred <- predict(r, data.frame(x=xx), type='response')
yy <- pred$posterior[,2]

color <- c("red","blue")

plot(y~x,pch=19,col=color[pred$class])
abline(lm(y~x),col='red',lty=2)
lines(xx,yy, col='blue', lwd=5, lty=2)
title(main='lda implementation')

On the other hand, if you need confidence intervals around your predictions or standard errors on your estimates, most classification algorithms ain't going to help you. You could use generalized additive (mixed) models, for which a number of packages are available. I often use the mgcv package of Simon Wood. Generalized additive models allow more flexibility than logistic regression, as you can use splines for modelling your predictors.
set.seed(55)
require(mgcv)
n <- 100
x1 <- c(rnorm(n), 1+rnorm(n))
x2 <- sqrt(c(rnorm(n,4),rnorm(n,6)))
y <- c(rep(0,n), rep(1,n))
r <- gam(y~s(x1)+s(x2),family=binomial)

xx <- seq(min(x1), max(x1), length=100)
xxx <- seq(min(x2), max(x2), length=100)
yy <- predict(r, data.frame(x1=xx,x2=xxx), type='response')

color=c("red","blue")
clustering <- ifelse(r$fitted.values < 0.5,1,2)

plot(y~x1,pch=19,col=color[clustering])
abline(lm(y~x1),col='red',lty=2)
lines(xx,yy, col='blue', lwd=5, lty=2)
title(main='gam implementation')

There's a whole lot more to do :
op <- par(mfrow=c(2,1))
plot(r,all.terms=T)
par(op)

summary(r)
anova(r)

r2 <- gam(y~s(x1),family=binomial)
anova(r,r2,test="Chisq")

...
I'd recommend the book of Simon Wood about Generalized Additive Models
Comment: [Here](https://gist.github.com/galenseilis/ea21fc7b792318c641b7911348ec430e) is a Python gist training similar models.
Answer: I agree with Joe, and would add:
Any classification method could in principle be used, although it will depend on the data/situation.  For instance, you could also use a SVM, possibly with the popular C-SVM model.  Here's an example from kernlab using a radial basis kernel function:
library(kernlab)
x <- rbind(matrix(rnorm(120),,2),matrix(rnorm(120,mean=3),,2))
y <- matrix(c(rep(1,60),rep(-1,60)))

svp <- ksvm(x,y,type="C-svc")
plot(svp,data=x)

Comment: [Here](https://gist.github.com/galenseilis/4427c875784473791c419b53dede1c30) is a Python gist training a support vector machine classifier using a radial basis function.
Answer: There are around 100 classification and regression models which are trainable via the caret package. Any of the classification models will be an option for you (as opposed to regression models, which require a continuous response). For example to train a random forest:
library(caret)
train(response~., data, method="rf")

See the caret model training vignette which comes with the distribution for a full list of the models available. It is split into dual-use and classification models (both of which you can use) and regression-only (which you can't). caret will automatically train the parameters for your chosen model for you.
Answer: Naive Bayes is a good simple method of training data to find a binary response.
library(e1071)
fitNB <- naiveBayes(y~x)
predict(fitNB, x)

Comment: [Here](https://gist.github.com/galenseilis/cb567a4f83b8c6cb80c6def58076d529) is a Python gist training a Gaussian naïve Bayes classifier.
Answer: There are two variations of the logistic regression which are not yet outlined.  Firstly the logistic regression estimates probabilities using a logistic function which is a cumulativ logistic distribution (also known as sigmoid). You can also estimate probabilities using functions derived from other distributions. The most common way apart from the logistic regression is the probit regression which is derived from the normal distribution. For a more detailed discussion between the differences of probit and logit please visit the following site.
Difference between logit and probit models
set.seed(55)
n <- 100
x <- c(rnorm(n), 1+rnorm(n))
y <- c(rep(0,n), rep(1,n))
r <- glm(y~x, family=binomial(link="probit"))
plot(y~x)
abline(lm(y~x),col='red',lty=2)
xx <- seq(min(x), max(x), length=100)
yy <- predict(r, data.frame(x=xx), type='response')
lines(xx,yy, col='red', lwd=5, lty=2)
title(main='Probit regression with the "glm" function')

The second alternative points out a weekness of the logistical function you implemented. If you have a small sample size and/or missing values logistic function is not advisable. Hence an exact logistic regression is a better model.  The log odds of the outcome is modeled as a linear combination of the predictor variables.
elrm(formula = y ~ x)

Furthermore there are other alternatives like to be mentioned:

Two-way contingency table
Two-group discriminant function analysis.
Hotelling's T2.

Final remark:
A logistic regression is the same as a small neural network without hidden layers and only one point in the final layer. Therefore you can use implementations of neural network packages such as nnet in R.
Edit:
Some weeks later I realized that there is also the
Winnow  and the
Perceptron  algorithm. Both are classifiers which work also for classifications into two groups, but both are fallen out of favor in the last 15 years.
Comment: [Here](https://gist.github.com/galenseilis/c4a10eea1475fa92ca6ee054e52b6fde) is a Python gist training some similar models.


.NET Native and RCW overhead

Question: I'm curious about how .NET Native works. Normally when using WinRT classes in managed code, they are invoked through RCW, incurring some overhead due to the interop between managed and unmanaged code. I wonder if there is theoretically the same overhead when the managed code is compiled using .NET Native?
Answer: .NET Native interop with WinRT has the same structure as running with CoreCLR or full framework. This is because you have the unavoidable overhead of ensuring the memory for various objects is tracked properly as they are handed accross the boundary. There will always be come irreducible set of things that need to be tracked because of the GC in whichever .NET runtime you're targeting.
That said, the interop code generated for a .NET Native based application will have the benefit of being generated ahead-of-time. This means that it's able to be optimized by the same program optimizer that is part of our C++ compiler so you're going to get the best assembly codegen that Microsoft can offer.
(Disclosure: I work on the .NET Native runtime and compiler team)

.NET Native and RCW overhead


windows server 2003 subdomain routing to lan

Question: I have Windows Server 2003 with two network cards. 1 network card is connected to the router and router is connected to internet. 2nd cards is connected to switch and there are another 5 PC's connected to that switch. Windows server routs all internet traffic for those PCs
I have a static IP and set up a domain name on that IP. Now what I wish to do is to add a subdomain (like computer1.domain.com I have DNS installed and know how to add subdomains) and route all that subdomain traffic to one PC inside LAN. So for example if I try to connect from the internet to domain.com I would connect to my windows server, but if I try to connect to computer1.domain.com I would connect to a PC inside my LAN.
Is this at all possible, and if so could someone at least point me to the right direction as I am struggling to see where should I start.
Thanks!
Answer: No. This is generally not possible if you only have one public IP address.
The main function of DNS is to resolve a name (eg. host.domain.com) into an IP address. It doesn't matter how many different subdomains or host records you create, because they will all resolve to the same IP address.
Because packets sent over the internet are addressed using only the IP address, there is generally no way for the recipient to distinguish between requests for host1.domain.com and host2.domain.com. In order to route traffic to different hosts, you will need more than one public IP address.
One common exception to this rule is HTTP. When a web browser sends an HTTP request, it also embeds information about the domain that you're trying to contact. Smart devices can use this information to route HTTP requests to different servers, even when they are behind the same IP address.


Is there any advantage to PreparedStatement#setInt vs inline SQL?

Question: I've read Give me Parameterized SQL or give me death numerous times.
The advantage of Parameterized SQL for Strings, Dates, and floating-point numbers is very obvious and indisputable.
My question is: what about ints?
I ask because, oftentimes, if I'm writing a query or update and the only parameter is an int, I'll just write an inline sql and append the int as a shortcut ("select * from table where id = " + id).
My question: Are there any advantages to using Parameterized SQL for ints alone?
To illustrate with Java:
Are there any advantage to this:
Connection conn;
int id;
String sql = "select * from table where id = ?";
try (PreparedStatement p_stmt = conn.prepareStatement(sql)) {
    p_stmt.setInt(1, id);
    ResultSet results = p_stmt.executeQuery();

    // ...
} catch (SQLException e) {
    // ...
}

over this:
Connection conn;
int id;
String sql = "select * from table where id = " + id;
try (Statement stmt = conn.createStatement()) {
    ResultSet results = stmt.executeQuery(sql);

    // ...
} catch (SQLException e) {
    // ...
}

Answer: I would say the biggest advantage would be consistency. If you decide that all SQL built by string concatenation is "wrong", it's easier to verify that your code is "right", compared to a rule like "All SQL built by string concatenation is wrong, except that which deals with ints as parameters".
Another case, say: down the line, you want to introduce sorting or grouping to the query, suddenly, your line turns into something like this:
String sql = "select * from table where id = " + id + " order by somecolumn";

And hopefully you remembered the space before order. And that everyone after you does also.
There is much to be said for doing things only one way, especially when that one way is the right thing most of the time.
Comment: Good answer. And I agree, consistency is important.


Determine at what points in its domain $f$ is differentiable

Question: I have been trying to solve the two problems. Here's what I did:
1) I found the partial derivatives:
(A) $\,f_x = -y\sin(xy)$ and $f_y = -x\sin(xy)$
(B) $\,f_x = ye^{xy} + 2x/(1+x^2+y^2)$ and $f_y = xe^{xy} + 2y/(1+x^2+y^2)$
2) I think that there is a theorem that says that if the partial derivatives of a function are continuous at $(a,b)$ then the function is differentiable at (a,b).
Now I don't know how to show that partial derivatives are continuous.
Is it correct for me to assume that since all the functions are continuous, so their product is also continuous, and hence both partial derivatives are continuous over the domain so the function is differentiable over the domain?
Comment: If a function is not continuous at some point, it can't be differentiable at this point. The superposition of continuous functions is continuous. Use those facts to solve the exercise
Comment: @Adam that's a very common and fatal misunderstanding that most students in my class made.
Comment: About "part B", why do you think the function isn't continuous at $(x, y)=(0, 0)$? It's continuous
Comment: @Adam my bad I don't know why I forgot that 1 in the denominator.
Answer: Since,
both partial derivatives exist and are continuous for both part(A) and part (B) in their whole domain $R^2$,
so both functions are differentiable at every point in $R^2$.


Imagem responsiva, não redimenciona corretamente

Question: Estou desenvolvendo um site, e uma imagem não está redimensionando como eu esperava, tenho a imagem:

e tenho minhas classe CSS para redimensionar:
.cover {
 padding: 30px 15px;
 margin-bottom: 30px;
 color: inherit;
 background-color: #eeeeee;
 margin-bottom: 0px !important;
 padding: 0px 0px;
 background-color: transparent;
 display: -webkit-box;
 display: -ms-flexbox;
 display: -webkit-flex;
 display: flex;
-webkit-align-items: center;
 align-items: center;
 overflow: hidden;
 position: relative;
 height: 70%;
}
.cover .cover-image {
z-index: -1;
position: absolute;
top: 0px;
width: 100%;
min-height: 30%;
height: 100%;
background-size: cover;
background-position: center;

}

Comment: redimensionar como ? como você quer que ela fique ?
Comment: https://jsfiddle.net/ddLaqyvq/
Comment: O controle de redimensionamento é feito no CSS. Mas você tem que analisar se o tamanho da imagem está bom. Seu width está 100% você pode aumentar seu height também. Mas ainda está um pouco difícil de entender...
Comment: @roger seguinte eu pretendo colocar qualquer imagem. Desta forma quero deixar ela redimensionando automaticamente
Answer: É o seguinte André a propriedade (background-size) quando você passar alguma unidade de medida em % por exemplo ele faz o redimensionamento mantendo o aspect ratio (proporção) da imagem com base na largura e altura do box pai.
Agora se você usa a palavra-chave (contain/cover) ele redimensionar proporcional mas trabalhando de forma diferente.
Contain: Maior dimensão ocupa toda extensão do box;
Cover: Menor dimensão ocupa toda extensão do box.
Agora você escolhe o melhor layout amigo.


Cross Validation for regularized portfolio optimization

Question: Hi I'm having an explanation like below. I'm trying to find the minimum global portfolio and I found following explanation

I need to use validation methods to use the optimal parameters. Also i need to use the regularizers.
I'm ok with adding the regularizers. If I need to implement the below method, it asks me to use the k fold cross validation. Can someone explains me the steps that I need to follow.
I can take this as a whole. But how is it possible to use cross validation. What should be the train dataset and the labels. based on what, i should find the best parameters.
Are these steps correct.
1) If I take 10 cross validation, data set will be divided in to 10 sets and 9 sets will be accounted for its best weight set. (Minimum variance and best sharpe ratio) Then the mean value of these weights will be taken. Then using the same lambda value find the rest of the best weight set as well. Then we can compare the Minimum standard error between 2 weight metrics
2) Then change the lambda, and do the same procedure.
3) We can follow the above two steps for various regularizers.
So with that approach we can find the best parameters who gives the minimum error.
Are the above steps correct? Can someone kindly correct me if Im wrong
Answer: If you're fine with finding the optimal portfolio with regularization, follow these steps:

Randomly pick K industries (note there's capital K, which is the number of industries, and small k = 10 which is the number of times you should repeat the process)
Calculate optimal weights for these randomly picked industries, and find their Lambda
Repeat (1)-(2) 10 times

When you finish you should have 10 lambdas, the quote says to pick the "maximum lambda with the minimum mean-squared error". Not sure what it means, maybe you can post the link of this paper and it'll be clearer.
Comment: But usually, 10 fold cross validation means ; dividing the dataset into 10 and train with 9 and test with 1 ryt? https://www.academia.edu/36207052/Markowitz_Mean-Variance_Portfolio_Optimization_Using_Regularization_Techniques?auto=download. This is the original paper


Changing the order of integration: How to set the bounds

Question: A derivation is given in a textbook. Here, $F$ is a probabilistic distribution function, which means that: $$\int_{-\infty}^{\infty} F(t) dt = 1$$
At one step, they change the order of integration:
\begin{align}
H(x) &= \int_{-\infty}^x \int_s^x dt \: dF(s) \\
&= \int_{-\infty}^x \int_{-\infty}^t dF(s) \: dt
\end{align}
My question is, how did they come up with the bounds in the second line?
Comment: That may depend on the actual function $F$ : do you have more information about this function ?
Comment: Yes. $F$ is a probabilistic distribution function, thus $\int_{-\infty}^{\infty} F(t) dt = 1$
Answer: Given a function $ f : \mathbb{R}^{2}\rightarrow\mathbb{R} $, such that $ \left(\forall s\in\mathbb{R}\right),\ f_{s}:t\mapsto f\left(t,s\right) $ is continious and integrable in $ \mathbb{R} $, and that $ g_{s}:x\mapsto\int\limits_{x}^{+\infty}{f\left(t,s\right)\mathrm{d}t} $ is also continious and integrable in $ \mathbb{R},\ \left(\forall s\in\mathbb{R}\right)\cdot $
Let $ x $ be a real.
For $ s \leq x $, denoting $ \left(\forall t\in\left]-\infty,x\right]\right),\ g_{s}\left(t\right)=\left\lbrace\begin{aligned}f\left(t,s\right),\ \ \ \textrm{If }t\geq s\\ 0,\ \ \ \textrm{If }t\leq s\end{aligned}\right. $, we have :
$$ \int_{-\infty}^{x}{\int_{s}^{x}{f\left(t,s\right)\mathrm{d}t}\,\mathrm{d}s}=\int_{-\infty}^{x}{\int_{-\infty}^{x}{g_{s}\left(t\right)\mathrm{d}t}\,\mathrm{d}s} $$
Using Fubini's theorem we get : \begin{aligned} \int_{-\infty}^{x}{\int_{s}^{x}{f\left(t,s\right)\mathrm{d}t}\,\mathrm{d}s}&=\int_{-\infty}^{x}{\int_{-\infty}^{x}{g_{s}\left(t\right)\mathrm{d}s}\,\mathrm{d}t}\\ &=\int_{-\infty}^{x}{\int_{-\infty}^{t}{f\left(t,s\right)\mathrm{d}s}\,\mathrm{d}t} \end{aligned}
Comment: Thank you for your answer. I don't completely understand though why $g_s(t)$ is defined like that for $t \geq s$ and $t \leq s$.


Mixed models. Random slopes only, mean and group centering?

Question: Are random intercepts a theoretical/practical prerequisite to random slopes? Why?
I have a three level (rep measures) mixed model where I wouldn't expect lvl 3 variation in initial status of outcome variable. That is, patients were randomly assigned to doctors, so their shouldn't be variation in mean of DV across doctors (all have equal chance of getting patients with high and low initial DV).
Variation exists in intercepts of patients, this is ok.
Question is, is a random slopes only model at lvl 3 allowed. Every example I see always has random intercepts first. Is this because it must or because I just got unlucky with examples?
Also, does anyone know how different numerical structures of the subject/ID variables affect mixed model?
I'd. Having a unique identifier for both levels vs having a unique identifier within each group at lvl 2 (individuals).
Also, can someone please explain the benefits, reasons and differences behind mean centered and group centered DVs?
Hope this is clear enough for discussion.
Thanks
Comment: What do you measure at level 1 for each patient? Repeated values of the DV at multiple time points? Also, does each patient see one and only one doctor?
Comment: @IsabellaGhement thanks for commenting. In this case the DV is a scale score made from the average of responses on 8 likert scale items. Yes, it's a rep measures design, 3 time points. Yes, one and only one doctor for all three time points.
Answer: This all depends on the nature of your study.
When you fit random intercepts, without random slopes, this assumes that each subject has the same response to the treatment, but each subject has a different baseline value:

When you add random slopes, then you allow each subject to have a different response to the treatment, and each subject still has a different baseline value:

It you don't fit random intercepts, but retain the slopes then you assume that each subject has a different response to the treatment, and each subject has the SAME baseline value:
Comment: Excellent response, Wayne!
Answer: A classic must-read on some aspects is Bill Venables (the Jekyll subset of Ripley/Venables) https://www.stats.ox.ac.uk/pub/MASS3/Exegeses.pdf.
And as a rare example where fixed zero offsets might be useful: Assume you measure "new-bone growth" after some surgery. By definition newbone is exactly zero at time of surgery, later it is measured and varies.
Answer:
Question is, is a random slopes only model at lvl 3 allowed. Every example I see always has random intercepts first. Is this because it must or because I just got unlucky with examples?

Yes, it is certainly allowed, but as illustrated in the plots in the answer by @Wayne, it is making an assumption about the baseline observations being equal at that level.

does anyone know how different numerical structures of the subject/ID variables affect mixed model? I'd. Having a unique identifier for both levels vs having a unique identifier within each group at lvl 2 (individuals).

This will depend on the software that you are using to fit the model and how you specify the model. In lme4 for R, for example, it should not make any difference provided that you specify the random intercepts correctly. See this answer and this answer for more information.

can someone please explain the benefits, reasons and differences behind mean centered and group centered DVs?

Grand-mean centering is often desirable for interpretation purposes, especially when interactions are involved, where the main effects show the effect of a covariate when the other one (in the case of a two-way interaction) is held at zero (which is often implausible in real world cases). In the case of group-mean centering, the random intercepts will be the unadjusted group means. The group means can then be used as a group-level predictor, and the coefficient for this predictor will be a between-group predictor.  Personally I have never found the need to do group-mean centering - though I have seen it done, particularly in the multilevel modelling literature.
Comment: Thanks. How would the first response see change,if any, with the predictor as a factor rather than a continuous. Time is a factor since they are rep measures
Comment: If I understand your point correctly it would make no difference. If time is a fixed effect then whether you model it as continuous or discrete is a modelling decision, and if you have a question about that, you should ask a new question here, or refer to other answers on that topic.
Comment: Ok, so the random intercepts specification only ever applies to the initial status.
Comment: We seem to be veering away from the substance of your question, so it would be better if you asked a new question about that, especially since I am not totally clear what you are driving at now, and I wouldn't want to give you incorrect advice. In the meantime please consider marking one of these answers as accepted. Comments are not meant for discussion on substantive issues.
Comment: "Yes, it is certainly allowed, but as illustrated in the plots in the answer by @Wayne, it is making an assumption about the **baseline** observations being equal at that level."

"Ok, so the random intercepts specification only ever applies to the **initial** status."

this is all I meant
Comment: Initial status and baseline are not necessary the same. It is not clear what you mean by  "initial", and "only ever applies". Things can be more complicated depending on how factors are encoded and whether continuous variables are centred. Please ask a new question about that, and include more detail about the study and the dataset.


guitar tuning - note shifts after striking it

Question: If I tune a guitar typically I see that I strike the string and the tuner records a certain value, e.g. dead on E.  However often (maybe not always - but I can't say for sure) a few moments later the tuner shows that the string is tuned slightly below E.
What causes this?  Surely as a string loses energy it doesn't drop in pitch?
Comment: May it be a [duplicate](https://music.stackexchange.com/q/940/8565)?
Comment: Maybe by tuning another string the neck gets slightly bowed and the string tension weakened.
Comment: This may be a possibility - particularly if the guitar has a trem system. I will do some testing ;)
Comment: Whilst you don't state what guitar you have, it's mostly a problem on 'cheaper' instruments.  I have a mid 80s Washburn with Floyd-Rose trem, and it doesn't go out of tune when played for hours/weeks at a time.  On the other hand, I've got a cheap-ish Telecaster that needs tuning every 5 minutes.
Comment: Maybe not a strict duplicate, but the answers there pertain very much to here.  Including the very important part about striking the strings while tuning to the same way you will be heard while playing.  So my classical guitar and my steel string strumming guitar are tuned with slightly different techniques.
Comment: This is difficult to answer without knowing details about your guitar. This could indicate that your tuning pegs needs adjustment/replacement, or if your guitar has nylon strings and you changed them recently they may simple be stretching/settling.
Comment: I think it *is* a [dupllicate](https://music.stackexchange.com/questions/23317/when-tuning-a-guitar-why-is-it-only-in-tune-for-a-moment/23329).
Answer: I don't know the precise physics of this, but it's an expected phenomenon, especially on heavier strings.
When you first strike the string hard, the amount of displacement in the vibration from 'perfectly straight' stretches the string, so in effect raises its tension & therefore pitch.
As it gets quieter, that displacement becomes less, so the pitch drops slightly, back to 'nominal'.
If you strike the string more softly, or further back towards the bridge, this will happen less.
This is aside from anything you may accidentally be doing to the guitar as this happens, perhaps resting on the rear of the body whilst holding the neck, etc. or that as you progress through the strings, if all needed to be raised in pitch, by the time you get to the last string the neck will have pulled forwards slightly, making the earlier ones flat.
Comment: I'll add to this: it's well known amongst us bowed string players that the pitch sharpens slightly as we crescendo from p to ff .  It's pure physics :-) .
Comment: @user307927 - if you hit it hard, it will, yes. It's all part of what makes a guitar [or any stringed instrument] sound 'alive'.
Comment: Yes. The "precise physics" of this involve two aspects: **a)** the "stretching" of the string. Actually, it's not stretching per se that's the problem – elastic stretching is the basis of why a string oscillates in the first place! – but that it's not perfectly _linear_: at strong amplitude the force becomes stronger than proportional to displacement. Solving this nonlinear differential equation yields a non-periodic solution, but its Fourier spectrum does indeed have higher frequencies than the linear low-amplitude version. **b)** [inharmonicity](https://en.wikipedia.org/wiki/Inharmonicity).
Comment: Could it be that a hard strike actually does stretch the string slightly? It has to be 'pulled' tighter so it produces a higher pitch, before returning to its proper tension. By stroking it instead, it's more likely to 'stay in tune'.
Comment: But surely if this were the case, as you strum a chord, for instance, it would sound out of tune as the volume decays.  hmmm
Comment: Well, I'm glad we cleared that one up ;-))
Answer: Yes, this is expected, for the reason Tetsujin states -- that a string vibrating at a higher amplitude is under higher tension.
Of course this raises the question - do you tune the guitar so that the attack is in tune with the other instruments, or the decay? The answer may depend on what kind of part the guitar is playing, and the mix of the track. In many cases it will be too small a factor to matter much, but occasionally being mindful of the pitch envelope of the decaying string will help you improve your final recording a little.
Comment: There is another aspect to "being mindful of the pitch envelope" and tuning: since the effect is more pronounced for wound strings than for bare ones, and is more pronounced the thicker the strings are, it sometimes makes sense, at least in a studio recording context, to record the bass line first, and then tune the other instruments to a playback of the isolated bass track instead of to a tuner.
Answer: It's always going to be the case, when you play the string too hard. Think about it - the string is stretched slightly as you pluck it (more when you pluck harder), so the shown pitch is going to be higher. Once it settles down and is sounding normally, it's fine.
Way round is to not pluck too hard - the device should still 'hear' it, but in any case, wait a second to establish what the tuner has decided the note is. Then tune accordingly.
On a personal note, I'm increasingly dismayed that so many players rely so heavily on tuners that soon they may have lost any other means of tuning!! Wait till the battery goes flat!
Comment: Don't forget tuning by ear is a skill that takes time to develop. My first guitar came with a tuning whistle, which made the learning curve even harder. Without a digital tuner I might not have made it past the first month. I do very much agree it's a valuable skill to learn.
Comment: @MeanGreen - too true. I threw away my tuning whistle, as it was *out of tune*!
Comment: +1 for tuning by ear, especially if you have to play to a slightly out of tune piano!  Always tune to the hardest instrument to tune in the group.
Comment: That said, if I AM the rhythm section for the session, and we are playing upbeat music with loud instruments, all anyone hears is my attack notes, so I tune to that initial strike, not the decay.  It depends on the role of the guitar within the other instruments.
Comment: @GuySchalnat - that's maybe why I still prefer to do it aurally - a lot of '60s discs were around half  a fret out from each other! What good would even a brilliant tuner (not invented yet) have been? Interestin that you tune slightly out. But if it works, it's a good move.
Comment: @Tim and bagepipes don't sound "right" tuned to concert A (to bagpipers, at least).
Comment: @GuySchalnat - every piper I've played with (and it's quite a lot over years) has been somewhere close to Bb - ish. So again, since bagpipes are really non-tunable (don't read anything into that..!) it's up to re-tuning guitars.
Answer: I was taught to tune from a higher frequency down to the correct value, instead of up from a low value.
There will likely be some difference in tension in the string, somewhere between the tuning mechanism to the nut after you stop turning the tuning peg. I assume the friction of the strings on the nut causes this.
It might not reveal itself directly, but when the tension evens itself out over the entire string later, the sounding part of the string can go slightly out of tune.
Comment: Generally, the term 'tuning up' comes from the practice of starting lower and literally tuning up. Mostly pertaining to violins, cellos et al, but it is also applicable to guitars, which can slip down, but rarely slip up (I leave that for when I solo...). So starting with tension, and increasing it up to the desired pitch is what I've done for many decades.
Comment: What's the pic for?
Comment: Now it's clear that the pic is to show 'nut' it makes sense. Good idea!
Comment: @Tim for me the term 'nut' was new in this meaning. If it's clear to most people what part I mean I can remove it, but I'm not a native English speaker.
Comment: The trouble with dropping to in tune from over-pitch is that the nut is far more likely to get sticky & suddenly drop 10 cents just when you thought it was all fine. Pulling on the strings as you would for a new string would help, but it's way more effort than just dropping the string a tone & tuning up from there.
Answer: Most people find it easier to identify "in tune" when coming up from below. I dunno why; one of those neuroacoustic things.
There's the added advantage that you reduce the risk of snapping a string from overtensioning.
And equally important: tuning from below means there's no backlash or relaxation effects. If you tune from above, you are releasing tension but the string may well take a little time to fully release - hence drifting out of tune.  And when tuning from below, the machine head (gears in the tuning mech) is always fully "non-backlashed" as well.
Comment: I'm guessing because strings usually don't get more *tight* when you leave them alone. So in practice, you'll always be coming from below, adjusting to higher. Do that umpty years, and that's what you will get trained in.
Comment: 'Tuning **up**' - true, but with violins and cellos, etc, isn't it to retain tension around the pegs. And have you tried those geared machine heads yet? Won't be long before Gibson gets their hands on them and automates them, as they have with guitars! Life will be so easy then - as soon as they go out of tune, the gears will re-tune for you!
Answer: What I usually do:
When I tune a guitar I pull on the string to stretch it or to control that it is correct fixed. Yes, and as I mentioned in my comment:
Maybe by tuning another string the neck gets slightly bowed and the string tension weakened.
Comment: Wouldn't that imply that effectively your guitar can't be tuned, and it's time to buy a new guitar? If tuning one string affects another string badly enough for the string to go out of tune, then you're basically doing a never ending dance to get it in tune. Worst case a **very** long and unreliable dance.
Comment: @WillemvanRumpt - it's fairly standard procedure on a full restring, especially if you have a skinny neck like an SG, or a floating trem. Quick tune from bottom to top, then an accurate one correcting the inherent detune the first one generates.
Comment: @Tetsujin: Yes. On a full restring.


what does scaling the normal vector of a plane (/hyperplane) mean?

Question: I understand that, scaling (multiplying or dividing by a constant) the normal vector of a plane, does not affect the plane itself.
But what happens when we do so? Are we zooming in or out of the space, like in a linear transformation?
Or in simpler words, what's the intuitive effect on scaling the normal vector of a plane(or a hyperplane)?
I came across the optimization problem whilst learning SVM (support vector machines) which goes like this:
minimize $w^\top w$  s.t. $\forall_i, \, \ y_i(w^\top\cdot x_i+b) \geq 1$,
where $w$ is the normal vector of the supporting hyperplane.
So we are basically looking to minimize the length of the normal vector of the hyperplane ($w^\top\cdot w$) subject to the constraint.
So I'm just wondering what effect could come out of minimizing the length of the normal vector.
Answer: We want to create as broad a separation (a wide "street") between positive and negative examples, or in other words, maximize the distance between the tips of the support vectors and the decision boundary (the median of the street):

If the normal vector to the decision hyperplane, $\vec w$, is normalized, $\frac{\vec w}{\Vert \vec w \Vert}$, the street width will be equal to the dot product of a vector spanning the distance between any two points in the positive and negative boundary limits ("the gutter"), ($x_{+}$ and $x_{-}$), and $\frac{\vec w}{\Vert \vec w \Vert}$.
Imposing the constraint $y_i(w^\top\cdot x_i+b) \geq 1$ will have the positive effect of maximizing the width of the street; however $b$ is not a predetermined value, and in fact, it is not part of the final Lagrangian expression. As for $y_i$, the objective is simply to keep the sign of the inequality (semi)-positive.
Given these premises, we can quickly arrive at the conclusion that maximizing the width of the "street" is equivalent to minimizing the norm of $\vec w$.
Above $x_+$ and $x_-$ are in the gutter (on hyperplanes maximizing the separation). Therefore, for the positive example: $({\bf x_i}\cdot \color{blue}{w} + b) -1 = 0$, or ${\bf x_+}\cdot \color{blue}{w} = 1 - b$; and for the negative example: $ {\bf x_-}\cdot \color{blue}{w} = -1 - b$. So, reformulating the width of the street:
$$\text{width}=(x_+ \,{\bf -}\, x_-) \cdot \frac{w}{\lVert w \rVert}= \frac{2}{\lVert w \rVert} \tag{the width of the street}$$
We just have to maximize the width of the separation, which amounts to maximizing  $  \frac{2}{\lVert w \rVert}$, or minimizing $ \lVert w \rVert$.
This can easily be verified analytically, or with a geometry game:

The positive examples are green dots, and the negative examples, red. Notice that by changing the slope of the parallel lines (the street gutters), we make the separation broader and broader until reaching a maximum value, and along the process, the norm or length of the normal vector (chosen randomly) decreases from $\Vert\text{NormVec}\Vert=2.67$ to $\Vert\text{NormVec}\Vert=2$. The vector spanning the difference between a positive and a negative example in the gutter is $\text{DiffSV}$ (difference support vector), and its projection orthogonal to the decision boundary $\left(\text{Proj}\right)$ (projection) increases in magnitude as the norm of the normal vector to the decision hyperplane decreases.
This makes sense, because at the same time, the angle $\alpha$ between $\text{DiffSV}$ (difference support vector) and $\text{Proj}$ (projection) decreases, and the cosine increases. Therefore $\Vert w \Vert$ has to decrease to keep the trigonometric relation:
$$\text{Proj}=\Vert \text{DiffSV}\Vert \,\cos(\alpha)=\frac{\vec w}{\Vert w\Vert}\,\cdot\,\text{DiffSV}.$$
Here is a Geogebra toy example.
Comment: Notice that we are engaged in an optimization problem ($\geq 1$), and that this $1$, when shifted to the LHS we end up with $y_i \, \left( x_i\cdot w + b \right) -1$, where the $b$ is not defined. There is a great post just dedicated to this point [here](http://stats.stackexchange.com/a/193459/67822).
Comment: I think you are pointing me in the right direction, but i don't completely follow you. Here we aren't normalizing the vector w (we arent' dividing by its norm), instead we are just minimizing its dot product, subject to the constraint. Could you please elucidate a bit more?
Comment: I'm big on editing posts until they are right, but I have to admit that I'm not quite sure what your question is, and this is just because communication is sometimes hard at both ends. I have some [notes on a website](http://rinterested.github.io/statistics/svm.html) that I keep mainly for quick access to info, and I wonder if you could take a look there, and see if we can get a good answer afterwards.
Comment: Ok, I went though the notes, and my question is related to what comes later in the notes. I understand how each step follows in SVM algorith, and towards the end we are left with this residual problemm - minimize $w^\top w$  subject to a constraint. How is finding a minimal  $w^\top w$ relate to the constraint or matter in any way, since we are just scaling down w by minimizing minimize $w^\top w$
Comment: @NithishInpursuitOfhappiness Hopefully this is a reasonable answer to your question.
Comment: Thank you for this brilliant depiction! I had a serious misunderstanding that we were fixing on one particular w and then trying to reduce its norm, which is clearly not the case. One more question that I had is, shouldn't the inequality  $y_i(w^\top\cdot x_i+b) \geq 1$ instead be $y_i(w^\top\cdot x_i+b) \geq $(largest dist between the+ and - points)? Why is it simply 1 instead?
Comment: Thanks for the compliment. In answer to your question, let me give you a visual: I have a very long ladder in the shed, as well as a ton of stuff piled up in it; I don't need it very often, but when I do, no amount of single measurements could help me decide how to get it out. The one thing I know, though, is that at some point, and after much maneuvering, I get the ladder over my head, and it slides right out the door, barely touching every other box, bicycle, shelf and gardening pot, and barely making it through the doors. I have optimized my SVM problem!
Comment: More concretely, the distance that makes the road broader, is not the maximum distance between positive and negative points.
Comment: I guess that's because, a road as broad as the max distance between positive and negative points, cannot always classify the points correctly. But, why did we start off saying that it has to be greater than "1" specifically? Why not any other arbitrarily small number? I just want to ensure that I'm not missing any known intuition over here.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/55452/discussion-between-nithish-inpursuit-ofhappiness-and-antoni-parellada).
Answer: I think that minimizing the normal vectors, allows you to compare planes just by their normal vectors. If they are the same, so are the two planes. This would not be as trivial if the two normal vectors are scaled differently. There are probably other useful features of having consistent rules for expressing normal vectors which I am not aware of.
Also note that, in terms of the plane, nothing is changing by scaling the normal vector since only the angle (or relative lengths of the components) matters to define a plane. Scaling is simply stretching the normal vector along it's axis.


How rough can differential form, manifold and chain be for Stokes theorem to hold?

Question: When I first learned Stokes theorem, everything is assumed to be smooth to prevent any strange things happen. But to apply to more cases, I may need to use a version of Stokes theorem that holds for rougher forms, chains and manifolds. For instance, when I learned Cauchy integral theorem, the paths and the analytic functions are only assumed to be $C^1$.
Does Stokes theorem hold for merely $C^1$ forms, chains and manifolds? I think so because we only exterior differentiate once in the equation of Stokes theorem, and the pullback by the chain (parametrisation of surfaces) only uses the first derivative, while the continuity of first derivative is added to ensure the exterior derivative ($d\omega$) and the pullback form ($(\partial c)^*\omega$) is integrable.
Edit: I see that Stokes theorem holds for manifolds with corners. I suppose these are equivalent to piecewise smooth surfaces, lines, etc. However, it is not all of what I am asking about. I am asking whether Stokes theorem holds when the differential form, manifold and chain are simply assumed to be $C^1$.
Comment: In page 137 of Spivak's Calculus on Manifolds (essentially the last page), he briefly comments that we actually can state Stokes' theorem for the so called *manifolds-with-corners*, modeled in open sets of "quadrants" (e.g., a $k$-manifold-with-corners is locally a piece of $\Bbb R^k$ bounded by pieces of $(k-1)$-planes). I have never seen the details written anywhere, though.
Comment: Maybe this might help [Stokes' theorem for nonsmooth chains](https://doi.org/10.48550/arXiv.math/9310231)
Answer: Stokes' theorem holds for manifolds with corners. The following is Theorem $16.25$ on page $419$ in John M. Lee's book $\textit{Introduction to Smooth Manifolds}$.
$\textbf{Theorem}$ (Theorem $16.25$, [Lee]). Let $M$ be an oriented smooth $n$-manifold with corners, and let $\omega$ be a compactly supported smooth $(n-1)$-form on $M$. Then
$$
\int_M d\omega = \int_{\partial M}\omega.
$$
The author proves the above theorem in the book. Furthermore, Lee also discusses and proves Stokes' theorem for surface integrals (see Theorem $16.34$ on page $427$).
$\textbf{Theorem}$ (Theorem $16.34$, [Lee]). Let $M$ be an oriented Riemannian $3$-manifold with or without boundary, and let $S$ be a compact oriented $2$-dimensional smooth submanifold with boundary in $M$. For any smooth vector field $X$ on $M$,
$$
\int_S \langle \text{curl } X,N \rangle_g \:dA = \int_{\partial S}\langle X,T\rangle_g \: ds,
$$
where $N$ is the smooth unit normal vector field along $S$ that determines its orientation, $ds$ is the Riemannian volume form for $\partial S$ (with respect to the metric and orientation induced from $S$), and $T$ is the unique positively oriented unit tangent vector field on $\partial S$.
Answer: In Lang's Real Analysis you'll find Stokes's Theorem stated for a $C^2$ manifold and $C^1$ form $\omega$. He goes on to discuss what to do with singularities.
Although Lang asserts existence of a $C^2$ partition of unity using the $C^2$ hypothesis, a $C^1$ partition of unity suffices. However, as @MatheinBoulomenos pointed out to me in chat, you need a $C^2$ chart in order to be sure that the pullback of the $C^1$ form (bumped off by the $C^1$ partition of unity) is still a $C^1$ form. (Lang is very sloppy about paying attention to details in this regard.) Then it's the usual computation.
Comment: To be more precise about what I am saying, in the formula $\int_Md\omega=\int_{\partial M}\omega$, I would hope that both $M$ and $\omega$ only need to be $C^1$, so that both $d\omega$ and $\varphi^*\omega$ will be continuous forms, where $\varphi$ is a $C^1$ chart. And of course I would hope that we can integrate any continuous forms.
Comment: But do we really need the form to be $C^1$ when we integrate it? What I have in mind is that when we integrate a real-valued function over a compact rectangle, only the continuity of the function suffices for integrability. So I think maybe we can weaken the condition of the manifold to be $C^1$ so that we obtain that the pullback form is merely continuous, while Stokes formula still holds.
Comment: Don't forget that you need to differentiate the form before you integrate over the rectangle!
Comment: Nevermind, I see what happened. By charting $M$ with a function $\varphi$, we may have to exhaust the differentiability of $d\omega$.


How can I add Taxonomy Term to a Node's Breadcrumb?

Question: The Node has attached a single Term.
Current breadcrumbs rendered
[HOME] >> [NODE_TITLE]

Want to render like this.
[HOME] >> [TERM] >> [NODE_TITLE]

Answer: Themers who don't want to use a custom module to implement a BreadcrumbBuilder can change the breadcrumbs in a preprocess hook.
Example how you can add a link before the last link:
function mytheme_preprocess_breadcrumb(&$variables) {
  $breadcrumb = &$variables['breadcrumb'];
  $lastlink = array_pop($breadcrumb);
  array_push($breadcrumb, [
    'text' => 'New Link',
    'url' => '/newlink',
  ]);
  array_push($breadcrumb, $lastlink);
}

If you add a taxonomoy term from a node you would have to add both as cache tags and a cache context on the url to make this work.
Comment: I like your idea to achieve the same. :)
Comment: I've tried to leverage the same, can you please review https://goo.gl/1nmkEU :)
Comment: @RishiKulshreshtha, this looks good, you could add an answer with your code
Answer: We can implement custom breadcrumb either via module or via HOOK_preprocess_breadcrumb.
Via HOOK_preprocess_breadcrumb:
Add this in your YOURTHEME.theme
/**
 * Implements HOOK_preprocess_breadcrumb().
 */
function YOURTHEME_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    $breadcrumb = &$variables['breadcrumb'];
    if (!empty($node->field_tags->entity)) {
      $term_url = $node->field_tags->entity->toLink();
      $node_url = array_pop($breadcrumb);
      array_push($breadcrumb, $term_url);
      array_push($breadcrumb, $node_url);
      // Implementing Cache.
      $variables['#cache']['contexts'][] = "url.path";
      $variables['#cache']['tags'][] = "node:{$node->nid->value}";
    }
  }
}

Via module:
In custom_breadcrumb.module file
<?php

namespace Drupal\custom_breadcrumb;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class Breadcrumbs.
 *
 * @package Drupal\custom_breadcrumb
 */
class Breadcrumbs implements BreadcrumbBuilderInterface {
  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.node.canonical' && $route_match->getParameter('node') instanceof NodeInterface;
  }

  /**
   * {@inheritDoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $node = $route_match->getParameter('node');
    $breadcrumb = new Breadcrumb();

    // By setting a "cache context" to the "url", each requested URL gets it's
    // own cache. This way a single breadcrumb isn't cached for all pages on the
    // site.
    $breadcrumb->addCacheContexts(["url"]);

    // By adding "cache tags" for this specific node, the cache is invalidated
    // when the node is edited.
    $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

    // Add "Home" breadcrumb link.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    // Given we have a taxonomy term reference field named "field_tags" and that
    // field has data, add that term as a breadcrumb link.
    if (!empty($node->field_tags->entity)) {
      $breadcrumb->addLink($node->field_tags->entity->toLink());
    }
    return $breadcrumb;
  }

}

and then in custom_breadcrumb.services.yml
services:
  custom_breadcrumb.breadcrumbs:
    class: Drupal\custom_breadcrumb\Breadcrumbs
    tags:
      - { name: breadcrumb_builder, priority: 100 }

Both the ways are achievable, if your question is which one should be followed and which one should be referred as a best practice, refer https://drupal.stackexchange.com/a/238962/3808
Answer: A slightly more parametrized theme code example for non-node entities with taxonomy parents, made by combining Rishi Kulshreshtha's code with taxonomy parents addition by mfrosch
/**
 * Implements hook_system_breadcrumb_alter().
 */
function THEMENAME_preprocess_breadcrumb(array &$vars) {
  // proper taxonomy breadcrumbs for Commerce Products through field_category
  $entity_type = 'commerce_product'; // TODO: change or verify
  $taxonomy_field_name = 'field_category'; // TODO: change or verify

  if (($entity = \Drupal::routeMatch()->getParameter($entity_type)) && $vars['breadcrumb']) {
    $cache_tag = "{$entity_type}:{$entity->product_id->value}"; // TODO: change or verify

    $breadcrumb = &$vars['breadcrumb'];
    if (!empty($entity->$taxonomy_field_name->entity)) {
      $node_url = array_pop($breadcrumb);

      $term = $entity->$taxonomy_field_name->entity;
      $storage = \Drupal::service('entity_type.manager')
        ->getStorage('taxonomy_term');
      $parents = $storage->loadParents($term->id());
      if (!empty($parents)) {
        foreach ($parents as $index => $parent) {
          array_push($breadcrumb, $parent->toLink());
        }
      }
      array_push($breadcrumb, $term->toLink());

      array_push($breadcrumb, $node_url);

      // Implementing Cache.
      $vars['#cache']['contexts'][] = "url.path";
      $vars['#cache']['tags'][] = $cache_tag;
    }
  }
}

Answer: Yes @No Sssweat is right. I think you need to built a custom module for this.
Add Taxonomy Term to a Node's Breadcrumb in Drupal 8
Answer: Taking a quick peek in contrib modules, as of this writting, there doesn't seem anything that you can use for D8.
Here is a creative quick and easy solution/suggestion:
With Views and bit of Rewrite Results/Template file + CSS you could create your own breadcrumbs view block.


Batch operations: callback_batch_operation() not invoked

Question: I have a batch process where the callback_batch_operation() functions are never called, as showed when logging with some Devel dd() calls.
Here is the involved code fundamental parts (all this in the same multilang.admin.inc file):
function multilang_default_form_submit($form, &$form_state) {
  $operations = array();
  if ($categories = $form_state['values']['default']) {
    foreach ($categories as $category) {
      if ($category) {
        $operations[] = array('multilang_default_process', $category);
      }
    }
  }
  $batch = array(
    'title' => '...',
    'init_message' => '...',
    'operations' => $operations,
    'finished' => 'multilang_default_finished',
    'file' => drupal_get_path('module', 'multilang') . '/multilang.admin.inc',
  );
  dd($batch, '$batch'); ## log
  batch_set($batch);
}

function multilang_default_process($category, &$context) {
  dd(func_get_args(), 'default_process'); ## log
  // ...do the desired job...
}

function multilang_default_finished($success, $results, $operations) {
  dd(func_get_args(), 'multilang_default_finished() args'); ## log
  // ...send appropriate messages...
}

And here is the log result, in a case where only one operation was required:
$batch: Array
(
    [title] => Resetting Multilang configuration
    [operations] => Array
        (
            [0] => Array
                (
                    [0] => multilang_default_process
                    [1] => multilang_exclude_paths
                )

        )
    [finished] => multilang_default_finished
    [file] => sites/all/modules/multilang/multilang.admin.inc
)

default_finished: Array
(
    [0] => 1
    [1] => Array
        (
        )
    [2] => Array
        (
        )
    [3] => 0 sec
)

The above log shows that the multilang_default_process() function is not called, though correctly stated as callback_batch_operation in $batch.
Obviously the first suspicion after the function's correct spelling, goes to its localization through the file index in $batch.
But not only I multiple checked it, but also we can notice that the default_finished() function gets called, while it is localized through the same file index.
This is also ensured by the fact that, if I intentionally set file to another, incorrect value, then the default_finished() function is not called.
Another puzzling thing (at least at my eyes) is the default_finished() passed arguments: despite no callback_batch_operation was called, $success (index 0) is set to TRUE and (remaining to process) $operations (index 2) is empty.
Am I missing (like it happens too often :-) something stupidly obvious...?
Answer: Yes, it was stupidly obvious!
When bulding my $operations I wrote
$operations[] = array('multilang_default_process', $category);
while according to the batch_set() documentation it should be
$operations[] = array('multilang_default_process', array($category));
Sigh...


How to add 'matplotlib' to readthedocs.yaml or requirements.txt?

Question: The scene:

wrote my own python package
used sphinx to create documentation for said package
I'm now trying to upload said documentation to readthedocs

The problem:
When I try to build the documentation, I end up with an error ModuleNotFoundError: No module named 'matplotlib'. I spent about two hours trying to figure out how to fix this, and I've added my .readthedocs.yaml and requirements.txt files, but I just copied what was on the readthedocs website, I can't find anything about how to add additional Python packages to these files (specifically what text I use to do so). I mean, everything says you can, and that you can add via the config or the yaml or through conda, but no example text. I really just need a simple example: "to add matplotlib module, add foo text to requirements.txt" or something like it
I'm sure it's a really simple obvious answer to people who work with this all the time, but this is my first time trying to publish documentation. Can anyone help?
Comment: I don't understand - you can open `requirements.txt` in any text editor and add text manually. And `.readthedocs.yaml` is also normal text file so you can open it in any text editor.
Comment: @furas Yes, I understand that part. What I'm saying is I don't know what text to add.
Comment: did you open `requirements.txt` in text editor? It should explain everything. You need new line with at least text `matplotlib` - and it will install the newest version. If you need some special version then you need `matplotlib==version` or `matplotlib>=version` if you need `version` or newer.
Answer: Check the version of matplotlib that your package depends on like so:
>>> import matplotlib
>>> matplotlib.__version__
'3.3.4'

The format for requirements.txt is like packagename==version, so you should add the following line:
matplotlib==3.3.4

If using a Linux command-line, you can also do it this way:
$ pip freeze | grep matplotlib
matplotlib==3.3.4

If working in a virtual environment where only the required packages are installed, you don't even need to do this by hand for each package; since pip freeze generates output in the correct format, you can just save the output of pip freeze to generate your whole requirements.txt file (see this Q&A for more details):
$ pip freeze > requirements.txt


(OMNeT++) Why PacketQueue is always 0?

Question: I'm trying to code in OMNeT++ an app that gets the queue length from the node where it is invoked and sends it to another node.
The plan is to modify the UdpBasicApp.cc file invoked in a router and make it get the length of the queue of the DropTailQueue module.
Searching online I found that this is the right method...
cModule *mod = getModuleByPath("router3.eth[*].mac.queue");
queueing::PacketQueue *queue = check_and_cast<queueing::PacketQueue*>(mod);
int c = queue->getNumPackets();
EV << c;

...since the DropTailQueue extends the PacketQueue module.
I put a print at the end to see if there was something wrong.
When I run the simulation, using the modified UdpBasicApp module, c is always 0.
I hardly doubt that the queue is always 0, but I don't know how to verify this doubt.
If it's an error, why is it always 0?
Comment: When do you check the size of the queue?
Comment: In the .ini file I set the sendInterval parameter to 2 seconds (2s). I put the code showed in the question in the sendPacket() function of the UdpBasicApp.cc file, before everything else, so everytime a packet is to be sent by the UdpBasicApp the value of int c is updated. Now that I think about it, I'm not sure if I have to delete the pointers and the int at the end of the sendPacket() function
Comment: However this is only a preliminary stage to see how it works. The next step is to create a message where I invoke the getNumPackets() using the code above, and then modify the sendPackets() function in the UdpBasicApp.cc file to send the newly created message.
Comment: A moment ago I added this line of code:

int d = queue->getMaxNumPackets();
EV << d

and the simulation shows the right number that I set as max queue capacity. So I don't know why I don't get the right value for the queue length moment by moment.
Answer: My guess is, that you are querying a different queue than you assume. You should not use patterns (i.e. *) in your model path, because that may match on multiple eth modules, and it's unspecified, which one will be returned.

(OMNeT++) Why PacketQueue is always 0?


Newton's method with Hessian Matrix

Question: Let's say we want to use Newton's method to find optimal $x_*$ for $f:\mathbb{R}^n \to \mathbb{R}$ , with
$x_{t+1} = x_t + H_f(x_t)^{-1}\nabla f(x_t) $
Can $H_f(x_t)^{-1}$ be calculated only once and used in every iteration step, or do we need to calculate it every time?
Does equation $H_f(x_0)(x_*-x_0) = \nabla f(x_0)$ need to be calculated only once to recieve optimal value?
Answer: "Can $H_f(x_t)^{−1}$ be calculated only once and used in every iteration step, or do we need to calculate it every time?"
No, the equation
$$
H_f(x_t)(x_{t+1} - x_t) = - \nabla f(x_t)
$$
needs to be solved at every iteration. This is the reason every iteration in Newton's method is costly compared to other methods with slower convergence. The exception is the quadratic problem
$$
\min f(x) , \quad f(x) = \frac{1}{2}x^T A x + b^T x
$$
with $\nabla f(x) = A x + b$ and $H_f(x) = A$. This problem is exactly solved by one step of Newton's.
$$
\begin{align} A(x_1 - x_0) &= - A x_0 - b \\
x_1 &= -A^{-1}b
\end{align}
$$
for which we see that $\nabla f(x_1) = 0$. Provided that $A$ is positive semidefinite this is a solution to $\min f(x)$.

Newton's method with Hessian Matrix


Como fazer o input() parar apos o espaço em vez da quebra de linha em Python3

Question: Estou querendo capturar vários numeros nesse formado:
2 4 5 3 5 0 4

Como quantidade de números indefinido e sem usar uma lista auxiliar, quero usar apenas uma variável
for _ in range(0,n):
    num = int(input())

Sei apenas criando lista
for _ in range(0,q):
    lista +=[int(input().split(' '))]

Comment: Mas se os numeros estão no formato `2 4 5 3 5 0 4 ` então `num = int(input())` nunca irá funcionar. O próprio `split` que tem na pergunta já devolve uma lista . Qual é exatamente a duvida ?
Answer: Realmente a pergunta está confusa mas se a lista é "infinita", basta ler uma linha inteira e depois separar os elementos:
#!/usr/bin/python3

# recebe cada número de uma só vez.
print('Digite a lista de números separada por espaços, <Enter> finaliza')
entrada = input('=> ')

# separa a string por espaços e converte em uma lista de inteiros.
lista = [ int(i) for i in entrada.split(' ') ]

# imprime a lista, apenas para referência.
print(lista)

Comment: se tiver um espaço no começo da entrada, como está na pergunta, esse código quebra -  tem que coloca um filtro "`...if i`` na list-comprehension.
Answer: É uma pergunta extremamente confusa e pelo pouco que entendi você quer que ao encontrar um valor " " o sistema pare, se não for corrija a pergunta. De qualquer modo segue a solução para o que eu disse:
import sys

lista = int(input("Digite a lista"))
newLista = lista.split(' ')

for i in newLista:
    if(i == " "): #Identifica o " "
        sys.exit() #O sistema irá parar

Se quiser separar cada termo da lista, terá que utilizar outro .split() e outro marcador. Os dados de entrada devem conter tal marcador.
Answer: Pelo que entendi, você deseja capturar todos os valores digitados em uma só linha. Ou seja, você gostaria de implementar um programa que ao solicitar a digitação dos valores, o usuário fosse capaz de digita-los em uma só linha.
De acordo com o meu entendimento o algoritmo ficaria...
valores = list(map(int, input('Digite os valores: ').split()))
print(f'\033[32mValores digitados: {valores}\033[m')

Observe o funcionamento do algoritmo no repl.it.
Observe que para utilizar corretamente este algoritmo, você tem que:

Executar o algoritmo;
Digitar todos os valores na mesma linha separados por um espaço;
Pressionar Enter.

Observe também, que este algoritmo é capaz de capturar um número indefinido de valores.


How to turn off buffering in IIS for MVC 4 Web API application

Question: I have a MVC 4 Web API application running on IIS 7. To analyse why the application is slow, I tried profiling the application and found no major bottlenecks. Apparently, the response is getting buffered and the wait time before flush is causing the delay. I learnt that there a setting - aspBufferingOn which can be set to false in IIS to disable buffering. Documentation says that this setting should be available under "ASP" feature in IIS Manager's Feature view. But I dont see a feature by name "ASP" there.

Where can I set the value of "aspBufferOn" setting for my Web API application in IIS Manager?
Comment: Web API's (WebHost) buffer policy is driven by `WebHostBufferPolicySelector`...what is your scenario? Are you trying to download a large file or something else?
Comment: My application exposes methods that return objects. ie HTTPResponseMessage contains object of type ObjectContent. The ContentLength property is null. Could not find a reliable way to compute the length of the object (as length could vary by encoding used) and TrygetContentLength() exposed by the object returns false/-1, so decided to turn off buffering in IIS
Comment: @Kiran Wouldn't turning off aspBufferingOn parameter in IIS solve the problem? If it wont, how do I use the WebHostBufferPolicySelector to turn off buffering?
Comment: By default `ObjectContent` is buffered to catch any serialization errors and embed this error info in the response msg. If `ObjectContent` is non-buffered, then you would loose this capability and in case of any serialization errors, the client would just see a disconnection. Why do you want to switch off buffering, is your object huge and consuming lot of memory? You can override the default implementation of `WebHostBufferPolicySelector`'s `UserBufferedOutputStream` method to conditionally buffer/non-buffer for specific requests..however please keep in mind of the above scenario
Answer: See Filip W answer first: https://stackoverflow.com/a/14906901/1241400
Regarding to your ASP feature question
You need to go to Start then in search type Turn Windows Features on or off and enable it.

Reference: ASP Limits
More on AspBufferingOn

This property specifies whether output from an ASP application will be
  buffered. If the value is TRUE (default), all output from the
  application is collected in the buffer before the buffer is flushed to
  the client browser. If this property is set to FALSE, output from ASP
  scripts will be written to client browser as it becomes available.
With buffering on, the ASP application will have to completely process
  the ASP script before any output is received by the client browser.
  For this reason, applications for which buffering has been turned on
  could seem slower to users than those applications for which buffering
  is turned off, even though the total time taken for the buffered
  script is less. Therefore, if buffering is turned on, you should
  consider using the Response.Flush method to pass the user pieces of
  content as the script is being processed.
Note   If buffering is turned off, any methods that modify existing
  HTTP headers, or generate new headers, must be executed before the
  content body is sent to the client browser. If buffering is turned on,
  this restriction is unnecessary.
Important   If you installed IIS 5.0 by upgrading from a previous
  version of IIS, the default setting for this property will be FALSE,
  not TRUE.

Data type    Boolean
Default value    TRUE
Inheritance  Inheritable


Facebook API for iPhone Error: An active access token must be used

Question: I am trying to retrieve my online friends and I am getting this error:

"An active access token must be used to query information about the current user."

This is my method:
<code>-(IBAction)act:(id)sender{

    NSArray* permissions =  [[NSArray arrayWithObjects:
                              @"user_online_presence", @"friends_online_presence", nil] retain];

    [facebook authorize:permissions delegate:self];
    [facebook requestWithGraphPath:@"me/friends" andDelegate:self];

    NSLog(@"dd");
    NSLog(@"%@",facebook.accessToken);
}
</code>
What I am doing wrong here?
Answer: you are not waiting for the authorization to complete.
You will need to implement the didLogin delegate method, and
[facebook requestWithGraphPath:@"me/friends" andDelegate:self];
should go only after didLogin was called.
Comment: how is the structure of didlogin? for example for didfailwitherror is this one: - (void)request:(FBRequest*)request didFailWithError:(id)result {
Comment: -(void)fbDidLogin;
And it's on FBSessionDelegate (who's also in Facebook.h)
Comment: I have tried this one on my .m but is not working! I am using the last version of FBconnect. -(void)fbDidLogin{

    [facebook requestWithGraphPath:@"me/friends" andDelegate:self];
    NSLog(@"did login");

}
Comment: It works for me
Looking back at your code, you are using
[facebook authorize:permissions delegate:self]

in my code i have
[facebook authorize:my_facebook_app_id permissions:permissions delegate:self]

Do you provide your facebook app id elsewhere?
Comment: Yeah! The pop up window ask me if I want to authorize and blah blah. Everything works fine except this! Here is my app id:- (void)viewDidLoad
{
    [super viewDidLoad];

    facebook = [[Facebook alloc] initWithAppId:@"xxxxxxxx"];
    [facebook authorize:nil delegate:self];
Comment: Something i forgot to mention is that I am doing all these procedures in my appViewController.m! Is ok with that right?
Comment: It should, you can also implement -(void)fbDidNotLogin:(BOOL)cancelled to check if it falls there.


How to make FragmentStatePagerAdapter from ViewPager fragment and ViewPagerAdapter

Question: I have a ViewPager fragment and a ViewPagerAdapter and I want to make a FragmentStatePagerAdapter.
So I searched everywhere but I can't find any good solutions.
Can someone help me to make a FragmentStatePagerAdapter of my ViewPagerfragment and my ViewPagerAdapter.

ViewPager fragment
public class ViewPage extends Fragment {

    // Declare Variables
    ViewPager viewPager;
    ViewPagerAdapter adapter;
    Uebung.SessionItemAdapter adapter2;
    String[] Titel;
    ImageButton btnswipeview;

    List<String> data = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from viewpager_main.xml
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View layout = inflater.inflate(R.layout.viewpage, container, false);

        ArrayList<String> strtext=getArguments().getStringArrayList("key");
        String frnames[]=strtext.toArray(new String[strtext.size()]);
        Titel = frnames;

        // Locate the ViewPager in viewpager_main.xml
        viewPager = (ViewPager) layout.findViewById(R.id.viewPager);
        // Pass results to ViewPagerAdapter Class
        adapter = new ViewPagerAdapter(getActivity(), Titel);
        // Binds the Adapter to the ViewPager
        viewPager.setAdapter(adapter);

        return layout;
    }

ViewPagerAdapter
public class ViewPagerAdapter extends PagerAdapter {
    // Declare Variables
    Context context;
    String[] Titel;
    ArrayList<String> listItems;

    ArrayAdapter<String> adapter;

    List<String> data = new ArrayList<String>();

   // int[] images;
    LayoutInflater inflater;

    private static final Map<String, Integer> TITLE_IMAGES =
            new HashMap<String, Integer>();
    static {
        TITLE_IMAGES.put("Arme", R.drawable.ic_launcher);
        TITLE_IMAGES.put("Bauch", R.drawable.ic_launcher2);
    }

    public ViewPagerAdapter(Context context, String[] Titel) {
        this.context = context;

        this. Titel = Titel;
       // this.images = images;
    }

    @Override
    public int getCount() {
        return Titel.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        // Declare Variables
        TextView txtTitel;

        ImageView image;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.swipeview, container,
                false);

        // Locate the TextViews in viewpager_item.xml
        txtTitel = (TextView) itemView.findViewById(R.id.swipeviewtitle);

        // Capture position and set to the TextViews
        txtTitel.setText(Titel[position]);

        // Locate the ImageView in viewpager_item.xml
        image = (ImageView) itemView.findViewById(R.id.swipeViewimage);
        // Capture position and set to the ImageView

        String title = Titel[position];
        Integer imageRes = TITLE_IMAGES.get(title);
        if (imageRes == null) { // not found in map
            image.setImageResource(0);
        } else {
            image.setImageResource(imageRes);
        }

        // Add viewpager_item.xml to ViewPager
        ((ViewPager) container).addView(itemView);

        final ListView listView = (ListView) itemView.findViewById(R.id.listViewswipeview);
        final EditText editText = (EditText) itemView.findViewById(R.id.editTextswipeView);

        Button btnswipeview = (Button) itemView.findViewById(R.id.imagebuttonswipeview);

        listItems = new ArrayList<String>();

        listItems.add("First Item - added on Activity Create");

        adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, listItems);

        listView.setAdapter(adapter);

        btnswipeview.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View View) {
                Toast toast = Toast.makeText(context,
                        "You clicked the button",
                        Toast.LENGTH_SHORT);
                toast.show();

                listItems.add(editText.getText().toString());
                adapter.notifyDataSetChanged();
            }
        });

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Remove viewpager_item.xml from ViewPager
        ((ViewPager) container).removeView((LinearLayout) object);

    }

}

swipeview.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_weight="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Titel"
        android:textSize="15pt"
        android:id="@+id/swipeviewtitle"
        android:layout_gravity="center_horizontal" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/swipeViewimage"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/ic_launcher"/>
</LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:ems="10"
            android:id="@+id/editTextswipeView"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imagebuttonswipeview"
            android:src="@drawable/ic_menu_add"/>

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:ems="10"
            android:id="@+id/editText2"
            android:layout_weight="1" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <ListView
            android:layout_margin="5dp"
            android:id="@+id/listViewswipeview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:clickable="true"
            android:drawSelectorOnTop="true"
            android:focusable="true"
            android:choiceMode="singleChoice"/>

        </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Spinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/spinnerswipeview"

            android:entries="@array/day"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1" />
        </LinearLayout>

</LinearLayout>

It would be nice if someone edit the code to a FragmentStatePAgerAdapter or would me explain how I must edit it.
Thanks in advance.
Answer: FragmentStatePagerAdapter is a child class of PagerAdapter, so you need to make your ViewPagerAdapter class extend directly from FragmentStatePagerAdapter, not from PagerAdapter.
Answer: What you have done here is very complex.
For FragmentStatePagerAdapter you should use FragmentStatePagerAdapter instead of PagerAdapter.


How many lags to include? (Temperature data set)

Question: I have a time series of daily temperature with autocorrelation that looks like this:

Of course, temperature is heavily autocorrelated. When looking at the partial autocorrelation plot, lags are significant up to the 15th lag.

But now I want to use this data as input for a regression model of a dependent variable y (perhaps something like heating), and I am wondering how many lagged values of temperature I should add.
$\text{heating}=c+\beta_0T_{today}+\beta_1T_{yesterday}+...$
Should I add all fifteen of them? It seems a little much. Especially since I don't think the temperature of fifteen days ago will influence the amount of heating done today very much.
Answer: I will provide an explanation of how I would go about deciding the number of lag points to consider.  This is exploratory in nature, it assumes that you do not have a justification (hypothesis/assumption) directing you to a specific number, and above all is, it is arbitrary.  (But, the final choice for any number of lag variables would be arbitrary anyways.)
I would start with a random subset of the data, and I would run a number of models increasing the number of lag points for each model.  Once I have determined when the additional lag points stopped reaching significance in the model, I would check to see if the final number of lag points all reach significance as predictors in a model with a different random subset of the data.  (If I were feeling extra-adventurous, I might even draw multiple samples at each step to build more evidence on how many lags to consider.)
Then I would run the model with the entire data set.  As justification that a reasonable number of lag variables have been included, the model parameter estimates should not change that dramatically if you add or subtract one of the lags.
I'm certain there are more sophisticated methods that can be employed, and I  am hoping other contributors will offer other responses explaining those protocols.
Comment: Thanks for your explanation! I asked this question indeed with the situation of no assumptions in mind. I guess I was mostly wondering how to deal with the trade-off between including all lags, removing any autocorrelation, and preventing overfitting?


Instancia de servidor restuful no tomcat

Question: Pessoal desenvolvi um aplicativo - https://play.google.com/store/apps/details?id=br.com.apprioconcurso
Estou utilizando um servidor restfull conexão com o banco postgree em hibernate.
Esse servidor esta hospedado no bitname em um tomcat, porém algumas vezes por algum motivo ele cai e é necessário reiniciar o servidor manualmente, existe algum outro jeito de fazer isso? Eu preciso ter dois servidores caso um caia eu chamo o outro? como funciona esse processo final para deixar meu servidor sempre startado?
Answer: Se possuir acesso ao cron de sua nuvem, uma forma muito comum de fazer o que você quer é usar um script Watchdog.
Ele consiste em ficar checando de tempo em tempo se um serviço ou programa está em execução e caso negativo executa um comando de inicialização.
Para isso se faz uso do agendador (em Linux é o Cron) com um intervalo de tempo aceitável que o sistema a ser monitorado fique fora. Geralmente usa-se o tempo médio que o serviço leva para "parar + iniciar".
Abaixo um script exemplo que serve para muitos serviços.
Basicamente você indica ao script qual serviço monitorar, qual o comando para iniciar o serviço, endereços de e-mail para alertas e caminhos para alguns binários
Supondo que salve o script no seu $HOME com o nome de watchdog.sh, , dê permissão de execução com chmod +x $HOME/watchdog.sh", edite sua crontable com contrab -e
e adicione uma linha como essa
*/5 * * * *  $HOME/watchdog.sh

Indicando que será verificado a cada 5 minutos
Segue um script de Watchdog
#!/bin/bash

NAME=tomcat
START=`which $NAME`
STARTCMD="$START + _ARGUMENTOS_"
NOTIFY=EMAIL1
NOTIFYCC=EMAIL2
GREP=`which grep`
PS=`which ps`
NOP=`which true`
DATE=`which date`
MAIL=`which mail` # ou sendmail dependendo da distro
RM=`which rm`

# $PS -ax|$GREP -v grep|$GREP $NAME >/dev/null 2>&1 # Caso tenha problema com serviço que roda com um usuario que roda muitos serviços
$PS -efx|$GREP -v grep|$GREP $NAME >/dev/null 2>&1
case "$?" in
   0)
   # Em execução, não fazer nada.
   $NOP
   ;;
   1)
   echo "$NAME NÃO ESTÁ EM EXECUÇÃO. INICIANDO $NAME E ENVIANDO AVISOS."
   $STARTCMD 2>&1 >/dev/null &
   mkdir -p "$HOME/tmp"
   NOTICE="$HOME/tmp/watchdog.txt"
   echo "$NAME não estava executando e foi iniciado em `$DATE`" > $NOTICE
   $MAIL -n -s "Aviso Watchdog" -c $NOTIFYCC $NOTIFY < $NOTICE
   $RM -f $NOTICE
   ;;
esac

exit

Answer: Você pode usar o Nagios para monitorar seu servidor, e com alguns parâmetros reiniciar seu servidor de forma automatizada. Mas recomendo que você investigue seu servidor e tente achar algum padrão para você configurar uma monitoração mais assertiva no Nagios.
Segue um ponto de partida:
Nagios tutorial Ubuntu


Manter efeito final do Animation css

Question: Estou fazendo uma tela de loading e no final do efeito, o valor de css que deve ser mantido, é o valor que está no 100% do animation, só que quando o efeito termina, ele volta ao css inicial.
Como faço para executar o efeito e manter o valor que está no 100%?
Css:
.loading_home_logo {
  position: absolute;
  right: 0px;
  top: -70px;
  animation: move-logo 4s;
}
@keyframes move-logo {
  0% {
    right: inherit;
    top: -10vh
  }
  50% {
    top: -40vh;
    left: 50%;
  }
  100% {
    top: -50vh;
    right: inherit;
    left: 0;
  }
}

Answer: Vc tem que usar o animation-fill-mode para parar a animação no final. No caso seria esse propriedade com o valor forwards, seria assim: animation-fill-mode:forwards
Consulte aqui as opções: https://developer.mozilla.org/pt-BR/docs/Web/CSS/animation-fill-mode
Segue um exemplo sismples pra vc entender. Veja que no final o elemento não volta para o início, mas a animação só acontece uma vez... se vc quiser que ela se repita use a propriedade animation-iteration-count https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count

.loading_home_logo {
    width: 100px;
    height: 100px;
  position: absolute;
  left: 0;
  top: 0;
  background-color: red;
  animation: move-logo 2s;
  /* animation-iteration-count: 3; */
  animation-fill-mode: forwards;
}
@keyframes move-logo {
    0% {
        left: 0;
        background-color: red;
    }
    100% {
        left: 200px;
        background-color: blue;
    }
}

123

Manter efeito final do Animation css


Drush backup of multisite platform

Question: Is there Drush command that can backup whole multisite platform:

database dump of each site
code of each site
backup of sites/all or complete core with sites/all
and all that in just ONE tar.gz

There is a archive-dump command which can backup whole platform code and database, but it does that for each site, and omitting other sites from its archive. And that is a problem because if you want to use that backup, and let's say you have 3 sites in platform, you would have to untar 3 backups of each site, and then merge those so your /sites folder has all three sites there, instead only one per archive.
Second, less annoying problem with that command is, if you provide it argument @sites, it will try to backup default site as well, which is not used on Aegir.
Answer: You can try drush archive-dump default,example.com,foo.com command to archive the DB and codebase. If it is not possibel through it, then you can create a shell script, which creates backup of the codebase and database.
Comment: Thanks, but I already said above that archive-dump doesn't do the job, and explained why. It makes backup of particular site and core, omitting all other sites from /sites
Comment: I just tried with drush 8 and it creates ONE tar archive containing the files from the specified sites ... and the sql dumps.
Comment: First I thought it might be the way how it saves in Drupal 7 (unlike you mentioned as single tar in D8), but it turned out to be that if you just pas argument @sites, it will make for each site. But if you pass list of sites without default, then it will again save two tars. Only if you pass exactly like you wrote, with default, it works. On Aegir default is not used but I can put there commented out settings.php (actuall default.settings.php copied as settings.php) and it works. Many thanks!

Drush backup of multisite platform


When to use ridge estimator / naive Bayes

Question: I used the Logistic function in weka, to predict a binary class. I have used SimpleLogistic before, but Logistic also seem to give me good results. I did want to clarify if I understand some things well on this classifier, pecially about the ridge estimator
Logistic does multinomial logistic regression with a ridge estimator.

multinomial means for more then binary classes as well. So it would appear I didn't really need this function
ridge estimator: I have been reading about this, but it is hard to summarise in one sentence. When attributes are highly correlated this might seem a good technique because XXt becomes close the zero otherwise. Is this correct? Do you have a better explanation in a few sentences?
If my interpretation of ridge is correct. It seems to be valid in exactly the opposite case as when you should use Naive Bayes, because this assumes independent variables.

Thanks for validating and providing a short explanation of ridge (which I don't fully get)
Answer: Ridge is a regularization technique. In simple words, adding ridge to Logistic Regression means that you want to make a model that is not overfitting with the training data and hopefully generalizes well in the test data. It is done by adding penalty on weights learned. This way, the learner will try to find the weights that are close to zero and not the weights that try to fit every training points.
Binomial is a special case of Multinomial distribution (when N=2). So, your multinomial logistic regression can also handle the binary case well.


Executar comando SELECT em banco de dados Firebird com JavaScript

Question: Olá, fiz um código pra executar um select em um banco de dados firebird usando javascript, com a biblioteca node-firebird, o código é esse:
firebird.attach(options, (err, db) => {
if (err)
    throw err

db.sequentially(sentence, (row, index) => {
    console.log(row)
}, (err) => {
    db.detach()
})

})
o problema é que o resultado desse row, que eu acredito que deveria ser os dados da tabela vem assim:
{
  CLIENTE: <Buffer 30 30 30 30 37 37>,
  NOME: <Buffer 4d 4f 4e 54 45 53 20 43 4c 41 52 4f 53>,
  RAZAO: <Buffer 4e 41 59 41 52 41 20 46 45 52 52 45 49 52 41 20 52 41 42 45 4c 4f>,
  ENDERECO: <Buffer 52 55 41 20 42 20 39 31>,
  BAIRRO: <Buffer 52 41 55 4c 20 4c 4f 55 52 45 4e c7 4f>,
  ESTADO: <Buffer 4d 47>,
  VENDEDOR: <Buffer 30 30 30 30 30 32>
}

Como pegar os dados de fato ao invés desses "Buffers" ?
Answer: O sequentially é para leituras sequenciais.
Você também deve chamar o next(). Um simples JSON.stringify() deve resolver. Sendo assim, seu código ficaria:
firebird.attach(options, (err, db) => {
if (err)
    throw err

db.sequentially(sentence, (row, index, next) => {
    console.log(JSON.stringify(row));
    next();
}, (err) => {
    db.detach()
})

Se não está trabalhando com streaming/big data, recomendo trocar o sequentially pelo simples query. Dessa forma, seu código ficaria quase o mesmo, apenas trocando para o query:
firebird.attach(options, (err, db) => {
if (err)
    throw err

db.query(sentence, (err, result) => {
    console.log(result)
    db.detach()

})

Answer: Estou com o mesmo problema, mas inserindo o código que Victor mencionou acima também não funciona.
firebird.attach(options, (err, db) => {
if (err)
    throw err

db.query(sentence, (err, result) => {
    console.log(result)
    db.detach()

})

Minha duvida.
Consulta retornando buffer somente no firebird com Node


ChartJS gráfico pie ou pizza exibir porcentagem

Question: Utilizando a lib Chartjs(http://www.chartjs.org/) Há alguma forma simples, de fazer um gráfico do tipo "pie", exibir a porcentagem de cada cor, ou pelo menos permitir a inserção do caractere "%" após exibir o número no "tooltip", pois nesse caso, posso calcular as porcentagens antes de renderizar os gráficos.
Segue o código utilizado até o momento:
    var data = [
        {
            value: 83,
            color: "#2DB45C",
            highlight: "#FF5A5E",
            label: "Masculino"
        },
        {
            value: 181,
            color: "#46BFBD",
            highlight: "#5AD3D1",
            label: "Feminino"
        }
    ];

 var pie = new Chart(document.getElementById("pie-chart").getContext("2d")).Pie(data, {});

Ao passar o mouse, na área de cada cor, ele exibe o número passado no parâmetro "value", no array de "configuração". Como já mencionei, posso facilmente transformar esse valor em uma porcentagem, mas a falta do caracter(%) vai tornar mais difícil para o usuário entender quer aquilo é uma porcentagem. Ah alguma solução nesse caso? Ou podem me sugerir alguma outra lib gratuita, que faça +- o mesmo que esta, porem sem essas "limitações".
Answer: Podes passar à função construtora do gráfico uma mudança à maneira como o conteúdo da ToolTip é gerado. Isto está documentado aqui, e na prática é passar uma string para ser interpretada como JS. Neste caso concatenei simplesmente o valor com a string "%":
tooltipTemplate: '<%= value + "%" %>'

O JavaScript poderia ser assim:
var el = document.getElementById("pie-chart").getContext("2d");
var pie = new Chart(el).Pie(data, {
  tooltipTemplate: '<%= value + "%" %>'
});

jsFiddle: http://jsfiddle.net/m2brxya8/