how to put pandas functions in list and run it all?

Question: from itertools import cobminations as combi

# this code doesn't work.
for func1, func2 in combi([pd.DataFrame.count,pd.DataFrame.min,
                           pd.DataFrame.max, pd.DataFrame.std,
                           pd.DataFrame.var, pd.DataFrame.mean]):
   x = df.col1.func1()
   y = df.col1.func2()
   ax = fig.add_subplot(8, 2, counter)
   ax.scatter(x,y)

this code doesn't work, because the func1&func2 is not the right name to call functions.
How Can I loop in pandas functions list? and how can call it?
Comment: You probably want to use `agg`
Answer: To answer the direct question, you can pass a dataframe to all the functions you created here, so this code runs:
import pandas as pd
from itertools import combinations

for func1, func2 in combinations([pd.DataFrame.count,pd.DataFrame.min,
                           pd.DataFrame.max, pd.DataFrame.std,
                           pd.DataFrame.var, pd.DataFrame.mean], 2):
    x = func1(df).col1
    y = func2(df).col1

But there are a few problems: we're recalculating these things multiple times, and in this method if we have many columns in df, the functions will be applied to those as well. So you could also use the pd.Series version of the functions and pass through the column, like this:
for func1, func2 in combinations([pd.Series.count,pd.Series.min,
                           pd.Series.max, pd.Series.std,
                           pd.Series.var, pd.Series.mean], 2):
    x = func1(df.col1)
    y = func2(df.col1)

It's much better to calculate these aggregates with .agg:
aggs = df.col1.agg(['count', 'min', 'max', 'std', 'var', 'mean'])

Now we can use strings access them:
for func1, func2 in combinations(aggs.index, 2):
    x = aggs[func1]
    y = aggs[func2]

Answer: Why don't you do a list with the function results? Like, you could do a nested function and apply all the functions you want from numpy/pandas and assign a value. Make a list from those values and assign another list/tuple/dictionary. I recommend dictionaries, they're easier to wok with, specially with Pandas.
Also i think you cannot iterate like the way you're trying to do. Your functions are missing the "()" in the end of the function and that's not how lists work in a for loop.
ps: Your code has "cobminations" instead of combinations. Maybe i've been wrong all along. hehehehehehhe. You didn't import pandas library as well from what you've shown in your code.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Can I estimate the COX regression using OLS

Question: I am wondering if I can estimate the Cox regression $h(t,z)= h_0(t)exp(\beta_1 z_1+\dots+\beta_x z_x)$ model using OLS. The idea would be to rewrite the model with regards to the structure of a simple linear regression. This would allow me to estimate with OLS: $\log(h(t,z)/h_0(t))$
This would be beneficial for a proof I am working on.
In the case this works, I would be interested in what $h_0(t)$ is. Can we estimate the $h_0(t)$ for human beings?
Answer: There are ways to use linear regressions to model survival, but they aren't what you seem to be expecting from the way your question is worded, and they aren't as generally reliable as maximum (partial) likelihood methods.
First, there is no single "$h_0(t)$ for human beings" that applies in all situations. This page shows a plot of hazard of death as a function of age from birth to age 100 for the US in 2003. But this hazard necessarily represents an average over the population, which would be hard to translate to a hazard function representing the baseline covariate values for your study. Furthermore, many applications of survival analysis don't cover the entire lifespan. For example, survival studies of adult cancer patients would be restricted to the latter parts of the age range. You want to have a baseline $h_0(t)$ that is as specific as possible to the population of interest, estimated from your sample of the population. For example, comparing different cancer treatments would use hazard functions for patients with that particular type of cancer, not hazards for the general population.
Second, the hazard function $h(t)$ is the instantaneous hazard: the risk of an event given that you haven't yet had an event. So at any time $T$ you have to consider the entire history of $h(t)$ up to that time, the cumulative hazard, to get the probability of having already survived that long. So the simple OLS approach you seem to be proposing wouldn't work.
If you have observed all cases having the same set of covariate values until they have events, there are ways to use linear regression to estimate survival characteristics if you assume a functional form for the hazard. You put the cases in order of event times, providing empirical estimates of the quantiles that they represent of the cumulative hazard. You then use the assumed functional form of the cumulative hazard to find a linearizing transformation of the quantile distribution over time, plot the quantiles and corresponding event times for all cases according to that linearization, and estimate the distribution's parameter values for that set of cases from the slope and intercept of a linear fit to the (appropriately transformed) observed values.
Before the age of readily accessible digital computers, this was a standard approach often based on an underlying Weibull distribution, a distribution that handles many situations with either continually increasing, constant, or continually decreasing hazards over time. If you have just a few groups (e.g., treatment and control), you could do separate plots for each group and compare the estimated distribution parameter values among the groups. You can still get graph papers for Weibull and other underlying distributions to generate these plots. But the usual assumptions of OLS aren't likely to be met with these linearizations, so you won't have reliable error estimates for the parameter values. If there are continuous covariates or multiple groups, this approach becomes unwieldy at best. Furthermore, if some cases haven't yet had events you need to take into account the censoring of event times for those cases: all you know is that they survived at least as long as you observed them.
Chapter 8 of the NIST handbook provides examples of linearized plots for survival analysis, but the authors note that maximum likelihood methods are highly preferable when you have an underlying functional hazard form in mind. Cox regression uses maximum partial likelihood to estimate both the entire non-parametric baseline hazard and the relative hazards associated with the covariates.


Evaluate $\int_{-\infty}^0xe^{-4x}dx$

Question: Evaluate $\int_{-\infty}^0xe^{-4x}dx$.
I first did integration by parts. My result is the following:
$\frac{-1}{4}xe^{-4x}-\frac1{16}e^{-4x}$, which I will evaluate from $-\infty$ to $0$ using the fundamental theorem of calculas. The part that gets evaluated at zero is just $\frac{-1}{16}$. I keep having problems figuring out $\lim\limits_{b \to -\infty} \frac{xe^{-4x}}{4}+\frac{e^{-4x}}{16}$. For the first summand, I use L'Hopital's rule and keep ending up with $-\infty$. For the second summand, I get $\infty$. This is a problem because I $-\infty+\infty$ is still indeterminant, and I can't figure out if I'm messing up a sign somewhere.
I know that I can evaluate this by factoring out $e^{-4x}$ from both summands. The final result is $-\infty$. But I want to figure out how to do it without factoring as well.
Comment: It's from $\infty$ to $0$, not from $-\infty$ to $0.$ If it were $-\infty$ to $0$ you would rightly get $-\infty$
Comment: Well, your integral evaluates from $\infty$ to $0$ and not from $-\infty$. This should restore order.
Comment: Sorry, it was supposed to say $-\infty$
Comment: Well then  the integral is $-\infty.$ $e^{-x}$ blows up in that direction.
Answer: The integral $\int_{-\infty}^0 xe^{-4x}\,dx$ does not converge.

The following solution is applicable to the originally posted question.  After this solution was posted, the OP changed the lower limit from $\infty$ to $-\infty$.

Begin by writing
$$\int_{\infty}^0xe^{-4x\,}dx=-\int_0^{\infty}xe^{-4x}\,dx$$
Then, integrating by parts with $u=x$ and $v=-\frac14e^{-4x}$ yields
$$\begin{align}
-\int_0^{\infty}xe^{-4x}\,dx&=-\left.\left(-\frac14 xe^{-4x}\right)\right|_{0}^{\infty}-\frac14\int_0^\infty e^{-4x}\,dx\\\\
&=-\frac14 \int_0^\infty e^{-4x}\,dx\\\\
&-\frac{1}{16}
\end{align}$$
since using L'Hospital's Rule we have
$$\begin{align}
\lim_{x\to \infty}xe^{-4x}&=\lim_{x\to \infty}\frac{x}{e^{4x}}\\\\
&=\lim_{x\to \infty}\frac{1}{4e^{4x}}\\\\
&=0
\end{align}$$

EDIT:
If the lower limit is $-\infty$, then enforcing the substitution $x\to -x$ reveals
$$\int_{-|L|}^0 xe^{-4x}\,dx=-\int_0^{|L|}xe^{4x}\,dx\le -\int_0^{|L|}x\,dx=-\frac12 |L|^2$$
Hence, $\lim_{|L|\to \infty}\int_{-|L|}^0 xe^{-4x}\,dx=-\infty$.  And we are done!
Comment: According to my textbook, the solution should be $-\infty$ though.
Comment: @mmm If the lower limit is $+\infty$, then your answer $-1/16$ is correct.  If the lower limit is $-\infty$, the improper integral diverges (to $-\infty$).
Comment: That's the part I needed clarification on. How can I show analytically that it diverges to $-\infty$?
Comment: @mmm I've edited by adding a section labeled $EDIT$ that proves the limit of the improper integral is $-\infty$.  There is no integration by parts required.
Comment: @mmm Did that suffice?
Answer: Sometimes is useful:
Using $\displaystyle\int pe^xdx=e^x(p-p'+p''-p'''+\cdots)$ where $p$ is a polynomial, we write
$$\frac{1}{16}\int-4xe^{-4x}d(-4x)=\frac{1}{16}\int ue^{u}du=\frac{1}{16}e^u(u-1)=\frac{1}{16}e^{-4x}(-4x-1)$$
Answer: Indefinite integral is $-\exp{(-4x)}\left(\frac{1}{16}+\frac{x}{4}\right)$. Whether it converges or not depends on the bounds.

Evaluate $\int_{-\infty}^0xe^{-4x}dx$


Usar Imagens de fundo diferentes no HTML+CSS

Question: Olá, tenho uma pagina em HTML+CSS e queria colocar Duas imagens diferentes de fundo, Uma pra ser exibida para PC e outra para mobile, como poderia fazer isso? Meu css está assim atualmente, chamando apenas uma imagem (BG.png)
<code>    body{
  font-family: 'Noto Sans TC', sans-serif;
  height: 100vh;
  background-image: url(bg.png);
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  background-color: #007ec7;
}

</code>
Answer: Para fazer isso você pode usar Media Queries, que te permitem aplicar um estilo de acordo com alguns seletores de media, no seu caso, o tamanho da resolução, o que vai te diferenciar de desktop/mobile, por exemplo assim:
<code>/* tamanho até 768px */
@media (max-width:768px) {
    body {
     background-image: url(bg-mobile.png);
    }
}

/* tamanhos maiores que 768px */
@media (min-width:769px) {
   body {
     background-image: url(bg-desktop.png);
   }
}
</code>
Comment: valeeeu, vou fazer aqui, muito obrigado ;)


Standard Errors in OLS models

Question: Assume, we estimate the model
$Y_i = \beta_0 + \beta_1 X_i + u_i$,
with OLS. In the case of homoscedasticity, the standard error of $\widehat{\beta}_1$ can be estimated as
$\sigma_{\widehat{\beta}_1} = \sqrt {\dfrac{\sigma_u^2}{n \sigma^2_X}} = \sqrt{ \dfrac{1}{n} \dfrac{\frac{1}{n-2}\sum_{i=1}^{n}\widehat{u}_i^2}{\frac{1}{n}\sum_{i=1}^n(X_i-\bar{X})^2}}.$
My question: In the enumerator, we use the correction term $n-2$. However, in the denominator, we do not use an equivalent "degrees of freedom correction". Instead, we divide by $n$. What is the intuition that we do not need to correct for degrees of freedom in this second case?
Answer: The $n-2$ occurs because the residuals lose two degrees of freedom due to the estimation of the slope and intercept parameters. For the $X$'s the estimated parameters do not enter in.  However, if you want to use the unbiased estimate for the variance of the $X$'s, $n-1$ should be used in the denominator of the denominator.
Comment: Thanks for your answer! What I do not understand: we also estimate one parameter in the denominator $\bar{X}$. Is this what induces the bias you are referring to?
Comment: Under the usual OLS assumptions, there is no theoretical justification to "use the unbiased estimate for the variance of the X's."  The denominator should be understood geometrically as *the appropriate measure* of the spread of the $X_i$, not statistically as an estimator of anything.

Standard Errors in OLS models


How a second test influences probability of having disease

Question: Suppose the probability to have a certain disease is $P(D)=1/2$.
A patient, after having a medical test, is told by the doctor: "We have results, they are negative (you don't have the disease) at 95%".
I think that means $P(D^\complement|negative \space result)=0.95$.
Now the question:

if I remake the test, and the results are negative which value does the probability $P(D^\complement|(negative \space 1st)\cap(negative \space 2nd))$ assumes?

This is what I try:
Let $D$=disease, and $neg_i$=i test is negative.
$$P(D^c|neg_1 \cap neg_2)=\frac{P(neg_1 \cap neg_2|D^c)P(D^c)}{P(neg_1 \cap neg_2|D^c)P(D^c)+P(neg_1 \cap neg_2|D)P(D)}=\frac{P(neg|D^c)^2}{P(neg|D^c)^2+P(neg|D)^2}$$
And then?
Comment: You need the probabilities that the test is negative twice given the patient has the disease and given the patient does not have the desease. This should be sufficient.
Comment: This is not an exercise taken from a book, I was wondering about it :(
Referring to the exercise I can't see how to do, I'll add in the answer what I'm trying to do
Comment: You can still apply Bayes'rule
Comment: I do it but it seems like I need more information about the test
Comment: I ended exactly with these conclusion. I post the question to see if it was an error in my reasoning. So without those informations is impossible to answer the question?
Comment: Yes, we need them. But it is sufficient to know the probabilities for a single test if we assume independence of the two tests. Which informations do we have in the exercise ?
Answer: $$ \begin{eqnarray*}
P(neg| D^c)=P(D^c | neg)\frac{P(neg)}{P(D^c)}=(0.95)(2)P(neg)
\\P(neg| D)=P(D | neg)\frac{P(neg)}{P(D)}=(0.05)(2)P(neg)
\end{eqnarray*} $$
the factors of $(2)P(neg)$ will cancel, so you are left with.
$$ P(D^c|n_1\cup n_2)=\frac{(0.95)^2}{(0.95)^2+(0.05)^2} \approx 0.99723 $$
This is also what you would get if you recognized that you are either sick or well
so either the test is right both times - $P_{rr}=(0.95)^2$
or the test is wrong both times - $P{ww}=(.05)^2$
So the total probability of the situation described is  $P_{sit}  = P_{rr} + P_{ww}$
And the conditional probability of the test being right both times is
$$ P(D^c|n_1\cup n_2)=\frac{P_{rr}}{P_{sit}  } \approx 0.99723 $$
It is also super close to what you would get if you just said that the probability of the test being wrong both times is $(0.05)^2$ so the probability of being right both times is $1-(0.05)^2=0.9975$


Quero gravar as informações em um .txt em c++

Question: O problema aqui é que ele cria o arquivo 'test.txt' porem quando chega na hora de gravar no arquivo ele não faz nada...
eu ja vi a permissão do arquivo e esta ok...
não entendi alguém poderia me ajudar?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
    int numero;
    string name;
    ofstream outFile;

    outFile.open("c:\\x\\test.txt");
    if (! outFile)
    {
        cout << "erro test.txt" << endl;
        abort();
    }

    cout << "Name: \n"
        << "Fim de arquivo (Ctrl-Z) termina a entrada de dados\n\n? ";
    while(cin >> numero >> name){
        outFile << numero << " " << name<< '\n'; // << Chega aqui ele não faz nada
        cout << "? ";
    }
    outFile.close();
    return 0;
}

Comment: Provavelmente o SO não esta fazendo o flush para o arquivo. Troque `'\n'` por `endl` e verifique se resolve.
Comment: No cout tenta assim || outFile << (numero) << " " << (name)<< "\n"; ||
Comment: da ero quando tento (outFile << (numero) << " " << (name)<< "\n";)
Comment: edita a pergunta e posta o erro
Answer: O problema do seu código é que o sistema operacional não esta realizando o flush dos dados para o arquivo devido ao CTRL+Z.
Para corrigir este problema, basta substituir o '\n' por endl:
outFile << numero << " " << name << endl;

Answer: int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

-------------------------------------------

std::ofstream file;
file.open("filename");
std::string my_string = "Oi qual o seu nome?\n";
file << my_string;
file.close();


Problema ao adicionar um elemento em uma Collection em tempo de execução

Question: Neste meu método devo preencher uma collection, independente de seu tipo
public void loadBeanCollectionItems(B bean, Collection collection, JSONArray collectionJson)
{
    for(int index = 0; index < collectionJson.length(); index++)
    {
        collection.add(getBean(collectionJson.getJSONObject(index)));
    }
}

porém é gerado a seguinte exceção:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
at org.hibernate.collection.internal.AbstractPersistentCollection.write(AbstractPersistentCollection.java:399)
at org.hibernate.collection.internal.PersistentBag.add(PersistentBag.java:314)
at tools.json.AbstractBeanConverter.loadBeanCollectionItems(AbstractBeanConverter.java:224)
at tools.json.AbstractBeanConverter.loadBeanArray(AbstractBeanConverter.java:215)
at tools.json.AbstractBeanConverter.getBeanArray(AbstractBeanConverter.java:194)
at tools.json.AbstractBeanConverter.loadBeanFields(AbstractBeanConverter.java:177)
at tools.json.AbstractBeanConverter.loadBean(AbstractBeanConverter.java:156)
at tools.json.AbstractBeanConverter.getBean(AbstractBeanConverter.java:142)
at tools.json.AbstractBeanConverter.loadBeanFields(AbstractBeanConverter.java:174)
at tools.json.AbstractBeanConverter.loadBean(AbstractBeanConverter.java:156)
at tools.json.AbstractBeanConverter.getBean(AbstractBeanConverter.java:142)
at tools.json.AbstractBeanConverter.loadBeanCollectionItems(AbstractBeanConverter.java:224)
at tools.json.AbstractBeanConverter.loadBeanArray(AbstractBeanConverter.java:215)
at tools.json.AbstractBeanConverter.getBeanArray(AbstractBeanConverter.java:194)
at tools.json.AbstractBeanConverter.loadBeanFields(AbstractBeanConverter.java:177)
at tools.json.AbstractBeanConverter.loadBean(AbstractBeanConverter.java:156)
at tools.json.AbstractBeanConverter.getBean(AbstractBeanConverter.java:142)
at services.StartGame.doPost(StartGame.java:93)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

Nesta pilha de exceções o atalho "AbstractBeanConverter.java:224" faz referencia a seguinte linha deste método:
collection.add(getBean(collectionJson.getJSONObject(index)));

Comment: Pelo jeito tu usa hibernate, pode ser porque tu está inicializando a variável com fetch=lazy, tenta inicializar com fetch=eager. Não vou responder nas respostas pq não tenho certeza, mas pode ser isso, se for eu formato uma resposta certinha.
Answer: Esse é um problema de uso do hibernate. Você está acessando uma lazy collection fora da sessão do hibernate.
Por exemplo, você buscou um objeto A que possui uma lazy collection de B. Porém antes de acessar a.getB() você fechou a sessão do hibernate. Quando finalmente a.getB() for invocado, a lazy collection do hibernate ao tentar recuperar a lista de Bs, identifica que não existe mais sessão e solta essa exceção.
Na realidade o seu problema é ao adicionar um elemento na coleção, mas o conceito é o mesmo.
Você precisa descobrir porque a sua sessão não está ativa durante a execução deste método.


Solving for $\sin(n \cdot\arcsin(x))$ when n takes on any integer value.

Question:

Solving for $\sin(n \cdot\arcsin(x))$ when n takes on any integer value.
How would I go about tackling this question for large numbers of n? I was able to compute it by hand for values of $n$ up to $4$ but there has to be an easier way to solve it for numbers like $50$ etc...
Comment: Are oyu familiar with Chebyshev polynomials and their relationship with [multiple-angle formulas](http://mathworld.wolfram.com/Multiple-AngleFormulas.html)?  So, if you can solve for $\cos(\sin^{-1} x)$ and $\sin(\sin^{-1} x)$, you can form a polynomial of those giving your multiple angle solution.
Comment: Try using the imaginary part of the complex number definition as a power of e.
Comment: Can you show the first four you said you found? I think it would be helpful for eventual answerers.
Comment: Check this link out, hope this helps
http://math.stackexchange.com/questions/407337/adriaan-van-roomens-45th-degree-equation-in-1593
Answer: If $U_n$ denotes de $n-$th Chebyshev polynomial of the second kind, we have :
$$\forall\theta\in\mathbb{R},\quad\sin((n+1)\theta)=\sin(\theta)\,U_{n}(\cos(\theta))$$
So, for all $x\in[-1,1]$ and $n\in\mathbb{N}^\star$ :
$$\sin(n\arcsin(x))=x\,U_{n-1}\left(\sqrt{1-x^2}\right)$$
It remains to explain how to compute effectively $U_n(t)$ for every pair $(n,t)$.
A simple way is to use the recurrence relation :
$$U_0(t)=1\qquad U_1(t)=2t\qquad \forall n\ge2,\,U_n(t)=2t\,U_{n-1}(t)-U_{n-2}(t)$$
Comment: Hello sir. I'm having a problem where I need to use the equation you typed above ChebyshevT(x)=x*ChebyshevU(n-1,sqrt(1-x^2)) but x needs to be outside of [-1,1].  My hypothesis is that the equation holds true even when x is a complex number. Do you have any proof that im wrong?
Comment: @RobertPuscasu The correct relation is $\sin(nx)=\sin(x)\,ChebyshevU(n-1,cos(x))$. Here $\cos(x)\in[-1,1]$ and you would like to replace it by something lying outside this interval. You could maybe use the following relation, which is also true : $\sinh(nx)=\sinh(x)\,Chebyshev(n-1,\cosh(x))$
Comment: Thank you sir...


Como ordenar por duas propriedades em Linq

Question: Tenho a seguinte sintaxe e não esta funcionando
return View(trabalhos.Where(a => a.Usuario == User.Identity.Name &&
                                 a.Data.Month == DateTime.Today.Month &&
                                 a.Data.Year == DateTime.Today.Year).ToList()
                                .OrderByDescending(a => a.Data)
                                .OrderByDescending(a => a.HoraInicial));

Percebam que tenho dois atributos com ordenação OrderByDescending.
Neste exemplo a ordenação que prevalece é OrderByDescending(a => a.HoraInicial), deixando sem efeito qualquer a ordenação OrderByDescending(a => a.Data)
Gostaria que os dois campo fizessem a ordenação primeiro por Data e depois da ordenação data faça a da Hora Inicial.
Comment: Você teve sua dúvida respondida? Precisa que algo seja melhorado?
Answer: Acontece que sempre que OrderBy é executado, ele ordena toda a coleção, ou seja, a ordenação anterior é desconsiderada.
Por isso, é preciso usar o método ThenByDescending()
trabalhos.Where(a => a.Usuario == User.Identity.Name &&
                     a.Data.Month == DateTime.Today.Month &&
                     a.Data.Year == DateTime.Today.Year).ToList()
                     .OrderByDescending(a => a.Data).ThenByDescending(a => a.HoraInicial));

Comment: "bueno", jbueno! rs... `+1`
Answer: Utilize ThenBy na segunda ordenação se quiser a ordenação default (ASC)
return View(trabalhos.Where(
a => a.Usuario == User.Identity.Name &&
a.Data.Month == DateTime.Today.Month &&
a.Data.Year == DateTime.Today.Year).ToList()
.OrderByDescending(a => a.Data).ThenBy(a => a.HoraInicial));

Ou utilize ThenByDescending na segunda ordenação caso queira a ordenação da data e hora inicial decrescente (DESC)
return View(trabalhos.Where(
a => a.Usuario == User.Identity.Name &&
a.Data.Month == DateTime.Today.Month &&
a.Data.Year == DateTime.Today.Year).ToList()
.OrderByDescending(a => a.Data).ThenByDescending(a => a.HoraInicial));

Comment: 30 segundos na minha frente :p +1


How appropriate is this logistic regression analysis?

Question: I am reviewing this study where they measured fathers' stress, anxiety and depression levels at four-time points. And they measured the child's behavioural problems only at the last time. They then created dichotomous variables from this data (whether there was or wasn't stress, depression, anxiety or behavioural issues). They created logistic models using the children's measure as the dependent variable and the father's measures as the independent. They created a model for each timepoint the father's distress measures were taken.
For each model, they then created another model adjusting for age, sex, father's age ...
Finally, they created a stepwise log regression with all fathers' and mothers' distress variables from all the time points to predict the children's behavioural problems.
I question whether you consider using a log regression appropriate with this data and whether they should have used one model with multilevel variables for stress, depression, and anxiety levels for each time point.
Also, in total, they did around ten models or so, given that they made different ones for each time point for each distress measure and then a combination of them. Should they correct for multiple comparisons, or do you think this might not be necessary in this case?
Answer: So much wrong with what was done!
I do statistical reviews for a couple of journals and this would, for sure, be "major revision."

Dichotomizing variables is almost always a bad idea. It reduces power and increases type 1 error and doesn't let you ask some interesting questions.

What method should be used depends on the original scoring of the child's measure. This might be ordinal (none, mild, moderate, severe) or it might be a score from some scale that was factor analyzed, or it might be something else. If it's a yes/no variable then ... well, that's really not a good measure of "behavior problems".

A separate model for each time point is not a good way to go. I'm not sure what I would recommend. I would look at the patterns over time before deciding how to proceed (and I would look at these without relating them to the dependent variable. There are ways of doing cluster analysis on this sort of thing, that might make sense here. But some sort of accounting for this should be done.

Stepwise is a bad way to build a model. All the output is wrong. Standard errors are too small, p values too low, parameter estimates biased away from 0.

As for multiple comparisons and corrections, well Jacob Cohen said "this is a subject on which reasonable people may differ."   I don't often see corrections for multiple models of the sort you are describing.
Comment: Thank you for your answer, Peter, always so helpful.


Confusion about vector triple product

Question: The question is simple. Say I have two vector $\mathbf{a}$ and $\mathbf{b}$, and I want to simplify the product $(\mathbf{a} \times \mathbf{b}) \times \mathbf{b}$. According to this, it can be rewritten as $-(\mathbf{b}\cdot\mathbf{b})\mathbf{a}+(\mathbf{b}\cdot\mathbf{a})\mathbf{b}$. This product is written in terms of both $\mathbf{a}$ and $\mathbf{b}$.
However, this cross product is absolutely perpendicular to $\mathbf{b}$ so it should not have any component on $\mathbf{b}$. I realized that $\mathbf{a}$ and $\mathbf{b}$ may not be orthogonal but I can't continue from there to justify the presence of $\mathbf{b}$.
Can anyone explain this in simple terms why $\mathbf{b}$ is there?
Comment: Try taking the dot product of $\boldsymbol{b}$ and $-(\boldsymbol{b}\cdot\boldsymbol{b})\boldsymbol{a}+(\boldsymbol{b}\cdot\boldsymbol{a})\boldsymbol{b}$. This shows that there is no component in the direction of $\boldsymbol{b}$.
Answer: If $a$ and $b$ are orthogonal to each other, then you are right that $(a\times b)\times b$ has to be a scalar of $a$. Otherwise, you can draw a picture and see that $(a\times b)\times b$ is a vector in the plane spanned by $a$ and $b$ and orthogonal to $b$. But since $a$ and $b$ are not orthogonal, so need both $a$ and $b$ to write $(a\times b)\times b$ as a linear combination of $a$ and $b$.
Answer: Let's write it in a more systematic manner. Given the equality
$$
(a \times b) \times b = -(b\cdot b)a + (b \cdot a) b,
$$
you correctly claim that the left hand side should be perpendicular to $b$. Now let's check if the right hand side is perpendicular to $b$:
$$
\text{RHS}\cdot b = -\left( (b\cdot b)a + (b \cdot a) b \right) \cdot b = - (b \cdot b)(a \cdot b) + (b \cdot a)(b \cdot b) = 0.
$$
As you can see the right hand side is also perpendicular to $b$, and there is no contradiction.
Your confusion roots from assuming that the existence of $b$ in the right hand side prevents it from being perpendicular to $b$. This is not always correct, unless $a$ and $b$ are perpendicular. But as you can see in this particular case, $a\cdot b$ would be zero, and $\text{RHS}=-(b \cdot b)a$. So, still no contradiction.
Comment: I am indeed a slow typist. Look at all the answers posted while I was typing my answer.
Comment: +1 for pointing out "assuming that the existence of b in the right hand side prevents it from being perpendicular to b"
Answer: In fact there is no component along with $b$. $b$ can be decomposed to two perpendicular components: the image of $a$ on $b$ and the remaining. In other words$$\vec{b}=k\vec{a}+\vec{c}$$where$$\vec{b}\cdot\vec{c}=0$$here the image of $\vec{a}$ on $\vec{b}$ is $$\dfrac{\vec{a}\cdot\vec{b}}{|\vec{b}|^2}\vec{b}$$
Answer: As long as $a$ and $b$ are linearly independent, they span a plane $P$,
and $a\times b$ is perpendicular to $P$. But $(a\times b)\times b$
is perpendicular to $a\times b$, so is in the plane $P$. That is,
$(a\times b)\times b=\mu a+\nu b$ for some $\mu$ and $\nu$.
That is how $b$ enters.
To confirm that $\mu=-b\cdot b$ and $\nu=a\cdot b$, all one has to
do is to prove that $c=-(b\cdot b)a+(a\cdot b)b$ has the same dot products
with $a$ and $b$ that $(a\times b)\times b$ has. But $$c\cdot b
=-(b\cdot b)(a\cdot b)+(a\cdot b)(b\cdot b)=0$$ which is good
as $(a\times b)\times b$ is orthogonal to $b$. On the other hand
$$c\cdot a=-(a\cdot a)(b\cdot b)+(a\cdot b)^2=|a|^2|b|^2(-1+\cos^2t)
=-|a|^2|b|^2\sin^2t$$
where $t$ is the angle between vectors $a$ and $b$. But
$$((a\times b)\times b)\cdot a =(a\times b)\cdot(b\times a)
=-|a\times b|^2=-|a|^2|b|^2\sin^2t.$$
Indeed then $c=(a\times b)\times b$.
Answer: $\frac{(a\cdot b)\,b}{b\cdot b}$ is the projection of $a$ onto the direction of $b$.
$\frac{a\times b}{|b|}$ is the projection of $a$ onto the plane perpendicular to $b$ then rotated $\frac\pi2$ about the direction of $b$. Since $\frac{a\times b}{|b|}$ is perpendicular to $b$, the cross product with $\frac{b}{|b|}$ simply rotates it another $\frac\pi2$ about the direction of $b$. That is, $-\frac{(a\times b)\times b}{b\cdot b}$ is the projection of $a$ onto the plane perpendicular to $b$.
Adding these two orthogonal projections yields
$$
\frac{(a\cdot b)\,b}{b\cdot b}-\frac{(a\times b)\times b}{b\cdot b}=a\tag1
$$
Solving for $(a\times b)\times b$ gives
$$
(a\times b)\times b=(a\cdot b)\,b-(b\cdot b)\,a\tag2
$$

Although it appears that there is a component of $b$ on the right-hand side of $(2)$, all that the $(a\cdot b)\,b$ serves to do is to cancel the part of $(b\cdot b)\,a$ that is in the direction of $b$. Note that
$$
((a\cdot b)\,b-(b\cdot b)\,a)\cdot b=0\tag3
$$
So there is indeed no component in the direction of $b$.

Confusion about vector triple product


SQL Select -> product -> comments -> user

Question: thanks for yout time helping on this ;)
I'm new to SQL and wish to solve somethign in just one query and i dont know how to do it.-
Basically I've a table of products, a table of users and a table of comments, linked by products.id -> comments.pid and user.id -> comments.uid ,
i wish to know what is the best practice to create just 1 query and get all products with child comments, including username.
Comment: Do you also like to try to write your entire application in one line of code? If you need two queries, use two queries.
Comment: Agree with Mark, if you think about getting all those data in one query you combine separate parts of your application. Instead it would make more sense to separate commenting from the product. That way you can work more efficiently. Next to that the situation might get more complex in future, for example you also need the categories the product is in. Just SELECT id, nam FROM products WHERE id=1 and another query: SELECT users.name, comments.comment FROM comments INNER JOIN users ON users.id=comments.uid WHERE comments.pid=1
Comment: Mark, i agree with you, to show data from one product in one page, but if you need to create a list of products like pinterest... do you think that is the best practice to loop trough products list usign multiple queries? in a heavy traffic website this could kill the server.- just think listing 100's products and getting 5 comments from each one.- there will be 101 queries, vs 1 using a join, my problem is that i dont know the limitations of joins because i am new into sql.-
Answer: Learn about SQL joins:
SELECT *
FROM   products
  LEFT JOIN comments ON products.id = comments.pid
  LEFT JOIN user     ON user.id     = comments.uid

Answer: learning joins is the best way to  solve such a problem
Explanation
what we are trying here to do is create a virtual table which fetches records based on some relations.
I have created three tables here

product
user
comments

and there is a relation set between the

product and the comments table  - using product.id and comments.prod_id
user and the comments table  - using user.id and comments.user_id

Now you can use  join to filter the results
SELECT product.id,user.name,comments.DATA
 FROM comments
LEFT JOIN product ON comments.prod_id = product.id
INNER JOIN USER ON comments.user_id = USER.id;
or if you don't want to use join you can simply create a relation
but please do note that using joins is the best possible way to do it
SELECT product.id,USER.name,comments.DATA
FROM product,USER,comments
 WHERE product.id = comments.prod_id AND USER.id = comments.user_id;

you can check the results here
SqlFiddle
Answer: Istead of using JOIN you can try this,
select p.id,u.name,c.data
from products as p,user as u,comment as c
where p.id = c.pid and u.id = c.uid;

Comment: [Why isn't SQL ANSI-92 standard better adopted over ANSI-89?](http://stackoverflow.com/questions/334201/why-isnt-sql-ansi-92-standard-better-adopted-over-ansi-89)
Comment: Also, I suspect in this case outer joins are necessary in case a product has no comments.
Comment: @eggyal Product which has both user associated with comment and comment only those will be displayed..
Comment: @eggyal in question he has not mentioned that he wants all product irrespective of comment :)


Inline style fetched from database

Question: I'm editing an existing Drupal 7 site, with coloured menu buttons, and each part of the site has the corresponding colours in it's titles and links.
For example: the menu item "about us" is coloured orange, and each subpage of "about us" uses orange for it's titles and links.
The problem is: these are all inline styles, fetched from the database table "field_data_field_colour" and printed by a template.
I can change the hex-colour values directly in the database, but I've looked everywhere and can't find where to change/set those colours without messing with the database.
Answer: The pattern field_data_field_ refers to Field storage. This data is attached to an entity of some kind, most likely a Node. You can learn more about content management on drupal.org, Nodes, content types and fields.
You should edit the node that you want to modify (admin/content or click Edit on a node if the tab hasn't been styled out of existence), and find the field that someone added there. Then you can change the value. You can check what fields are used in which entity types by going to /admin/reports/fields. Each field usage has a link to its respective Field Management page where you can learn more about how that particular field is configured.
Modifying field_data_field_ directly in the database is incorrect because data retrieval happens in field_revision_field_ tables.
Comment: Thanks, your link made me find the colour field, and then where it was applied, and then where the colours were set.

Inline style fetched from database


Proving discontinuity at $\,x =1\,$ using $\,\varepsilon$-$\delta\,$ definition

Question: I was doing a proof for discontinuity using $\,\varepsilon$-$\delta\,$ definition but I'm not sure whether the proof is right. Would you mind checking it for me please, thanks!
$g(x)=\begin{cases}\dfrac{1}{1-x}\;,\quad& x\neq1\\0\;,&x=1\end{cases}$
For the proof, I have chosen $\,\varepsilon = 1$.
And said for $x\in [0,2]\cap(1-\delta, 1+\delta)\,$ where $\,x\neq1$
$|x-1|<\delta\,$ but $\,|g(x)-g(1)|\geqslant1\,,$
Is this right?
Thanks!
Comment: Yes, apart from this typo it seems correct, but better *choose* (for *any* $\delta>0$) some $x$ (in fact any of those you mention will do: e.g. $x=\min(2,1+\delta/2)$).
Comment: You are looking at a function $g(x)$. What is $f(x)$? Which case in the definition of $g(x)$ has an obvious typo?
Comment: Is not correct. You need to prove that no matter which $\delta>0$, there is always an $\epsilon$ that contradicts the definition thus rendering the function discontinuous.
Answer: The function g(x) is continuous at $x=x_0$ if
$$\forall \epsilon >0, \exists \delta >0:|x-x_0|<\delta\Rightarrow |g(x)-g(x_0)|<\epsilon$$
The function g(x) is discontinuous at $x=x_0$ if
$$\exists \epsilon >0\,,\forall \delta >0\,,\exists x\in(x_0-\delta,x_0+\delta) :|g(x)-g(x_0)|\ge \epsilon\,.$$
In this case $x_0=1; g(x_0)=0\,.$
Lets take $\epsilon=1$. Observe that, for $0<|x-1|<1$,
$$
\frac{1}{|x-1|}>\epsilon,\quad\text{ or equivalently, }\quad
\left|\frac{1}{x-1}-0\right| \gt \epsilon\,.
$$
That is:
$$
|g(x)-g(1)| \gt \epsilon\,.
$$
This shows that for $\delta=1$ every $x\in(1-\delta,1)\cup(1,1+\delta)=(0,1)\cup(1,2)$ satisfies
$$\tag{1}
|g(x)-g(1)|>\epsilon.
$$
Clearly, for any other $\delta>0$ we can find at least one
$x\in(1-\delta,1)\cup(1,1+\delta)$ that satisfies (1) as well because the
intersection of this set with the previous one, $(0,1)\cup(1,2)\,,$ is not empty.
This finishes the proof that $g(x)$ is discontinuous at $x=1\,.$
Comment: The centered interval contains $x=3$ and for this $x$ the inequality $|f(x)-f(3)|\ge\epsilon$ only holds for $\epsilon=0\,.$ That was my point about your definition of the discontinuity of $g$.
Comment: The truth is in implication not in parts of it. Take a step function of the form $f(x)=\left \{ \begin{align} 1&,x\le3\\4&,x>3\end{align}\right.$. The value $f(x)=3$ can not be found on any vicinity of 3. There is $\epsilon=3$ for which $\forall x \in (3-\delta, 3+\delta)\Rightarrow |f(x)-f(3)|\ge\epsilon$
Comment: As far as I can tell: For this $f$, $f(3)=1$ and $\forall x\in(3-\delta,3)$ we have $|f(x)-f(3)|=0\,.$ This is in stark contrast to your last claim.
Comment: I cannot follow that definition of discontinuity. For $x=x_0$ the condition $|x-x_0|<\delta$ is true but $|g(x)-g(x_0)|\ge\epsilon$ is false, no matter if $g$ is continuous or discontinuous.
Comment: I changed it to f(3)=3. Then it has to be the centered interval, not half of it.
Comment: If you apply the rules of negation to your correct definition of the continuity of $g$ the discontinuity becomes
$$
\exists \epsilon>0\,\forall \delta>0\,,\color{red}{\exists x\in(x_0-\delta,x_0+\delta)}: |g(x)-g(x_0)|\ge \epsilon\,.
$$
Comment: Thank you for clarifying that. Please be so kind to write the answer for everyone to benefit.
Comment: I think it is better if you or I edit your answer. There is not much to change. You want to give it a go?
Comment: Of course but you deserve the credit, not me. I'm good with what I've learned today.
Comment: As you can see, I needed three attempts to get it right. :) Please review.


difference between sample_weight and class_weight RandomForest Classifier

Question: I have a very imbalanced big dataset (500000 instances, 60 features) which is prone to changes (increase in size and number of features). But what will stay fixed is the imbalance in the classes, this is, class 0 will always be the dominant one. On average, 90% of the data will be in class 0, and the rest 10% in class 1.
I am interested in classifying as accurately as possible instances with class label 1, so I want to increase its cost of misclassification.
The classifier I chose is RandomForest and in order to account for the class imbalance I am trying to adjust the weights, then evaluate using StratifiedKFold and then plotting the corresponding roc_curve for respective the k fold.
This is the code for my classifier:
 clf1 = RandomForestClassifier(n_estimators=25, min_samples_leaf=10, min_samples_split=10,
      class_weight = "balanced", random_state=1, oob_score=True)

 sample_weights = array([9 if i == 1 else 1 for i in y])

I looked through the documentation and there are some things I don't understand. I tested all these methods but the difference in the evaluation metrics was minimal so I have a hard time identifying which settings optimize my classifier.
Needless to say even though I use weighting the prediction power of my model is very low, with sensitiviy being on average 0.2
These are my questions:

should sample_weight and class_weight be used together simultaneously?
between class_weights = "balanced" and class_weights = balanced_subsamples which is supposed to give a better performance of the classifier
is sample_weight supposed to be adjusted always according to ratio of imbalance in the samples?
class_weights = balanced_subsamplesand sample_weight give an execution error when used simultaneously. why?

Also if there is a better approach for evaluating the classifier please do let me know.
Comment: You are using the sample_weights wrong. What you want to use is the class_weights. Sample weights are used to increase the importance of a single *data-point* (let's say, some of your data is more trustworthy, then they receive a higher weight).
So: The sample weights exist to change the importance of **data-points** whereas the class weights change the weights to correct class imbalance. They can be used together with their purpose in mind. In your example, using class weights has no effect whatsoever, because you abused the sample weights to do the job of the class weights.
Comment: @Glue it is equivalent! Yet, for this special case, there _is_ already functionality available, namely the `class_weight`. It's not wrong, it's just unnecessary complicated
Comment: To add to @Mayou36's comment, class_weight are passed on to sample_weight as well. So be careful while using them.
Comment: @GarimaJain just to be explicit about your (true) comment: the weight of datapoint i is given by `class_weight[class_of_datapoint_i]` times `sample_weight[i]`.
Comment: @Mayou36, why do you say he abused sample_weight param? My understanding is that the following are equivalent: 1.`sample_weights = array([9 if i == 1 else 1 for i in y])` , 2. `class_weight={0: 1, 1: 9}`
Answer:
You are using the sample_weights wrong. What you want to use is the
  class_weights. Sample weights are used to increase the importance of a
  single data-point (let's say, some of your data is more trustworthy,
  then they receive a higher weight). So: The sample weights exist to
  change the importance of data-points whereas the class weights change
  the weights to correct class imbalance. They can be used together with
  their purpose in mind. In your example, using class weights has no
  effect whatsoever, because you abused the sample weights to do the job
  of the class weights.
Comment: I've copied this comment by @Mayou36 as a community wiki answer because they are, more or less, an answer to this question. We have a dramatic gap between answers and questions. At least part of the problem is that some questions are answered in comments: if comments which answered the question were answers instead, we would have fewer unanswered questions.
Comment: Fair enough. However, not all of the questions in the post have been addressed and it would be nice if more of them are answered.
Comment: @Roxanne FWIW, you might get more answers if you post questions separately (though there are cases when putting some together makes sense).
Answer: Q&A

Should sample_weight and class_weight be used together simultaneously

If your goal is to weight your classes because they are imbalanced, you can use either. Using class_weight="balanced is the same as sample_weight=[n_samples].
I tested it with an unbalanced set in kaggle. I estimated the "sample_weight" based on what was given in the sklearn docs: n_samples / (n_classes * np.bincount(y))
Note: "A guide as to what weights to give is to make them inversely proportional to the class populations"--- People at Berkeley

between class_weights = "balanced" and class_weights = balanced_subsamples which is supposed to give a better performance of the classifier

You can easily test it for your dataset. It's hard for me to say. For me, recall was higher (9%) and precision was lower by 9% (on the minority) dataset.

is sample_weight supposed to be adjusted always according to ratio of imbalance in the samples?

Depends on what you care about. If you want the prediction error (1-recall) of all classes to be the same, then you can look at the different recalls, change your weights and until they balance out. Note: This WILL reduce your overall prediction error.
This is suggested by "some people" at Uni of Berkeley. However, I was not able to balance out my 1-recall despite increasing my minority class weight by a lot (1000 from 26).
Here is a comparison table for one of the kaggle contests I am working on:

tr recall
vd recall
tr prec
vd prec

baseline
37.4
26.9
94.8
79.6

balanced  (1,26)
67.6 (80%)
30.2 (12%)
88.7 (-6.5%)
75.3 (-5.5%)

subsample balanced
67.5 (80%)
32.9 (22%)
88.0 (-7.2%)
70.9  (-11.7%)

overweighting (1,1000)
65.3 (80%)
25.1 (-7%)
84.5 (-10.9%)
84.0  (5%)

class_weights = balanced_subsamples and sample_weight give an execution error when used simultaneously. why?

Not sure.


Bootstrap rows inconsistent padding

Question: I have a grid template with 3 columns, and my first row in the column is being pushed by a few pixels. What CSS option do I need to change for this? I'm using bootstrap

    <input type="redacted" class="form-control" id="redacted" placeholder="" required>

    <input type="redacted" class="form-control" id="redacted" placeholder="">

    <input type="redacted" class="form-control" id="redacted" placeholder="">

Here's the CSS
.gridMatchInputs {
  display: grid;
  grid-template-columns: 200px 200px 200px;
}

Comment: Please provide more information. Read the above link ^
Comment: Can you please include a [mcve] in your question?  The code provided does not illustrate the issue.  At first glance, I do not see multiple rows in your code so it seems like more code is missing
Comment: Sorry, please see here

https://jsfiddle.net/cr798jmn/

Notice how the 2nd row is indented? I believe it's an issue because the 2nd row starts with a `select` but I'm not sure where to look to change this.
Comment: It has nothing to do with `select` - check answer below
Answer: If you remove this line grid-template-columns: 200px 200px 200px; from your CSS and use .row when you want to have elements in a new row, I think you achieve what you are looking for
See demo below

.gridMatchInputs {
  display: grid;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

      <input type="text" class="form-control" id="1" placeholder="1" required>

      <input type="text" class="form-control" id="2" placeholder="2">

      <input type="text" class="form-control" id="3" placeholder="3">

      <select class="form-control" id="select1">
        <option selected>select1</option>
      </select>

      <select class="form-control" id="select2">
        <option selected>select2</option>
      </select>

      <select class="form-control" id="select3">
        <option selected>select3</option>
      </select>

Comment: Yes, this was indeed it, I also had two column  in the code as well which causes the indentation, thank you!
Comment: I'm glad I could help :)

Bootstrap rows inconsistent padding


How to limit a user from deleting a post that isn't theirs?

Question: So I'm following this tutorial https://medium.com/@deallen7/how-to-build-a-reddit-like-site-with-ruby-on-rails-7b6cd106463d and got to the part where I add this
before_filter :authenticate_user!, except: [:index, :show]

to my Links Controller. I'm using the devise gem, and when no user is logged in, I'm not supposed to be able to destroy a post through the View but I can.  Is the code above deprecated?
Comment: Devise gives you a user model. For permissions you need another system like [Cancancan](https://github.com/CanCanCommunity/cancancan).
Answer: If you keep reading in the link you posted, the new version, you'll see that it should be
before_action :authenticate_user!, except: [:index, :show]

Further down it show to add this in your view:
<% if link.user == current_user %>
    <%= link_to 'Edit', edit_link_path(link) %>
    <%= link_to 'Destroy', link, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>

However keep in mind without backend permissions, a skilled user could hack this.  While the example might be a good basic way to get a basic idea of rails, there's a lot of bad practices on how to code here.  I would suggest looking for better materials to learn from.


perl ssh move to next if error

Question: I have few routers in my network who accept telnet and other few who accept ssh only.
So I used this module (SSH_TELNET::ssh_telnet;)
now there is one router (blys830) not accepting my credential. I want in this situation to try next router and skip current one.
Here is my code but not working.
use SSH_TELNET::ssh_telnet;

my @node=("blys830","brtc817");
my @op;
my $ok=1;
$user="xxxx";
chomp $user;
$pass="xxx";
chomp $pass;

foreach $node (@node) {
$node=~s/^\s+|\s+$//g;

$session = SSH_TELNET::ssh_telnet->new("$node") or $ok=0;
$session->login($user,$pass) or $ok=0;

if (!$ok) {
print "not OK\n";
next;
}

else {
$session->cmd('term len 0');
@op=$session->cmd('sh isis neighbor');
}

$session->disconnect;
}

I was expecting it to move to next router but it print below output.
blys830 TELNET authentication failed at test_ssh.pl line 47

Any suggestion ?
Regards
Mahesh
Comment: That module is not public. Anyway, you may like to use `eval` to trap errors. Read the perl documentation.
Comment: Where did you get the module from, does your script terminate after printing this and not progress to the next router at all? if so then most likely the implementation of the module is calling "croak" when it cannot connect which is causing your script to end. As salva said, you can use eval to trap and prevent this.
Answer: use eval :
use SSH_TELNET::ssh_telnet;

my @node=("blys830","brtc817");
my @op;
my $ok=1;
$user="xxxx";
chomp $user;
$pass="xxx";
chomp $pass;

foreach $node (@node) {
$node=~s/^\s+|\s+$//g;
eval {
$session = SSH_TELNET::ssh_telnet->new("$node") or $ok=0;
$session->login($user,$pass) or $ok=0;
}
if (!$ok) {
print "not OK\n";
next;
}

else {
eval {
$session->cmd('term len 0');
@op=$session->cmd('sh isis neighbor');
}
}

$session->disconnect;
}

perl ssh move to next if error


Is this set dense in some open set?

Question: Let $S$ be a subset of $\mathbb{R}$ (with at least two elements)  which satisfies the following property:
$$\mbox{if $a,b \in S$ with $a<b$ then $(a,b)\cap S\not=\emptyset$}.$$
Is it true that there exists a non-empty open set $U$ such that $S\cap U$ is dense in $U$?
Any reference in the literature to this kind of sets is welcome.
Answer: Not necessarily. Let $C$ be the middle-thirds Cantor set, and let $E$ be the set of endpoints of the open intervals that were removed in the construction of $C$. Let $S=C\setminus E$; then $\operatorname{cl}S=C$, which is nowhere dense, and $S$ is densely ordered (i.e., satisfies your requirement).
Comment: So $S$ is the set of numbers between 0 and 1 whose base 3 expansion consists of 0s and 2s and it is non-terminating. Am I right?
Comment: @Robert: Yes, that's exactly right. (And one really need only delete *one* of the endpoints of each interval to make $S$ densely ordered.)

Is this set dense in some open set?


404 when using a variable in URL- error: No query results for model [App\Models\Seeker]

Question: Im calling from the angular front side to my laravel back end.
When I use a variable in the url (USERID) it gives me a 404 error.
When I remove the USERID from the url it works and reach the function in the server.
Client side:
  getSeeker(userID: number) {
    return this.http.get(`${this.endPoint}/${userID}/getSeekerProfile`,
      {headers: this.getTokenHeaders()})
  }

Server side:
    Route::get('candidate/{userID}/getSeekerProfile',   'CandidateController@getSeekerProfile');

Error on client side:
GET http://localhost:8000/api/headhunter/candidate/363/getSeekerProfile 404 (Not Found)

Error on server side:
message: "No query results for model [App\Models\Seeker]."

the targted function (getSeekerProfile):
PS - i also tried to just return dd('reached') and removing the (User $userID) parameter.
    public function getSeekerProfile(User $userID)
    {
        dd($userID);
    }

I cant really find the problem. Im not even using the Seeker model in relation to this piece of code.
Any ideas will be most welcome.
Thanks.
PS - maybe this will help:
There is a middle ware before the route
Route::group(['prefix' => 'headhunter','middleware' => ['AuthHeadhunter']], function () {

and it doesnt even go inside it.
is it possible that during the request it goes through another place first?
Comment: @Mubashar that's how laravel works, if you provide the ID (int) in the route and expect a model, it will launch `Model::find($id)` to get the instance of the model and inject it to the method. wich will return a 404 if the model is not present in the DB
Comment: remove the Model injection for further debug: `public function getSeekerProfile($userID)` did you check your database for the user with id 363 and not having soft delete and `deleted_at` null
Comment: I think the problem is in your parameter of function "getSeekerProfile(User $userID)" in your controller. You are giving type of $userID as object of User model but it is just an integer from variable segment of URL. Please try removing User(type hint) before $userID, well if you want it to be type hinted make it "int". Hope it would helpful to you otherwise it seems good.
Comment: I checked, user 363 exist, no soft delete.
Answer: public function getSeekerProfile(User $userID) this line send query for $userID to User Model.But User Model has not this $userID =>363
So you can saved this Id User Model or you can use
getSeekerProfile($userID)
{
$user = User::find($userID);
}

instead of
getSeekerProfile(User $userID)

Comment: Thanks for the comment, I tried that
```
    public function getSeekerProfile($userID)
    {
        dd($userID);
    }
```

still the same
```
No query results for model [App\Models\Seeker]
```

Why is it still referring the the Seeker Model?

what weird is that the request doesnt even reach the AuthToken function that is in the middleware before the URL, and directly gives a 404
Comment: you can share dd result
Comment: it doenst reach the dd but gives the No query result found
Comment: User Model has not $userID on database. is not it
Comment: the user 363 does exist in the database in the User model
Comment: also i tried
getSeekerProfile($userID)
{
dd('reached')
}

still same error
Comment: AuthHeadhunter middleware can you share
Comment: it doesnt even reach there.
does laravel has a special handle for variables that are been send through url?
Comment: what is the endpoint angular side.this endpoint is can try in postman
Comment: the endpoint is good cause when i remove the userID

  getSeeker(userID: number) {
    return this.http.get(`${this.endPoint}/getSeekerProfile`,
      {headers: this.getTokenHeaders()})
  }

    Route::get('candidate/getSeekerProfile',   'CandidateController@getSeekerProfile');

it does reach.
Answer: OK so whoever is interested -> the answer has been found!
I had two routes one after the other:
Route::get('candidate/{seeker}/{jobID}','CandidateController@show');
Route::get('candidate/{userID}/getSeekerProfile','CandidateController@getSeekerProfile');

The problem was the order of the routing.
the request always entered the first router because in theory the first route has two variables (seeker & jobID) so potentially they could be anything:
Route::get('candidate/{can be anything}/{can be anything}','CandidateController@show');

so laravel looked at the first url (with the two variable) as equal to the second route:
get('candidate/{can be anything}/{can be anything}','CandidateController@show');

is the same as:

get('candidate/{can be anything}/getSeekerProfile','CandidateController@getSeekerProfile');

Only if we enter the two variable route first
so it enter the first route (which was incorrect)
the solution was to switch their order:
Route::get('candidate/{userID}/getSeekerProfile','CandidateController@getSeekerProfile');
Route::get('candidate/{seeker}/{jobID}','CandidateController@show');

now laravel will not get confused cause the "getSeekerProfile" is not a variable so it will know to enter inside.
In my initial post I only showed one route, cause I didnt even consider this as the problem.
Thank you for everyone who tried to help, and sorry for the initial unintended lack of information.


Cross test: Gagliardo seminorm

Question: This question comes from a cross test submitted to me and my advanced calculus class (we faced very few preliminaries of the Hitchhiker's guide to the fractional Sobolev spaces).
Let $\Omega$ be bounded in $\mathbb{R}^N$ with Lipschitz boundary, $k\in\mathbb{N}$, $0<s_1 <\dots <s_k<1$, $N>2s_k$ and let $u\in H^{s_k}(\Omega)=\{u\in H^{s_k}(\mathbb{R}^N): u=0 \text{ in } \mathbb{R}^N\setminus\Omega\}$.
Let $$[u]_{s_k}^2=\iint_{\mathbb{R}^{2N}}\frac{|u(x)-u(y)|^2}{|x-y|^{N+2s_k}} dx dy$$
be the usual Gagliardo seminorm.
Assume that $[u]_{s_k}^2 = 1$ and let also $0<a_1 <\dots <a_k<1$ with $\sum_{i=1}^k a_i = 1$.
Find an upper bound for the quantity
$$\sum_{i=1}^k a_i [u]_{s_i}^2.$$
The alternatives were: $k$, $0$ and "none".
About me the correct answer is "none" since the correct upper bound is $1$.
In fact, as $0<s_1 <\dots <s_k<1$ and $[u]_{s_k}^2 = 1$, we have that $$[u]_{s_i}^2 \le [u]_{s_k}^2 = 1\quad \forall i\in\{1, \dots, k-1\}.$$
Hence,
$$\sum_{i=1}^k a_i [u]_{s_i}^2 \le \sum_{i=1}^k a_i =1.$$
Could someone please tell me if I argued correctly?
The lecturer said that my answer was not correct.
Comment: Why is $[u]_{s_{i}}^{2} \le [u]_{s_{k}}^{2} \ \forall i < k$?
Comment: It should be true up to a constant depending on $N, s$. Did you mean this?
Answer: Unless, I'm mistaken there is something incorrect in the question. Let $\mathcal H^s_0(\Omega) = \{ u \in H^s(\mathbb R^n) \text{ s.t. } u = 0 \text{ in } \mathbb R^n \setminus \Omega \}$ (note, it's not a good idea to call this space $H^s(\Omega)$ since this a common notation for a different space), $a:= \{a_j\}_{j=1}^k$, and define $$C_\ast(\Omega,k,a) := \sup_{u\in \mathcal H^s_0(\Omega)} \bigg \{ \sum_{j=1}^k a_j [u]_{s_j}^2 \text{ s.t. } [u]_{s_k}=1\bigg \}. $$ From what I understand, you have been asked to show that decide whether (a) $C_\ast=0$ (b) $C_\ast =k$; or (c) $C_\ast = +\infty$. None of these options appear to be correct:

The answer is not (a): Let $C_\ast =0$ and $u\in \mathcal H^s_0(\Omega)$ be such that $u \neq 0$. Then $$ 0\leqslant a_1 [u]_{s_1}^2\leqslant \sum_{j=1}^k a_j [u]_{s_j}^2 =0, $$ so $u$ is a constant in $\mathbb R^n$. Then, since $u=0$ in $\mathbb R^n \setminus \Omega$, so $u=0$ which is a contradiction.

The answer is not (b): In fact, $C_\ast$ cannot be independent of $\Omega$ and $a$. Indeed, define $$\tilde C_\ast (k,a)= \sup_{u\in C^\infty_0(\mathbb R^n)} \bigg \{ \sum_{j=1}^k a_j [u]_{s_j}^2 \text{ s.t. } [u]_{s_k}=1\bigg \}. $$ (Note: the difference is the space of function we are taking the supremum over). I claim that $$\tag{$\ast$}\text{if }C_\ast \text{ is independent of }\Omega \text{ then }C_\ast(\Omega,k,a) = \tilde C_\ast(k,a). $$ Indeed, for a given $\Omega$ and for all $u\in C^\infty_0(\mathbb R^n) \cap \mathcal H^s_0(\Omega)$ such that $[u]_{s_k}=1$, we have that $$ \sum_{j=1}^k a_j [u]_{s_j}^2 \leqslant \tilde C_\ast(k,a).  $$ Hence, by density of $C^\infty_0(\mathbb R^n) \cap \mathcal H^s_0(\Omega)$ in $\mathcal H^s_0(\Omega)$, for any open bounded $\Omega\subset \mathbb R^n$, we have that $$C_\ast(\Omega,k,a) \leqslant \tilde C_\ast(k,a).  $$ Moreover, for all $u\in C^\infty_0(\mathbb R^n)$ such that $[u]_{s_k}=1$, we have that $$ \sum_{j=1}^k a_j [u]_{s_j}^2 \leqslant C_\ast (\operatorname{supp}u,k,a ) .$$  Hence, if $C_\ast$ is independent of $\Omega$ then $\tilde C_\ast(k,a)\leqslant C_\ast (k,a )$ from which $(\ast)$ follows.
Now, let $\lambda >0$ and $u_\lambda(x):=u(\lambda x)$. We have that $$ [u_\lambda]_s = \int_{\mathbb R^n}\int_{\mathbb R^n} \frac{\vert u(\lambda x)-u(\lambda y)\vert^2}{\vert x- y \vert^{n+2s}} \, dy \, dx =\int_{\mathbb R^n}\int_{\mathbb R^n} \frac{\vert u(x)-u(u)\vert^2}{\lambda^{-n-2s}\vert x- y \vert^{n+2s}} \lambda^{-2n} \, dy \, dx = \lambda^{2s-n}[u]_s. $$ Next, let $b_\lambda = \{b_{\lambda,j}\}_{j=1}^k$ with $$ b_{\lambda,j}:= a_j \lambda^{n-2s_j} \bigg ( \sum_{j=1}^k a_j \lambda^{n-2s_j} \bigg )^{-1}. $$ By construction, $\sum_{j=1}^k b_{\lambda_j}=1$. Hence, if $C_\ast$ is independent of $\Omega$ then, using $(\ast)$, we have that for all $u \in C^\infty_0(\mathbb R^n)$, \begin{align*}
\sum_{j=1}^k a_j [u]_{s_j}^2 &= \sum_{j=1}^k a_j \lambda^{n-2s} [u_\lambda]_{s_j}^2\\
&= \bigg ( \sum_{j=1}^k a_j \lambda^{n-2s_j} \bigg ) \bigg ( \sum_{j=1}^k b_j [u_\lambda]_{s_j}^2 \bigg ) \\
&\leqslant C_\ast(k,b_\lambda)  \bigg ( \sum_{j=1}^k a_j \lambda^{n-2s_j} \bigg )[u_\lambda]_{s_k}\\
&=C_\ast(k,b_\lambda)  \bigg ( \sum_{j=1}^k a_j \lambda^{2(s_k-s_j)} \bigg )[u]_{s_k} \\
&= C_\ast(k,b_\lambda)  \bigg ( \sum_{j=1}^k a_j \lambda^{2(s_k-s_j)} \bigg ).
\end{align*} It follows that, $$C_\ast(k,a) \leqslant C_\ast(k,b_\lambda)   \sum_{j=1}^k a_j \lambda^{2(s_k-s_j)}  $$ for $\lambda>0$. However, if $C_\ast$ is also independent of $a$ then this implies that $\sum_{j=1}^k a_j \lambda^{2(s_k-s_j)} \geqslant 1 $ for all $\lambda>0$, so $$ 1\leqslant \lim_{\lambda\to 0^+}\sum_{j=1}^k a_j \lambda^{2(s_k-s_j)}=a_k<1  $$ which is a contradiction. In particular, this proves that $C_\ast$ cannot be equal to $k$.

The answer is not (c): Let $u \in \mathcal H^s_0(\Omega)$ be such that $[u]_{s_k}=1$. By Proposition 2.1 in Hitchhiker's guide to the fractional Sobolev spaces, for each $i=1,\dots,k-1$ we have that$$ [u]_{s_i} \leqslant C_i \big ( \|u\|_{L^2(\mathbb R^n)}^2 +[u]_{s_k}^2 \big ) = C_i \big ( \|u\|_{L^2(\mathbb R^n)}^2 +1 \big )   $$ with $C_i$ a constant depending only on $n$ and $s_i$. Then, since $u\in \mathcal H^s_0(\Omega)$, using that $2<2^\star_{s_k}:=\frac{2n}{n-2s_k}$, it follows from the Hölder inequality and the fractional Sobolev inequality (Theorem 6.5 in Hitchhiker's guide), that \begin{align*}
\| u\|_{L^2(\mathbb R^n)}&= \| u\|_{L^2(\Omega)} \\
&\leqslant C(\Omega,n,s_k) \| u\|_{L^{2^\star_{s_k}}(\Omega)} \\
&=C(\Omega,n,s_k) \| u\|_{L^{2^\star_{s_k}}(\mathbb R^n)} \\
&\leqslant C(\Omega,n,s_k) [u]_{s_k} \\
&=C(\Omega,n,s_k).
\end{align*} Thus, each $[u]_{s_i}$ is bounded independently of $u$, so $C_\ast<+\infty$.
Comment: Let me know if you have any questions or if you find an error :)

Cross test: Gagliardo seminorm


Mapping values inside pandas column

Question: I used the code below to map the 2 values inside S column to 0 but it didn't work. Any suggestion on how to solve this?
N.B : I want to implement an external function inside the map.
 df = pd.DataFrame({
   'Age': [30,40,50,60,70,80],
   'Sex': ['F','M','M','F','M','F'],
   'S'  : [1,1,2,2,1,2]
 })
 def app(value):
     for n in df['S']:
         if n == 1:
             return 1
         if n == 2:
             return 0
 df["S"] = df.S.map(app)

Answer: Don't use apply, simply use loc to assign the values:
df.loc[df.S.eq(2), 'S'] = 0

   Age Sex  S
0   30   F  1
1   40   M  1
2   50   M  0
3   60   F  0
4   70   M  1
5   80   F  0

If you need a more performant option, use np.select. This is also more scalable, as you can always add more conditions:
df['S'] = np.select([df.S.eq(2)], [0], 1)

Answer: Use eq to create a boolean series and conver that boolean series to int with astype:
df['S'] = df['S'].eq(1).astype(int)

OR
df['S'] = (df['S'] == 1).astype(int)

Output:
   Age Sex  S
0   30   F  1
1   40   M  1
2   50   M  0
3   60   F  0
4   70   M  1
5   80   F  0

Comment: @user3483203 you can try mask , should be faster :-) `df.S.mask(df.S>1,0)
`
Comment: Hmm, this is much faster than assigning via `loc`
Comment: Yep, much faster, I need to use `mask` more :D
Answer: You're close but you need a few corrections. Since you want to use a function, remove the for loop and replace n with value. Additionally, use apply instead of map. Apply operates on the entire column at once. See this answer for how to properly use apply vs applymap vs map
def app(value):
    if value == 1:
        return 1
    elif value == 2:
        return 0
df['S'] = df.S.apply(app)
   Age Sex  S
0   30   F  1
1   40   M  1
2   50   M  0
3   60   F  0
4   70   M  1
5   80   F  0

Answer: You can do:
import numpy as np

df['S'] = np.where(df['S'] == 2, 0, df['S'])

Answer: If you only wish to change values equal to 2, you can use pd.DataFrame.loc:
df.loc[df['S'] == 0, 'S'] = 0

pd.Series.apply is not recommend and this is just a thinly veiled, inefficient loop.
Answer: You could use .replace as follows:
df["S"] = df["S"].replace([2], 0)
This will replace all of 2 values to 0 in one line
Answer: Go with vectorize numpy operation:
df['S'] = np.abs(df['S'] - 2)

and stand yourself out from competitions in interviews and SO answers :)
Answer: >>>df = pd.DataFrame({'Age':[30,40,50,60,70,80],'Sex':
 ['F','M','M','F','M','F'],'S':
 [1,1,2,2,1,2]})

>>> def app(value):
        return 1 if value == 1 else 0
    # or app = lambda value : 1 if value == 1 else 0

>>> df["S"] = df["S"].map(app)

>>> df
   Age  S Sex
      Age  S Sex
   0   30  1   F
   1   40  1   M
   2   50  0   M
   3   60  0   F
   4   70  1   M
   5   80  0   F

Mapping values inside pandas column


Needs to Add Instagram in Beautifo WordPress Theme

Question: I have just purchase a new theme for my beauty shop (Beautifo theme) from Themelexus author.
And now i don't know I would like to add Instagram in our website. Anybody help me? Thanks in advance.
Answer: There is a widget you can add of Instagram to your theme. Also, you can add FB too. It will have live photos.
Answer: I see this theme supports by Elementor. You can use Elementor to add a widget and import Instagram to your theme.
I checked theme guide, you can follow: https://wpdocs.gitbook.io/beautifo/faq/faqs/how-to-add-instagram-in-wordpress
You can add for yourself or ask theme provider to get urgent support.
Thanks


Código PHP dentro de JQuery, é possível?

Question: Tenho uma aplicação e nela uso JQuery e a função que estou com problemas é o seguinte:
Quando o usuário clica no botão + chama o JQuery que lê um conteúdo HTML e PHP e executa numa linha abaixo para inserir um novo registro, porém com o PHP não quer funcionar. Como faço?

(function($) {

  RemoveTableRow = function(handler) {
    var tr = $(handler).closest('tr');

    tr.fadeOut(400, function() {
      tr.remove();
    });

    return false;
  };

  var counter = 1;
  jQuery('a.add').click(function(event) {
    event.preventDefault();
    counter++;
    var newRow = jQuery(
      '
' +
      '' +
      '
' +
      '<select name="Produto" id="produto" class="form-control select2" style="width: 100%;">' +
      <?php
          $sql = "SELECT id_Produto, cod_Produto, dsc_Produto from produtos ORDER BY cod_Produto ASC";
          $resultado = mysql_query($sql);

          while ($linha = mysql_fetch_array($resultado)) {
              $id_Produto = $linha['id_Produto'];
              $cod_Produto = $linha['cod_Produto'];
              $dsc_Produto = $linha['dsc_Produto'];

              echo"<option value='$id_Produto'> $cod_Produto  |  $dsc_Produto   </option>";
          }
      ?>
      '</select>' +
      '
 ' +
      '	' +
      '	' +
      '<input type="text" class="form-control" name="volume" id="volume" style="width: 50px; margin: 0;">	' +
      '<input type="text" class="form-control" name="quantidade" id="quantidade" style="width: 60px; margin: 0">	' +
      '	' +
      '	' +
      '	' +
      '	' +
      '	' +
      '	' +
      '
'
    );
    jQuery('table.table-bordered').append(newRow);
  });

})(jQuery);
Comment: Sim é possível mas não vai funcionar da maneira que você espera. Lembre que o php executa no lado servidor (apenas uma vez por requisição) e o javascript no lado cliente. O mais recomendado é utilizar um ajax para montar esses combos caso tenham valores diferentes se forem iguais pode clonar o elemento.
Comment: Como assim? De qual forma?
Answer: Você está usando um arquivo .js ou seja, só javascript pode ser executado aí dentro, se você quiser executar PHP e javascript, teria de fazer algo do tipo:
//arquivo script.php

<?php
foreach ($usuarios as $bla) {
    echo $bla;
} //só um exemplo
?>

Mas aqui o PHP iria executar primeiro e não poderia executar novamente.
Solução: Use Requisições AJAX. Cada vez que o usuário clicar neste botão, envie uma requisição ajax para um arquivo separado, assim a cada requisição o PHP será executado separadamente e retornará o HTML desejado.
Comment: Veja alguns tutorias na internet (youtube) tem este site da w3schools, que muita gente fala que está antigo, mas é bom pra quem ta começando: https://www.w3schools.com/xml/ajax_intro.asp um melhor seria o site da mozilla , O MDN https://developer.mozilla.org/pt-BR/
Comment: Como posso fazer isso?


Why can't I find any pages after migrating a site?

Question: I need to migrate a drupal site from one host to another. I didn't create the original. I tried using "Backup & Migrate", and I also tried to export the sql database in phpmyadmin from old site, import into new site, and move the file manually with ftp. My new host is GoDaddy. I can change that if GoDaddy causes issues!
Here is the problem, The theme used in the old site appears as an option, I can choose it, and the site works, but no content is there at all. All the modules show up in the new environment, still no content. I go to search for content, still no content. I can't find any pages anywhere!!!
Any help?
Comment: do you have phpMyAdmin or something to browse the database?
Answer: So, the usual way to do this is like this.

dump all caches and back up the database
clean drupal install on your new server
move the db to your new server
configure proper db user on new server
copy the sites folder to the new server
make sure settings.php is correct for new server config
run update.php

It's not clear from your description exactly what's happened, but I would try it again. From what you describe, it doesn't sound like you followed all the steps for a normal site migration, so you need to make sure all the stuff drupal needs is there. I've also had some issues with folder permissions when moving stuff to Godaddy, so you can look at that too.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/33770/discussion-on-answer-by-nizz0k-migrating-a-drupal-site).
Answer: OK, I fixed it!!!!
I'm really hoping this helps someone else at some point.
Detailed problem:
I was migrating a drupal site from a private host to GoDaddy subdomain host to test the files and sql db before going to live environment.
Drupal site migrated and everything looks right but no content is listed. No pages, no media, nothing. The proper theme was available as an option, but not selected.
in the settings.php file, the prefix that godaddy installed for me was "drup_", but my imported database tables didn't have "drup_" as a prefix.
Fix:
nizz0k was very helpful in pointing out that I need to run update.php. I had already tried that, but his comment about godaddy not allowing enough ram gave me the idea to increase the ammount of ram from godaddy. The error I was getting before increasing the ram, had to do with "not enough ram or exceeding available ram" something like that. As soon as i increased the resource level with godaddy, the update script worked.
So, to wrap it up, if you are hosting with godaddy, beware of the prefix.

I had godaddy install the drupal app for me in the subdomain
imported the sql db from my old host
imported the files using ftp
edited the settings.php file to get rid of the "drup_" prefix that godaddy had
go to site.com/q=user to log into the site and have permissions
go to site.com/update.php to update things

That's what worked for me. I'm really hoping this helps someone out. I was looking for something about this for more than 5 days before I posted the question.
Again, thank you so much for this website for hosting the forum, and most certainly thanks to nizz0k for the prompt response and excellent idea's!!
Comment: IMO you should accept nizz0k's answer as what you wrote is pretty much #5 #6 #7 on his list.
Comment: What threw everything off was that you used the GoDaddy installer rather than just transferring all of the Drupal files with ftp.


How do I build a node native module with rpath in AWS Lambda?

Question: I'm trying to use node-phash in an aws lambda function, but coming-up short.
I've found instructions for the node-canvas library here and on github, but still having some trouble.
Steps I've taken:

on an Amazon Linux ec2 instance, I've cloned the node-phash repo
I set an env var to use an rpath, as the node-canvas walkthrough instructed:
export LDFLAGS=-Wl,-rpath=/var/task/
I determined the shared deps:
$ readelf -d pHashBinding.node | grep NEEDED
  0x0000000000000001 (NEEDED)             Shared library:      [libstdc++.so.6]
  0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
  0x0000000000000001 (NEEDED)             Shared library: [libgcc_s.so.1]
  0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
  0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

I then copied and downloaded the listed files to include in my zip for lambda
I ran npm install, which went ostensibly fine
I confirmed that the .node would look at the aws lambda root for its deps:
 $ objdump -p build/Release/pHashBinding.node | grep RPATH
    RPATH                /var/task/

I then downloaded the build/Release folder and overwrote my project's node_modules/phash/build/Release with the folder from the Amazon Linux environment
I zipped my project for upload to Lambda, including the 5 *.o files from step 3 into the root of the zip, so they'd be unzipped at /var/task/ in Lambda

Unfortunately, after all that, I still get the same errors I did before:
"errorMessage": "/usr/local/lib64/node-v4.3.x/lib/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by /var/task/node_modules/node-phash/build/Release/pHashBinding.node)",
  "errorType": "Error",
  "stackTrace": [
    "Object.Module._extensions..node (module.js:434:18)",
    "Module.load (module.js:343:32)",
    "Function.Module._load (module.js:300:12)",
    "Module.require (module.js:353:17)",
    "require (internal/module.js:12:17)",
    "Object.<anonymous> (/var/task/node_modules/node-phash/lib/phash.js:23:13)",
    "Module._compile (module.js:409:26)",
    "Object.Module._extensions..js (module.js:416:10)",
    "Module.load (module.js:343:32)"
  ]
}

libstdc++.so.6 is in the root of my zip.  So, how do I get pHashBinding.node to reference the correct directory when looking for dependencies?
Comment: op here--if anyone finds themselves in a similar predicament, I eventually just resorted to using a [python image hashing library](https://github.com/JohannesBuchner/imagehash) for this function. I'm not great at Python, but I was able to get a functional microservice setup in short order (and most of the native dependencies for python are widely avail. as prebuilt on aws linux)
Answer: I know this is an older question but I was struggling with this and managed to find a solution that might work for you as well.
This solution comes from a GitHub discussion here https://github.com/grpc/grpc/issues/6443#issuecomment-270558452
Basically you should use Docker to install your packages when you are ready to deploy to AWS Lambda.

Delete the node_modules folder inside your project.
Open terminal and cd into your project folder.
Run this command docker run --rm -it -v "$PWD":/worker -w /worker node:4.2 npm i --production --silent

Afterwards you should see a node_modules folder in your project, this can now be zipped up and uploaded to AWS Lambda.
This should work for any dependencies that require native code when npm install is run.
Hope this helps!
Comment: Docker is not needed (only for this specifc scenario) if you're already using Linux.


Multiple layers on TMAP

Question: I have a dataframe looking like this:
dataframe
Id is the zip code and the columns go from 2015 to 2019.
Link to download the database (with the .shp file needed to execute this program)

library(dplyr)
library(sf) # pour gérer les fichiers shapefile
library(ggplot2)
library(tmap) # pour créer une carte
library(leaflet)
library(stringi) # pour le problème d'encodage du fichier shapefile
library(maptools)
library(mapview) # permet une carte dynamique

base= read.csv("../bddlongsubstance.csv", stringsAsFactors = FALSE, encoding = "UTF-8", sep= ",", dec= ".")
base= data.frame(base)
base$code_postal_acheteur= as.factor(base$code_postal_acheteur)
names(base)[1]= "ID"

codes_postaux= st_read(dsn = "../codes_postaux_V5/codes_postaux_region.shp",
                       layer = "codes_postaux_region",
                       quiet = TRUE) %>%
  select(ID, LIB, DEP)

codes_postaux$LIB= stri_encode(codes_postaux$LIB, from= "ISO-8859-1", to= "utf8")

fusion= codes_postaux %>%
  left_join(base[1:17], by= "ID") %>%
  st_transform(2154)
summary(fusion)

tmap_mode(mode= "view")
autre_2015=
  tm_basemap("CartoDB.Voyager")+ tm_shape(shp= fusion)+
  tm_fill(col= "Autre_quantite.totale.2015", palette= "YlOrBr", id= "ID",
          textNA = "Valeur manquante", style = "quantile", n= 6, title= "Quantité totale :
 Catégorie AUTRE",
          popup.vars = c("Ville"= "LIB", "Quantité"= "Autre_quantite.totale.2015"))+
  tm_borders("black", lwd= 0.3, alpha= 0.6)+
  tm_layout(title = "Quantité de substances phytopharmaceutiques achetées en 2015 (en kilogrammes)", title.position = c("center", "bottom"), legend.bg.color = "white", legend.bg.alpha = 0.4)+
  tm_scale_bar(position = c("left", "bottom"))+
  tm_view(view.legend.position = c("right", "bottom"))

tmap_mode(mode= "view")
toxique_2015=
  tm_basemap("CartoDB.Voyager")+ tm_shape(shp= fusion)+
  tm_fill(col= "Toxique_quantite.totale.2015", palette= "YlOrBr", id= "ID",
          textNA = "Valeur manquante", style = "quantile", n= 6, title= "Quantité totale :
 Catégorie TOXIQUE",
          popup.vars = c("Ville"= "LIB", "Quantité"= "Toxique_quantite.totale.2015"))+
  tm_borders("black", lwd= 0.3, alpha= 0.6)+
  tm_layout(title = "Quantité de substances phytopharmaceutiques achetées en 2015 (en kilogrammes)", title.position = c("center", "bottom"), legend.bg.color = "white", legend.bg.alpha = 0.4)+
  tm_scale_bar(position = c("left", "bottom"))+
  tm_view(view.legend.position = c("right", "bottom"))

with this code I can only generate one map simultaneously that looks like this:
picture of the map
but ideally, I would like a system with multiple layers and where I can select whatever column from the dataframe i want to display but I really can't find how to.
Thanks
Comment: yep, it did work, thank you man I wouldn't have find without you !
Comment: Not sure if this is possible when using "view" mode alone. There exists tmapProxy to update the map (more specifically, to add and remove layers) when using tmap in Shiny via [renderTmap](https://www.rdocumentation.org/packages/tmap/versions/3.3-3/topics/renderTmap). Depends on in which context you want to use your interactive map.
Comment: The goal is to have an online map, exactly like this: vincentchangeon.shinyapps.io/testtest but with the option to select the column of my dataframe i want to plot
Comment: Then renderTmap allows to do what you want. I suggest to play around with the example given in the documentation using `tmapProxy` and  `tm_remove_layer`.
Answer: Here is an alternative solution that allows you to create an interactive choropleth using tmap and leaflet programatically with as many layers as you want.
I am unable to download the data at the link provided, so I use an example dataset from the spData package.
library(tmap)
library(leaflet)
library(sf)
library(tidyverse)
library(spData)

#Set to interactive mode:
tmap_mode(mode = "view")

#Get data from spData package:
nz <- nz

#Create a function that allows you to make as many layers as you want:
#' create_tm_;ayer
#'
#' @param data - an sf dataframe
#' @param column - a string that is a column name in data
#'
#' @return - a tmap map

create_tm_layer <- function(data, column) {
  tm_shape(data,
           name = column) +
    tm_fill(col = column)

}

#Iterate over function with as many column names as you want
tmap_mode(mode="view")

columns <- c("Median_income", "Sex_ratio", "Population")

# This configures Population to be the variable that appears at first
variables_to_start_hidden <- columns[columns != "Population"]

results <- map(create_tm_layer, data = nz, .x = columns)

tmap_results <- Reduce(`+`, results)

tmap_leaflet_results <- tmap_leaflet(tmap_results) %>%
  hideGroup(variables_to_start_hidden)

Multiple layers on TMAP


Why is there a  tag where I didn't add it?

Question: I put the following code into the bock content box and set the input type to Full HTML; then I enabled it on page--front.tpl.php. When I viewed the HTML source, I
saw the  label contained a
 tag.

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test/strong>

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

For example, for the last list item, the output was the following.

tsdet
Fujia Chanpin 01

Why is there a
 tag where I didn't add it?
Answer: For not getting the paragraph tags, you need to use an input format that does not include the Lines and paragraphs break automatically setting.
Check to see if Convert line breaks into HTML input format is enabled in admin/config/content/formats/full_html, and disable it. You can still add
 and
, but Drupal will not add them automatically for every line break present in the text.
Comment: check to see if `Convert line breaks into HTML` is enabled `/admin/config/content/formats/full_html` and disable it. You can still use your own p and br, but Drupal will not convert it automatically.
Comment: but my code needs paragraph and break tags.how do i do?


Passing a Variable to a system stored procedure

Question: I am sure I am missing something simple. I am looking to map some of my data objects. I wanted to create a procedure would insert the results of sp_depends and insert data name.
Here is what I have created:
create table DatasetMapping
(
    Name nvarchar(257),
    Type nvarchar(16),
    updated nvarchar(7),
    Selected nvarchar(8),
    Column sysname
);

Insert into DatasetMapping
    exec sp_depends 'dbo.PositionReport_Quote_V3_2016'

This works great manually.
I then created
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Repotingdatasets]
AS
    DECLARE @object NVARCHAR(257)

    INSERT INTO DatasetMapping
        EXEC sp_epends  @objname = @object

    EXEC [dbo].[Repotingdatasets] @object =' dbo.PositionReport_Quote_V3_2016';

but I only get an error:

Msg 8146, Level 16, State 2, Procedure Repotingdatasets, Line 0 [Batch Start Line 48]
  Procedure Repotingdatasets has no parameters and arguments were supplied
Comment: Can I pass the @object into my insert statement and add it to my table as object name.  thanks
Answer: You just need to change some syntax:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[Repotingdatasets](
@object     nvarchar(257)
)
as

Insert into DatasetMapping
exec sp_depends  @objname=@object

exec [dbo].[Repotingdatasets]  @object =' dbo.PositionReport_Quote_V3_2016';

Answer: You don't declare the variable like that if you intend to pass it.  You're looking for this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Repotingdatasets] @object nvarchar(257)
AS
BEGIN

INSERT INTO DatasetMapping
EXEC sp_depends  @objname=@object

END

Then..
EXEC [dbo].[Repotingdatasets]  @object =' dbo.PositionReport_Quote_V3_2016';

If you want a default value add it to the same spot:
CREATE PROCEDURE [dbo].[Repotingdatasets] @object nvarchar(257) = 'default'


Trigger é executada somente após fechar a aplicação (JPA)

Question: Eu possuo a seguinte Trigger no meu Banco:
<code>    CREATE OR REPLACE function calcula_avaliacao_fisica()
RETURNS TRIGGER AS $$
BEGIN
    UPDATE avaliacao_fisica SET imc = calcula_imc(NEW.peso, NEW.altura/100) WHERE codigo = NEW.codigo;
    UPDATE avaliacao_fisica SET percentual_gordura = calcula_percentual_gordura(NEW.peso, NEW.peso_gordura) WHERE codigo = NEW.codigo;
    UPDATE avaliacao_fisica SET percentual_massa_magra = calcula_percentual_gordura(NEW.peso, NEW.peso_massa_magra) WHERE codigo = NEW.codigo;

    RETURN NEW;
END
$$ LANGUAGE PLPGSQL;

CREATE TRIGGER calcula_avaliacao_fisica AFTER INSERT ON avaliacao_fisica
FOR EACH ROW EXECUTE PROCEDURE calcula_avaliacao_fisica();
</code>
A ideia dela é calcular alguns atributos da minha tabela de avaliações físicas.
Além disso, tenho o meu método de inserir utilizando JPA:
<code>public void inserir(AvaliacaoFisica avaliacao) {
    EntityManager em = this.emf.createEntityManager();

    em.getTransaction().begin();
    em.persist(avaliacao);
    em.getTransaction().commit();

    em.close();
}
</code>
O problema que estou encontrado é que a trigger executa somente após eu fechar minha aplicação.
Por exemplo, eu realizo o cadastro de uma nova avaliação física e após esse cadastro solicito a exibição da mesma. Quando eu for visualizar essa avaliação, o IMC (exemplo) estará com o valor padrão de 0.
No entanto, após eu encerrar o build da minha aplicação, buildar novamente e solicitar a exibição da mesma avaliação física, os dados apareceram calculados corretamente.
Alguém tem ideia de como resolver esse erro? Parece que o JPA executa as trigger's somente após encerrar a execução.
Answer: O problema era Cache!
Desativei o cache do JPA mudando essa propriedade no persistence.xml:
Comment: Leandro, sua resposta resolveu seu problema e aparentemente está correta, por favor, classifique-a como tal para que outras pessoas da comunidade possam se beneficiar disso no futuro.


What is the 'true' value of a probability parameter?

Question: We seem to distinguish empirical estimates of parameters from 'true' values, and make comparisons between the two. I can understand what an empirical estimate is. What is a 'true' value?
For instance, my course notes have:

Definition 4.7 (Consistent estimator) An estimator $T(X_1,...,X_n)$ for a parameter $\theta$ is consistent if, for any $\epsilon>0$, we have
  $$
\lim_{n\rightarrow\infty}P(|T(X_1,...,X_n)-\theta|<\epsilon)=1
$$

How do we determine $\theta$ apart from by estimating it, in order to compare it to an estimator?
Comment: @mjc the modeled value is always an estimator. What you describe, first assuming that the probability is $0.01$ and then later observing that $0.5$ is better, is the way the estimator tends probabilistically towards the true value. So anything that you use in practice is always (except simulation studies) an estimator. In your example you assumed that the coin ACTUALLY has a probability of $0.5$. That is the true value, you gave it by DEFINITION. In practice the true value can never be determined or observed, it can only be estimated.
Comment: A parameter is any definite quantitative property of the "box" that models a population or process.  See https://stats.stackexchange.com/a/54894/919.
Comment: @mjc Not quite. 3 is correct. But whenever you "observe" something, you have to make inferences. I can't "observe" the mean of a sample, you have to compute it from the data.  Likewise, you can't "observe" the probability of a coin, you have to calculate it. So 1 and 2 should be the same thing. If you calculate the probability of a coin from observed tosses, you are using a model. So what you call "observation" (dividing heads by total tosses) is fitting a model. Any model should provide a consistent estimator, so 1 and 2 are just two different (hopefully) consistent estimators.
Comment: @mjc If $f$ is consistent with $\theta_1$ does not depend on $d$. Consistency is a theoretical property of an estimator, not one that depends on the sample $d\subset D$. That's why it must converge probabilistically, and not deterministically. If you get a bad sample, your estimate can be as much of as you like, it's just very improbable to get such a bad sample, if you have a lot of observations. As for the model: You mean a predictive model? The best predictive model should match the generating process. In that case $\theta_1=\theta_2$. For wrong models (i.e. all models): more complicated.
Comment: Could you share some context? Where did you saw this term? It may be important for getting adequate answer.
Comment: I agree with Tim. Context will be crucial. Do you mean the $p$ parameter in a binomial or a Bernoulli distribution?
Comment: @Tim I've edited the OP to add an example.
Comment: @Dave See above.
Comment: @whuber How does this sound? What I called the 'true' value is really the 'modelled' value. This is arbitrary in principle and usually empirically or theoretically determined in practice. If we want, we can assign a probability parameter of 0.01 to throwing heads on an unweighted coin. Once we've conducted a long experiment and observed empirically that it lands heads at a rate of around 0.5, we start to think 0.5 might be a better probability parameter to use, and tune our model to reflect observations.
Comment: @LiKao So we have three values, I think. 1) The empirically observed value; 2) the theoretically modeled value; and 3) the unobserved and unobservable 'true' value, a property of physics under a suitable philosophy (e.g. Platonism). Would you agree?
Comment: @LiKao How's this? We can take a function $f$ (e.g. sample mean) of a dataset $d\subset D$ and make one of two uses of it: a) use the output of $f$ as a parameter $\theta_1$ in a model $M$; or b) use $f$ itself as an estimator $T$ for some other parameter, $\theta_2$. Used as an estimator, $f=T$ will be consistent i) with observations on the whole of $D$ iff $d$ happens to be perfectly representative of $D$; ii) with $\theta_2$ if $f=T$ converges to $\theta_2$ over a given (perhaps infinite) number of observations.
Answer: In general the "true value" is a fiction, defined within a model that in reality won't fit perfectly, in which case consequently there is also no such thing as a "true value". Assuming that there is a true parameter value is a device for doing theory and developing methods. It allows us to theoretically show that this-or-that method to estimate it has this-or-that property and works better or worse, which is a motivation for these methods even though it doesn't correspond exactly to the real situation (but then no model does).
If we simulate artificial data, however, we can fix and control the true parameter values, in which case we can compare the estimate to the true value (ignoring here potential issues with random number generation).
There are also some real situations in which true values can be "controlled" or known to some extent, for example if we have a measurement instrument that is meant to measure a certain quantity with stochastic measurement error, and in some situations we may be able to control the quantity that is measured. This still cannot guarantee the truth of the measurement error model within which the model parameter is defined, but at least we can control the real quantity that is interpreted to correspond to the true parameter value.
An example for this are indirect estimates from age determination methods applied to individuals of which we know the precise age.
Sometimes we estimate parameters that correspond to existing population quantities of a usually big but finite population (such as population means of something that is well defined for all population members such as age) from a sample, in which case the population quantity would correspond to the "true" parameter value.
Answer: It all boils down to theory vs. practice.
The true value of a parameter is always a theoretical quantity. Thus, you can never determine the true $\theta$.
The idea behind this is, that there is some kind of process, which generates the data. This process has some parameter. If you knew that parameter and the process you could generate data, which would be indistinguishable from the real process. Other parameters always generate data, which can eventually be distinguished from the real process.
The only way to "know" the true $\theta$ is if you define the process mathematically. For example, if you define a fair coin, then the true probability of showing heads is $0.5$, but not because you determine it by an experiment, but because you defined it to be.
A consistent estimator will tend (probabilistically!) towards the true value, which is captured by the definition you provided. As you collect more data, the probability that the consistent estimator differs by a certain amount $\epsilon$ from the true value goes towards zero (NOTE: it is a common misconception that probability of zero means something never happens, but that is not necessarily true. It only means, it practically never happens).
So if you want to "determine" a true value just based on the data alone, a consistent estimator is your best method. You can never be sure, that you really got the right value (which is why any estimator should come with confidence intervals, etc).
Now, how do you know an estimator is a consistent estimator if you can't know the true value in practice? If some estimator is consistent is not a practical observation, but a theoretical property. Thus, you prove (theory!) that something is a consistent estimator.
Take for example the expected value and variance (true parameters) of a normal distributed variable (the process). The mean of the samples is a consistent estimator of the expected value. So you define $X \sim Normal(\mu,\sigma^2)$ (i.e. $\theta = (\mu,\sigma)$), and then you prove (!) that the mean will tend probabilistically towards $\mu$ for any $\mu$ and $\sigma$. Then you know, that the method you have just proven can be applied in practice to estimate the true $\mu$.