Bayesian Naive Classifier with 0 variance

Question: I am experimenting with the Bayesian Naive Classifier and I have come across a situation for which I wasn't able to find a solution on the net.
Suppose you have a dataset with a few attributes that takes real values. The values of the observations varies around a mean as they typically do -- except for a particular attribute and for a particular class where all observations have the same value.
For that particular attribute-class subset, the variance will be 0 and the probability density for such a distribution will be infinity for any 'x'.
How should a BNC handle such situations? Should we discard an attribute if it has a degenerate (zero variance) distribution for any class even if it has a normal distribution otherwise?
Edit:
I'd rather not ignore them if possible. They may have a lot of information, just not for the class for which variance is 0. I'll try to explain myself:
Suppose you have a bowl of cookies, some of them were made by a machine and the others were handmade and you want to classify them (as well as eating them). One of the attributes you use to classify is the diameter of the cookie. A handmade cookie will have a good variance while the machine-made ones all have the same (0 variance).
Say all machine-made cookie are all 2.5 inches in diameter. I agree that picking a 2.5 inch cookie at random will give us no useful information; but picking a 3 inch cookie is a pretty strong indication that is was handmade.
In the case of a 0 variance distribution, I was thinking making the Probability Density function return a 1.0 (neutral) when 'x' is the mean and 0.0 when it's not. But I'm not experienced enough in statistics to understand the possible side-effects of this.
Answer: Within statistics, all is uncertain, also the class membership of each pattern. Probabilities that are purely 0 and 1, that indicates a deterministic mechanism, for which statistics was not developed. As soon as uncertainty comes into play, a deterministic paradigm is left and it becomes statistics and probability theory.
When you can with 100% certainty (on a very large, representative dataset) classify all patterns correctly, you get into the deterministic situation. Boolean algebra with truth-predicates and (in)equalities are sufficient to represent the classification rule.
Comment: Thanks Match Maker. If I understand correctly, you say that in situations like the cookie problem, I don't need a classifier; a _if()_ would do just fine.
Comment: Correct - that is the point I wanted to make.
Answer: The PDF is the probability density function. What you're describing doesn't have a  density of 1 at the mean, it has a probability mass of 1 at the mean. If you really are certain that the variance of machine cookies is zero, then you should classify all cookies that don't have the mean of machine cookies as homemade cookies with probability 1. If a cookie does have the mean of machine cookies, then your probability of being a homemade cookie should be prior * x/(prior * x+1-prior), where x is the probability mass of (diameter=machine mean|homemade). If you have infinite precision, x=0. Otherwise, if you have an interval I such that if the actual diameter is in I, the measured diameter will be the machine mean, then x is the integral of the PDF of the diameter for homemade cookies over I.
As for where the formula prior * x/(prior * x+1-prior) comes from:
The number of homemade cookies with a machine mean is proportional to the prior probability times the conditional probability, prior * x. For machine cookies, the conditional probability is 1, so it's just the prior probability of machine, which is 1-(prior probability of homemade).
Often, when learning about conditional probabilities, it's easier to work with proportions rather than percentages (that is, "10 out of 100" is more concrete than "10%"). If you're having trouble following an argument, putting in integers and taking successively smaller portion of the total as more conditions are added can help.
For example, suppose there are 1000 cookies, and 20% of the total number of cookies are homemade. And suppose that 10% of homemade cookies have the same diameter as machine cookies. Then the number of homemade cookies with the machine mean is 1000*10%*20% = 20. Since 20% are homemade, 80%, or 800, are machine made. So there are 20+800 cookies with machine mean, and of them, 20 are homemade. So if you know a cookie has machine mean, the probability of it being homemade is 20/(20+800) = 2.4%.
Now, again, I introduced the 1000 just so that we would have integer cookies and the math would be easier to follow; the 1000 should of course cancel out, so if you take the formula
prior * x /(prior * x+1-prior)
and substitute in prior = 20%, x = 10%, you get
.2*.1/(.2*.1+.8) = .02/.82 = .024
Comment: Thanks a lot @Accumulation. I would be interested in knowing why the probability of being a homemade cookie should be prior * x/(prior * x+1-prior). Please can you tell me where this comes from? (Sorry if it's a basic stats question, but I'm pretty much a beginner)


2D FFT for Huge Matrix

Question: I have 2d Vector with 2533136*8 dimension like below :
vector<vector<double>> DataChannel1(2533136, vector<double>(8));

I want to take FFT from this Vector with fastest solution but I don not How!
can you help me How can I do that?
In addition to I used FFTW library but with my dimension(ROW=2533136 and COL=8) Take long time to calculate.
const auto ROWS = 2533136;
const auto COLS = 8;
fftw_complex in[ROWS][COLS], out[ROWS][COLS];
fftw_plan g;

g = fftw_plan_dft_2d(ROWS, COLS, *in, *out, FFTW_FORWARD, FFTW_MEASURE);

Comment: You might also want to clarify exactly what operation(s) the "5-7 seconds" refers to.  The `fftw_plan_dft_2d` call shown takes 24s on my own box event though a subsequent call to `fftw_execute(g)` only takes 0.5s.  If, on the other hand, I use `FFTW_ESTIMATE` rather than `FFTW_MEASURE` then `fftw_plan_dft_2d` takes 0.05s and `fftw_execute` 1s.
Comment: 1) What does "long time" mean? FFT is fast, but still takes some time to compute. 2) Is the result that you obtain with FFTW correct?
Comment: If your input data is strictly real (as suggested by the declaration of `DataChannel1`) then why create/execute a complex FFT?  You might also want to look at [multithreading](http://www.fftw.org/fftw3_doc/Usage-of-Multi_002dthreaded-FFTW.html#Usage-of-Multi_002dthreaded-FFTW)
Comment: Also, don't use a `vector>>`. This is about the worst way to store data. You can't even pass the pointer into FFTW. Use a simple `vector`, and compute the 1D index from the 2D (i,j) index.
Comment: Please show a [mre]. How do you copy data to FFTW to compute the FFT?
Comment: @Evg 1)"long time" means 5-7 second. 2)Yes it is correct but 5-7 second for one function is not suitable and efficient.
Comment: @G.M. Yes I used  'FFTW_ESTIMATE'  and my problem Solved :)
Answer: My Problem Solved And I am very thanksful from @G.M., He/She is considering my problem.
In My problem most of time spent in fftw_plan_dft_2d, I saw the FFTW documentation and understood the last input of this function is Planner Flags :
fftw_plan fftw_plan_dft_2d(int n0, int n1,
                       fftw_complex *in, fftw_complex *out,
                       int sign, unsigned flags)

All of the planner routines in FFTW accept an integer flags argument, which is a bitwise OR ('|') of zero or more of the flag constants defined below. These flags control the rigor (and time) of the planning process, and can also impose (or lift) restrictions on the type of transform algorithm that is employed.
Planning-rigor flags
FFTW_ESTIMATE specifies that, instead of actual measurements of different algorithms, a simple heuristic is used to pick a (probably sub-optimal) plan quickly. With this flag, the input/output arrays are not overwritten during planning.
FFTW_MEASURE tells FFTW to find an optimized plan by actually computing several FFTs and measuring their execution time. Depending on your machine, this can take some time (often a few seconds). FFTW_MEASURE is the default planning option.

2D FFT for Huge Matrix


Best exponential decay line greater than 95% of data

Question: I've got some data that has an exponential decay. And I want to do some curve fitting.
X = [x for x in range(0,900)]
N_0 = 300
m_lambda = .005
left_shift = 0
up_shift = 0

plt.close()
Y = [ N_0 * np.exp(1)**(-1*m_lambda*(m_x+left_shift)) + up_shift + np.random.normal(0,15) for m_x  in X]

Y_fit = [ N_0 * np.exp(1)**(-1*m_lambda*(m_x+left_shift)) + up_shift for m_x  in X]

plt.plot(X,Y,'o')
plt.plot(X,Y_fit,'-')

But the catch is, I don't want the best fit for all the data.  I want the best fit that keeps the line above 95% of the data.
Something like this
X = [x for x in range(0,900)]
N_0 = 300
m_lambda = .005
left_shift = 0
up_shift = 1

plt.close()
Y = [ N_0 * np.exp(1)**(-1*m_lambda*(m_x+left_shift)) + up_shift + np.random.normal(0,15) for m_x  in X]

Y_fit = [ N_0 * np.exp(1)**(-1*1.1*m_lambda*(m_x+left_shift)) + 30*up_shift for m_x  in X]

plt.plot(X,Y,'bo')
yy  = pd.DataFrame(Y)
yy = yy[yy>pd.DataFrame(Y_fit)].dropna()

plt.plot(yy.index,yy,'ro')
plt.plot(X,Y_fit,'-g')

My current plan is to just modify the parameters of the equation, but that is inefficient and not very rigorous.
So I was wondering if there's any known technique for getting the 'best' possible curve that lies under 5% of my data.
Comment: See [posts about quantile regression](http://stats.stackexchange.com/search?q=quantile+regression) for some approaches.
Answer: As whuber notes, quantile regression is what you want. You can simply exponentiate the model results from a log linear model to get the quantile. Here is an example in python:
import numpy as np
from statsmodels.regression.quantile_regression import QuantReg
import matplotlib.pyplot as plt
%matplotlib inline

x = np.random.gamma(1,1,size = 1000)
xx = np.linspace(0,6,101)
y = 10*np.exp(-x/2) + np.random.normal(0, 0.25, size = x.size)

plt.scatter(x,y, c = 'C0', alpha = 0.5, s = 5)

X = np.c_[np.ones_like(x), x]
XX = np.c_[np.ones_like(xx), xx]
model = QuantReg(np.log(y),X).fit(q = 0.95)

preds = np.exp(model.predict(XX))

plt.plot(xx, preds, color = 'red')

This yeilds the following plot

And as required, approx 95% of model predictions are above the data

np.mean(np.exp(model.predict(X))>y)

>>>0.949

```

Answer: If you add to the equation a constant value of, say, 25.0 then the existing parameter named "up_shift" will be adjusted by the nonlinear fitting algorithm to account for the added value.  When using the fitted equation, no longer add the fixed value - this will shift the fitted curve by the amount of the fixed constant.
Once you see that this is working, you can adjust the fitted curve up or down the Y axis as you please.
Answer: This may be just a little late, but like someone else has said, you want quantile regression. You can do this with pystan. Your family will be asymmetric laplace with quantile set to .95, set the mu_link to 'log', this will get you your exponential curve, and that is exactly what you want.


Como transformar uma data em formato objeto que contém dia mes ano e hora para somente dia mes ano

Question: De que forma da para converter data em formato objeto tendo dia, mês e o ano   hora, para somente com dia, mês e o ano para  realizer operações de soma de consumo de material por data?
Criei dessa forma mas algumas datas foram convertidas de forma errada;  dia invertido com o mês:
R3047['Machine types'] = R3047['Machine types'].astype('datetime64[ns]')
R3047['Machine types']=R3047['Machine types'].apply(lambda x: datetime.datetime.strftime(x, '%Y-%m-%d'))

Ao realizar alteração de  dias acabam se invertendo com o mês.
Answer: Uma solução é o uso do  pd.to_datetime  (notação importante de to_datetime)

Deprecated since version 2.0.0: A strict version of this argument is
now the default, passing it has no effect.

Essa nota afirma que versão 2.0.0 , qualquer conversões de data é mais específica.
E o argumento format pode ser omitido nas versões mais recentes do pandas.
E a omissão do format nesse caso ira inferir o formato  string data.
import pandas as pd

R3047['Machine types'] = pd.to_datetime(R3047['Machine types'], format='%d/%m/%Y %H:%M:%S')

R3047['Date'] = R3047['Machine types'].dt.strftime('%d/%m/%Y')

R3047 = R3047.drop(columns=['Machine types'])

print(R3047)

R3047['Machine types'] = pd.to_datetime(R3047['Machine types'], format='%d/%m/%Y %H:%M:%S')

R3047['Date'] = R3047['Machine types'].dt.date

R3047['Ano'] = R3047['Date'].dt.year
R3047['Mes'] = R3047['Date'].dt.month
R3047['Dia'] = R3047['Date'].dt.day

R3047 = R3047.drop(columns=['Machine types', 'Date'])

print(R3047['Ano'])
print(R3047['Mes'])
print(R3047['Dia'])

Os '%d/%m/%Y %H:%M:%S' é usado pelo motivo se contem esses detalhes todos deveram ser convertidos ou pode ser omitido %H:%M:%S.
R3047['Machine types'] = pd.to_datetime(R3047['Machine types'], format='%d/%m/%Y')

E o uso do drop é para apagar o uso da coluna ou a linha, Machine types sera removido
R3047 = R3047.drop(columns=['Machine types', 'Date'])

Comment: Ao editar as perguntas não esqueça de verificar as tags. Após lido sinalize o comentário como desnecessário.
Comment: Muito obrigada, segui a recomendação e funcionou! :)


While loop with strings in python not behaving as expected

Question: I'm new to Python and I'm learning about loops and conditions. I have the code:
import random
import sys
import os

test_file = open("test.txt", "wb") #use wb if write

append = ""
while append != "exit":
    print("Write something to append to file: ")
    append = sys.stdin.readline()
    test_file.write(bytes(append, 'UTF-8'))

test_file.close()

Now, whenever I type in 'exit', I would expect it to exit out of the loop, but for some reason, it doesn't. It continues to be what seems like an infinite loop. What could be the reason behind it? Thanks in advance.
Answer: readline() includes the \n newline character.
You could use append.strip().
In [1]: import sys

In [2]: append = sys.stdin.readline()
test

In [3]: append
Out[3]: 'test\n'

In [4]: append.strip()
Out[4]: 'test'

or you could write that like this
with open("test.txt", "w") as test_file:
    while True:
        print("Write something to append to file: ")
        append = input()
        if len(append) == 0 or input.strip() == "exit":
            break
        test_file.write(append)

Answer: Change condition to "exit\n" and execute. It worked for me.
Answer: try printing append to see exactly what it is, or using append = str(sys.stdin.readline())


Place as few knights as possible on an 8 by 8 chess board so that every square is controlled by at least one knight.

Question: Squares containing knights should be controlled as well.  I think you need at least 3 knights to cover a corner, i.e. have the outside squares covered by knights, so that would be at least 12 knights to cover the board.  16 knights is the best I have done so far.  I need to find the minimum and prove it's the minimum.
Comment: See here https://en.wikipedia.org/wiki/Mathematical_chess_problem#:~:text=Domination%20problems,-Another%20kind%20of&text=In%20these%20problems%20it%20is,%2D%208%2C%20knights%20%2D%2012.
Comment: The attack all squares problem is easily found on the Internet too, and has been solved long ago.
Comment: I am trying to prove the "attack all squares" version.  So 14 knights is the minimum and I need to prove it.
Answer: You can solve the problem via integer linear programming as follows.  For each cell $(i,j)$, let $N_{i,j}$ be the set of neighbors (a knight's move away) of $(i,j)$, and let binary decision variable $x_{i,j}$ indicate whether a knight is placed on $(i,j)$.  The problem is to minimize $\sum_{i,j} x_{i,j}$ subject to
\begin{align}
\sum_{(k,\ell)\in N_{i,j}} x_{k,\ell} &\ge 1 &&\text{for all $i,j$} &(\alpha_{i,j} \ge 0)\\
x_{i,j} &\ge 0 &&\text{for all $i,j$} &(\beta_{i,j} \ge 0)\\
\end{align}
Here, the dual variables are indicated in parentheses.
The linked page shows a solution that yields an upper bound of $14$.  The following optimal dual values prove the lower bound:
$$\alpha=
\begin{pmatrix}
1 & 1/2 & 0 & 0 & 0 & 0 & 1/2 & 1 \\
1/2 & 1/2 & 1/2 & 0 & 0 & 1/2 & 1/2 & 1/2 \\
0 & 1/2 & 0 & 0 & 0 & 0 & 1/2 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1/2 & 0 & 0 & 0 & 0 & 1/2 & 0 \\
1/2 & 1/2 & 1/2 & 0 & 0 & 1/2 & 1/2 & 1/2 \\
1 & 1/2 & 0 & 0 & 0 & 0 & 1/2 & 1 \\
\end{pmatrix}
$$
$$\beta=
\begin{pmatrix}
0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 \\
1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\
0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 \\
\end{pmatrix}
$$
As you can check, multiplying each constraint by its corresponding dual value and adding them all up will yield $\sum_{i,j} x_{i,j} \ge 14$.


Statistical test to compare global performance of two models over multiple data set of time series

Question: I have measurements from $N$ subjects. For each subjects $i \in {1,...,N}$, I measure three time series composed of $T_i$ elements : $x^i = \{x^i_1,...,x^i_{T_i}\}$, $y^i = \{y^i_1,...,y^i_{T_i}\}$ and $z^i = \{z^i_1,...,z^i_{T_i}\}$. I use two models to predict $z^i_t$ from $x^i_t$ and $y^i_t$ respectively, for $t \in {1,...,T_i}$. Using the corresponding residuals $r^i_{x_t}$ and $r^i_{y_t}$, I can test if the signal $x^i$ is better (provides the lowest errors) than $y^i$ to predict $z^i$ for a given subject $i$.
Now, I want to test statistically if the signals $x$ are generally better than $y$ to predict $z$. How can I do it ?
Answer: If you only want to know whether one model yields a statistically significant better prediction than the other, a paired t-test is appropriate. In R, this would be
<code>zx <- predictionfrom(x)
zy <- predictionfrom(y)
t.test(zx, zy, paired=TRUE)
</code>
and then check whether the reported p-value is sufficiently small (e.g less than 0.01).
If you want to know which model is "better", you might also want to take into account the number of parameters in the model: a model with more parameters tends to yield better prediction results. Measures that try to quantize the trade-off between accuracy and the number of parameters are BIC or AIC.
Comment: Thank you. Both models have same number of parameters. Is it ok to use a paired t-test if each time series $x^i$ is correlated to $y^i$ (and having correlated residuals) ?
Comment: Yes, that is the reason why a *paired* test must be used: it assumes correlation between $x_i$ and $y_i$, but independece between $x_i - y_i$ and $x_k - y_k$ for $i\neq k$.


Hooking up Sproutcore frontend and custom Python backend

Question: I am building a web-based application. The frontend has been designed in Sproutcore. For the backend, we have our own python API which handles all transactions with multiple databases. What is the best way to hook up the front-end with the back-end.
AFAIK django is pretty monolithic (correct me if i am wrong) and it would be cumbersome if I dont use its native ORM...I would prefer a python-based solution..any ideas?
thanks!
Suvir
Answer: The only thing I know about sproutcore is what I read about 10 seconds ago to answer this. Javascript can do ajax so I assume so can sproutcore. So providing a restful api+json to your backend would be an option. If you need to sell it to your boss, call it a service oriented architecture. You'll probably have it working before he can look it up in this weeks Information Weekly.
All that's required for that to work is anything that can answer an http request and return json. There are a bizillion web frameworks out there that can do this. You mentioned one already and it will probably be mentioned again. I'll go ahead and state my preference though. bfg or pylons either of which will work for you and pretty much stay out of your way. There are others of course, and maybe after playing with them you might find you could write your own pretty easy either using just Webob (used by pylons and bfg and others) or straight wsgi OR a combination of all of them using pieces where appropriate according to your needs.
Comment: Thanks a lot, CherryPy seems to do all I need for now. Will check out bottle.py as Pydroid suggested.
Answer: There's also Bottle.py if you just want it simple.


Dijkstra Algorithm Time Complexity

Question: I am new to Dijkstra Algorithm.
My question is that: for an undirected graph G with n nodes and m edges, the time complexity for Dijkstra Algorithm to find shortestst path is o((n+m)logn). However, if the G is connected, why this time complexity can be also expressed as o(mlogn)?
Cheers
Comment: You've used little-o, but do you mean big theta?
Answer: If it is not connected, say in the case where there is only one edge (m=1), then it can be it is o(nlgn). That is why in the general case it is o((m+n)lgn).
If it is connected, there should be a tree that connects the whole graph (length n-1), so m is at least n-1: (m>=n-1). So for purposes of small O notation (Small O:f is dominated by g asymptotically), I can replace n by m: o((m+1+m)lgn) "=" o(mlgn)

Dijkstra Algorithm Time Complexity


ValueObject json deserialization returns Null

Question: I am trying to implement valueobject in asp.net core with ef core. I have money as value object and product which has money as price property. The problem is that money is serialized in product table but deserialization returns null. I tried debug mode but it even doesn't go in money class for deserialization.
Note:I used [NotMapped] because migration gave me error that money needs primary key, But I didn't need table for money and I wanted money to be serialized as a price field in product table.
my money model:
[NotMapped]
public class Money
{
    public static readonly Money Empty = new Money(0);
    public decimal Value { get; private set; }

    protected Money()
    {
    }

    public Money(decimal value) : this()
    {
        if (value < 1)
            throw new Exception("value is invalid");
        Value = value;
    }
  }

my product model:
public class Product
 {
    public Product()
    {

    }
    public Product(string name, decimal price)
    {
        if (string.IsNullOrEmpty(name))
            throw new Exception("Name is invalid");
        Name = name;
        Price = new Money(price);
    }
    public int Id { get; private set; }
    public string Name { get; private set; }

    public Money Price { get; private set; }
  }

my dbcontext:
public class StoreDbContext:DbContext
  {
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=XXX;initial catalog=Basket2;integrated security=true");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new ProductConfiguration());
        //modelBuilder.Entity<Product>()
        //    .HasKey(lc => new { lc.Id });
    }

    public DbSet<Order> Orders{ get; set; }
    public DbSet<OrderLine> OrderLines{ get; set; }
    public DbSet<Product> Products{ get; set; }
  }

my productconfiguration:
   public class ProductConfiguration : IEntityTypeConfiguration<Product>
    {

    public void Configure(EntityTypeBuilder<Product> builder)
    {

      var test=  builder.Property(c => c.Price).
            HasConversion(c => JsonConvert.SerializeObject(c), c => JsonConvert.DeserializeObject<Money>(c));

     }
    }

Answer: SerializeObject and DeserializeObject cannot always underestand a code successfully, that's why we have ISerializable interface. I believe, if you implement it, your issue would be fixed. Please have a look on the links below:
Implementing ISerializable
Newtonsoft and ISerializable


Testando app localmente no browser?

Question: Estou tentando desenvolver um aplicativo hibrido usando ionic e angularjs e para isso estou testando no browser.
Quando eu faço  ionic serve ele cria um servidor local com o endereco localhost:8100/#/main e meu webservice tbm esta no localhost na porta 80.
Quando tento fazer alguma requisicao ajax para esse webservice o Firefox me retorna a mensagem:

Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em http://localhost/AppPanel/users/doLogin.json. (Motivo: o cabeçalho CORS 'Access-Control-Allow-Origin' não está presente).`

Ja tentei desabilitar essa verificação no Firefox dessa maneira: about:config -> security.fileuri.strict_origin_policy -> false mas não consegui resultados ainda. Fiz meu webservice em CakePHP.
Como resolver esse problema?
Comment: @Bacco estou tentando aqui, assim que conseguir(se conseguir) posto a resposta. Se nao conseguir vou criar uma maquina virtual mesmo. obrigado
Comment: Você implementou o CORS na sua API ?
Comment: Onde está localizado o seu serviço e seu front-end ? Estão no mesmo diretório ou diretórios diferentes?
Comment: @FelippeTadeu o frond-end(browser app) e o back-end(webservice) estão todos no localhost.
Comment: problema resolvido. Adicionei ao atalho do Chrome os parametros `--args --allow-file-access-from-files --disable-web-security` e agora funcionou blzinha. Obrigado a todos.
Answer: Você contornou a segurança da app e do backend desabilitando o CORS.
Para configurar o CORS no cliente e no servidor (em ambiente de desenvolvimento) eu faço isso:
index.html:
<meta http-equiv="Content-Security-Policy"
        content="default-src *;
               script-src 'self' 'unsafe-inline' 'unsafe-eval'
                           127.0.0.1:*
                           http://*.gstatic.com
                           http://*.googleapis.com
                           https://*.gstatic.com
                           https://*.googleapis.com
                           ;
               style-src  'self' 'unsafe-inline'
                           127.0.0.1
                           http://*.gstatic.com
                           http://*.googleapis.com
                           https://*.gstatic.com
                           https://*.googleapis.com
    ">

no seu backend, defina os headers para aceitar a origem 127.0.0.1
 (exemplo em RubyOnRails):
def set_headers    #este é um before_filter no controller
    if request.env['HTTP_ORIGIN'] and request.env['HTTP_ORIGIN'].match(/^http:\/\/127\.0\.0\.1/)
        headers['Access-Control-Allow-Origin'] = '*'
        headers['Access-Control-Allow-Methods'] = 'GET' #'POST, PUT, DELETE, GET, OPTIONS'
        headers['Access-Control-Request-Method'] = '*'
        headers['Access-Control-Allow-Headers'] = 'Origin' #'Origin, X-Requested-With, Content-Type, Accept, Authorization'
        puts "PERMITINDO CORS PARA ORIGIN: #{request.env['HTTP_ORIGIN']}"
    else
        #puts "HTTP_ORIGIN é nil => REQUEST.ENV => #{request.env}"
    end
end

Você deve servir a app assim:
ionic serve --address 127.0.0.1

Testando app localmente no browser?


adding new column to data frame in R

Question:   rate   len ADT trks      sigs1 slim shld lane acpt  itg lwid hwy
1  4.58  4.99  69    8 0.20040080   55   10    8  4.6 1.20   12 FAI
2  2.86 16.11  73    8 0.06207325   60   10    4  4.4 1.43   12 FAI
3  3.02  9.75  49   10 0.10256410   60   10    4  4.7 1.54   12 FAI
4  2.29 10.65  61   13 0.09389671   65   10    6  3.8 0.94   12 FAI
5  1.61 20.01  28   12 0.04997501   70   10    4  2.2 0.65   12 FAI
6  6.87  5.97  30    6 2.00750419   55   10    4 24.8 0.34   12  PA
7  3.85  8.57  46    8 0.81668611   55    8    4 11.0 0.47   12  PA
8  6.12  5.24  25    9 0.57083969   55   10    4 18.5 0.38   12  PA
9  3.29 15.79  43   12 1.45333122   50    4    4  7.5 0.95   12  PA

I got a question in adding a new column, my data frame is called highway1,and i want to add a column named S/N, as slim divided by acpt, what can I do?
Thanks
Comment: You probably can use cbind! For more information look: http://stat.ethz.ch/R-manual/R-devel/library/base/html/cbind.html
Comment: Avoid using `cbind`. :) Instead use `$`, `transform`, `with`, `within`  ...
Answer: > mydf$SN <- mydf$slim/mydf$acpt
> mydf
  rate   len ADT trks      sigs1 slim shld lane acpt  itg lwid hwy        SN
1 4.58  4.99  69    8 0.20040080   55   10    8  4.6 1.20   12 FAI 11.956522
2 2.86 16.11  73    8 0.06207325   60   10    4  4.4 1.43   12 FAI 13.636364
3 3.02  9.75  49   10 0.10256410   60   10    4  4.7 1.54   12 FAI 12.765957
4 2.29 10.65  61   13 0.09389671   65   10    6  3.8 0.94   12 FAI 17.105263
5 1.61 20.01  28   12 0.04997501   70   10    4  2.2 0.65   12 FAI 31.818182
6 6.87  5.97  30    6 2.00750419   55   10    4 24.8 0.34   12  PA  2.217742
7 3.85  8.57  46    8 0.81668611   55    8    4 11.0 0.47   12  PA  5.000000
8 6.12  5.24  25    9 0.57083969   55   10    4 18.5 0.38   12  PA  2.972973
9 3.29 15.79  43   12 1.45333122   50    4    4  7.5 0.95   12  PA  6.666667

I hope an explanation is not necessary for the above.
Comment: Thanks Ananda, I tried this before, but it always shows an error, because the name is"S/N", i just type > mydf$S/N <- mydf$slim/mydf$acpt, but it's an error.
Comment: @user3472222, that's because "/" is not a valid character to be used in a variable name. If you really want to do that, you could use `mydf$"S/N" <- mydf$slim/mydf$acpt`, but that might just make things more complicated later on since you'll always need to quote the variable names when you need to refer to them.
Answer: While $ is the preferred route, you can also consider cbind.
First, create the numeric vector and assign it to SN:
SN <- Data[,6]/Data[,9]

Now you use cbind to append the numeric vector as a column to the existing data frame:
Data <- cbind(Data, SN)

Again, using the dollar operator $ is preferred, but it doesn't hurt seeing what an alternative looks like.

adding new column to data frame in R


Finding constants of an equation using equation the coefficients or convenient values method

Question: How do you find the constants for the equation $$\frac{30x-17}{(6x-1)^2}=\frac{A}{6x-1}+\frac{B}{(6x-1)^2}$$
Multiplying by lowest common denominator yields $$30x-17=A(6x-1)+B$$
This can be written as $30x-17=6A\cdot x-A+B$, but I am unsure of where to go from there.
Comment: Hint substitute values for $x $. Try $x=0$
Answer: Now you have two equations and two unknowns. $$30 = 6A \\ -17 = B-A$$ Can you see how I got these?
Comment: Much appreciated!  I was getting there!
Answer: $\displaystyle \frac{30x-17}{(6x-1)^2}=\frac{A}{6x-1}+\frac{B}{(6x-1)^2}$
$\implies 30x-17=A(6x-1)+B$
$\implies 30x-17=6Ax-A+B$
comparing both sides, we have
$6A=30~\&~-A+B=-17$
So from first equation we'll get $A=5$ putting $A=5$ in second equation we get $B=-12$.
Answer: $$30x-17=A(6x-1)+B$$
$ x = \frac 16 \rightarrow  B = 5-17 = -12 $
$ x = 0 \rightarrow  -17 = -A  + B = -A -12$


Continuous mapping of the unit interval to a compact subset of $\mathbb{R}^d$

Question: This is directly copied from Problem 6 in Chapter 7 of Stein and Shakarchi's Real Analysis.

A compact subset $K$ of $\mathbb{R}^d$ is uniformly locally connected if given $\epsilon > 0$ there exists $\delta > 0$ so that whenever $x, y \in K$ and $| x − y | < \delta$, there is a continuous curve $\gamma$ in $K$ joining $x$ to $y$, such that $\gamma \subset B_\epsilon (x)$ and $\gamma \subset B_\epsilon (y)$.
Using the previous problem, one can show that a compact subset $K$ of $\mathbb{R}^d$  is the continuous image of the unit interval $[0, 1]$ if and only if $K$ is uniformly locally connected.

The previous problem is as follows. (It is quite easy to prove.)

Prove a theorem of Hausdorff: Any compact subset $K$ of $\mathbb{R}^d$ is a continuous image of the Cantor set $\mathcal{C}$.
Answer: I spent a few hours on this problem before realizing there is an error in it. I am sharing my solution to save others' time. I denote such a continuous mapping as $f$.
We can prove the only if part by contradiction. If the statement is not true, there exist an $\epsilon > 0$ and $x_n, y_n \in E$, such that $|x_n - y_n| < \frac{1}{2^n}$ and there isn't any $\gamma$ joining $x_n$ to $y_n$ such that $\gamma \subset B_\epsilon (x_n)$ and $\gamma \subset B_\epsilon (y_n)$.
Because $E$ is compact, we can find a subsequence $(x_i, y_i)$ such that $\lim_{i\rightarrow\infty} x_i = \lim_{i\rightarrow\infty} y_i = x \in E$.
Because $[0,1]$ is compact, we can find

a subsequence $a_j$ in the unit interval such that $f(a_j) = x_{i_j}$ and $\lim_{j\rightarrow\infty} a_j = a \in [0,1]$, and
a subsequence $b_j$ in the unit interval such that $f(b_j) = y_{i_j}$ and $\lim_{j\rightarrow\infty} b_j = b \in [0,1]$.

Note that $a$ and $b$ might be different. Still, we can now define $\gamma_N = f([a_N, a]) \cup f([b, b_N])$. This curve will be within any $B_\epsilon(x)$ for sufficiently large $N$. By construction, it joins $f([a_N)$ and $f([b_N)$, leading to a contradiction.
The if part is simply not true. A trivial counter-example is $E = \{ 0, 1\}$. $E$ is locally connected, but not (globally) connected. We cannot find a continuous mapping from $[0,1]$ to $E$. If we change locally connected to connected in the original problem, we can find mapping $f$ by

Find a continuous mapping $f'$ from the Cantor set $\mathcal{C}$ to $E$ (as in Problem 5).
$\mathcal{C}^C$ is made of a countable set of open intervals $(a_i, b_i)$. Since $f'(a_i)$ and $f'(b_i)$ are connected by a curve $\gamma_i \subset E$, we simply reparameterize $\gamma_i$ so that it maps $[a_i, b_i]$ to the same curve in $E$. In this way we extend $f'$ defined on $\mathcal{C}$ to $f$ defined on $[0,1]$.

Combining both halves of the problem, we have proved that A compact and connected subset $K$ of $\mathbb{R}^d$ is uniformly locally connected.
Comment: On a related note check out this: https://math.stackexchange.com/questions/39584/reference-for-a-proof-of-the-hahn-mazurkiewicz-theorem


Adicionar parágrafo com jQuery

Question: Boa noite, estou tentando adicionar um parágrafo quando clicou no botão mas não está funcionando e não consigo saber o porque, alguem poderia ajudar?

e no HTML está assim:

            <input type="text" name="text" id="t"/>
        <input type="button"
                value="Adicionar parágrafo" id="btAdd" />

        <input type="button"
                value="Aumentar tamanho fonte" id="btAumentarFonte" />
        <input type="button"
                value="Diminuir tamanho fonte" id="btDiminuirFonte" />

        <input type="button"
                value="Remover último parágrafo" id="btRemoverUltimo" />
        <input type="button"
                value="Remover todos os parágrafo" id="btRemoverTodos" />

 Lorem ipsum dolor sit amet, consectetur adipiscing elit.

 Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Comment: A parte de `script` e `html` estão no mesmo arquivo? Qual versão da biblioteca `jQuery` está utilizando?
Comment: @Rfroes87 Estão, estou usando  para a biblioteca do jQuery
Answer: Boa noite!
o seu script esta dessa forma

      $("#btAdd").click(function(){
            var texto = document.getElementById("t").value;
            $("#new").append("
"+texto+"
");
        });

Você precisa adicionar o seu JQuery dessa forma:
$(document).ready(function(){ <> });

dessa forma tudo que voce colocar dentro dessa instrução irá ser executado.
codigo:

O $("#new").html('<>') adiciona as instruções html dentro do #new
Ps: é necessario chamar o script do JQuery antes da do script do seu código.
Answer: Opa Eduardo!
Adaptei o seu script para utilizar o Jquery na hora que pegar o valor do input

$("#btAdd").click(addText)

function addText () {
  const text = "
"+$("#t").val()+"</p";
  $("#new").append(text);
}

            <input type="text" name="text" id="t"/>
        <input type="button"
                value="Adicionar parágrafo" id="btAdd" />

        <input type="button"
                value="Aumentar tamanho fonte" id="btAumentarFonte" />
        <input type="button"
                value="Diminuir tamanho fonte" id="btDiminuirFonte" />

        <input type="button"
                value="Remover último parágrafo" id="btRemoverUltimo" />
        <input type="button"
                value="Remover todos os parágrafo" id="btRemoverTodos" />

 Lorem ipsum dolor sit amet, consectetur adipiscing elit.

 Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Adicionar parágrafo com jQuery


Creating Custom Logger for Both .Net core and WCF

Question: I am working  with micro services some of my micro services are written in WCF,and rest are Asp.net core,Now i would like to maintain a centralized logger system among those micro services.So that i want to create common custom logger which inherit ILogger. Is there any way to create a common logger library which will support both WCF and Asp.net core API ?
Comment: I don't understand what part you're stuck on? Can you explain what's preventing you from accomplishing your task?
Answer: Do you ask which framework can you use? Ff yes then you can write a library in standard and use that. The purpose of .NET Standard is simple: to share code between runtimes. When you want to share code between different runtimes in the .NET Ecosystem, use .NET Standard.[1] [1] https://stackify.com/net-standard-explained/
 https://learn.microsoft.com/en-us/dotnet/standard/net-standard


Adding custom functions PHP to use in a views template

Question: I want to use a custom function in views-view-fields--field-name.tpl.php template file. Where do I have to put it? Is it possible to use it in template.php in some preprocess functions?
Comment: Add your function in any file and include the file in views-view-field--field_name.tpl.php.
Comment: You should include the file in **views-view-field--field_name.tpl.php** using **module_load_include**. Example :  module_load_include('file_type', 'module_name', 'base_file_name'); https://api.drupal.org/api/drupal/includes!module.inc/function/module_load_include/7
Answer: You can use a preprocess function in your template.php file. For example:
function YOURTHEME_preprocess_views_view_fields__field_name(&$vars) {
  // Do your changes for the field here
}

Comment: call to undefined function it says...
Answer: In Drupal 7, you can achieve this using module_load_include OR include_once.

Create a .inc file in the custom module, which will keep all the template files functions, or if you have only one function then just add the function in your custom module.
Go to your template file (views-view-fields--field-name.tpl.php) and include the file using module_load_include() or include_once()

If it is a .inc file, use module_load_include('file_type', 'module_name', 'base_file_name');
If it is a function in a custom module, use include_once 'FILE_PATH';
Comment: If it is a function in a module, then there isn't any need of using `include_once()` since every enabled module is loaded when Drupal completes its bootstrap. It's only on early bootstrap phases that the enabled modules are still to be loaded.


Where to free up memory of a dynamic array created inside a function

Question: This is in reference to the discussion in this topic here
How to have a char pointer as an out parameter for C++ function
In the code below, where do I free the memory of pTemp? Is it not required?
Would things would have changed in anyway if instead of array of chars there was array of integers?
void SetName( char **pszStr )
{
    char* pTemp = new char[10];
    strcpy(pTemp,"Mark");
    *pszStr = pTemp;
}

int main(int argc, char* argv[])
{
    char* pszName = NULL;
    SetName( &pszName );
    cout<<"Name - "<< pszName << endl;
    delete [] pszName;
    cin.get();
    return 0;
}

Answer: You're assigning pTemp to *pszStr, and pszStr points to pszName.
Therefore, delete [] pzxName deletes the allocated memory as required.
The confusion is a good example of why you should avoid weird C-style idioms and manual memory management. It would be much clearer as:
#include <string>
#include <iostream>

std::string GetName() {return "Mark";}

int main() {
    std::string name = GetName();
    std::cout << "Name - " << name << std::endl;
}

with no pointers, new or delete required.
Answer: You don't need to.
The memory allocated to it is deallocated when you call:
delete [] pszName;

Note, that new/new [] returns you a address and to avoid a memory leak you need to call delete/delete [] on the exact same address and only once.
What you have in above code is two different pointers(pszName and pTemp) pointing to the same address which was returned by new []. So calling delete [] on one suffices.
In C++ you are much better off using a std::string instead of char * and in case of other data types, You surely can use smart pointers and save yourself the explicit memory management.
Answer: pTemp, the variable itself, is deallocated once the function exits since it was allocated on the stack in the first place. The array whose pointer was put into pTemp persists outside the function via the argument passed to it, pszName. When the value in this variable is deleted, the heap memory used by the array will be freed.
Comment: Thanks a lot. Totally missed out the point that variable pTemp was in stack.


Does Go runtime create OS threads(M)?

Question: numLogicalProcessors on Intel core i7 is 8(2 X 4 physical cores). Linux OS.  So, eight OS threads(M) can work in parallel. Go runtime can assign eight contexts(P1, P2....P8 - runtime.GOMAXPROCS(numLogicalProcessors)) in my Go program.

Go follows M:N threading model, where N are OS threads and M are go routines of a Go program.
OS scheduler schedules OS threads. Thread states are WAITING, RUNNABLE & EXECUTING.
Go scheduler schedules Go routines. Go-routine states are WAITING, RUNNABLE & EXECUTING. Goroutine is a user level thread.

Does the runtime of a Go program explicitly create those eight OS threads(M)? before assigning each context(P) to each OS thread(M)?
If OS thread(M1) is pre-empted(due to time-slice) by OS scheduler, How does goroutine scheduler(P1) manage the state of goroutine G1 using LRQ? Does P1 get the notification from OS that M1 state has changed?
Comment: This is an implementation detail and may change from version to version or be different in gc and gcc (it is not, but it may be).
Comment: It is an ambiguity. Processor has a number of cores, each core does hyberthreading. The operating system sees multiple processors. OS takes processes and schedules them among available processors. Threads are like special type of processes. They share memory with another processes. Threads are not owned by operating system. Processors are.
Comment: @GrzegorzŻur Yes... *OS thread* is  Linux native thread created using `pthread_create()`. Yes... `pthread_create()` uses `clone()` system call internally. My question is... Does GO runtime creates these eight linux native threads(`M`)?
Comment: goroutine scheduler = threadpool.
Comment: @DavidHaim Threadpool of userlevel threads(Goroutines)?
Comment: no. a regular os threadpool.
Comment: @DavidHaim goroutine scheduler(`P1`) gets assigned to a single OS thread(`M1`). Why would `P1` create a thread pool of eight OS threads?
Comment: because goroutine scheduler = threadpool.what are goroutines if not stackful coroutines that are managed by an underlying threadpool? you're confusing yourself with fancy terms.
Comment: @DavidHaim So, `P` is logical processor in intel core i7 they are 8, `M` is OS thread, which one is scheduler?
Answer:
Yes, Go scheduler start execution threads. The number of them can be examined or changed with runtime.GOMAXPROCS.
No, operating system preemption is transparent to the running process. Go runtime since version 1.14 can preempt Go routines but this is to avoid locking threads by tight loops. It is not related to operating system preemption.
Comment: 1) Did you get my second question? let me know, if it still needs clarification 2) Go runtime is nothing but C code that performs *OS thread creation* & *syscalls*. just to add to your answer. Figure on Page 2  explains [here](http://www.cs.columbia.edu/~aho/cs6998/reports/12-12-11_DeshpandeSponslerWeiss_GO.pdf)
Comment: With regards to your first answer, when you say, "Go runtime create OS threads",  Do you mean each goroutine scheduler(say `P1`) creates its corresponding OS thread `M1`?
Comment: Each goroutine scheduler runs in a separate thread started by the runtime.
Comment: You mean...., Does Go runtime launches goroutine scheduler(`P1`) as OS thread(`M1`) and goroutine scheduler(`P2`) as OS thread(`M2`) and the rest all OS threads? And `P1` is nothing more than `type p struct`
Comment: Yes, I mean that. You can check it by running any Go program and then using `pidof` and `ps -T ` to view those threads. Context is a concept represented somehow in Go runtime, although I don't know the details of it.
Comment: `1` is incorrect. The number of threads may or may not equal `GOMAXPROCS`. The Go scheduler is permitted to create additional threads if a thread is held on a blocking system call so that other goroutines can continue to use CPU. There is only one goroutine scheduler per Go process, not one per thread.
Comment: @Adrian **1)** when you say `1`, I guess you are referring my question one.  **2)** When you say: "There is only one goroutine scheduler per Go process" Are you saying that, it is wrongly mentioned/understood in the query that `P1`, `P2`,`P3`...`P8` are eight goroutine schedulers. Isn't `GOMAXPROCS(8)`  creating eight goroutine schedulers?
Comment: When I say `1` I'm referring to the answer. And yes - it doesn't create eight schedulers. There is one scheduler. Each thread has a goroutine queue that could be considered a scheduler, but the global scheduler is responsible for assigning goroutines to threads, spawning and killing threads, etc.
Comment: @Adrian Thank you for correction. I updated the answer.
Comment: @Adrian if there is one goroutine scheduler, then how do I interpret this mapping  `P1` <-> `M1`, `P2`<-> `M2`, `P3`<-> `M3`... `P8`<-> `M8` that I mentioned in the query?  What does `P?` indicate? https://golang.org/src/runtime/runtime2.go#L552
Comment: `P` is a logical processor, `M` is an OS thread, `G` is a goroutine.
Comment: @Adrian When you say, "Each thread has a goroutine queue that could be considered a scheduler", Are you referring to LRQ(Local Run Queue)?
Comment: @overexchange yes.

Does Go runtime create OS threads(M)?


Simplification of $\sum_{n=1}^{+ \infty} \frac{z^{n-1}s^{n}}{(n-1)!n!}$

Question: How can I simplify $\sum_{n=1}^{+ \infty} \frac{z^{n-1}s^{n}}{(n-1)!n!}$ for $z$ and $s$ positive real numbers ?
I thought about finding a function $f$ such that $f^{n}(0) = \frac{1}{(n+1)!} \forall n$.
I also thought about representing the sum as the inner product of two vectors with components of the exponential in an Hilbert space.
Comment: Looks like some kind of Bessel function.
Comment: This is a mild modification of the $I$ Bessel function. The way to know that it's in the class of Bessel functions is the appearance of two factorials and the way to know it is $I$ is that the terms are not alternating.
Comment: Thanks, this is what I was looking for!
Answer: $$\frac{s}{\sqrt{sz}} I_{1}(2\sqrt{sz})$$
Comment: Thanks, I obtained the same formula


Subfields of an ultrapower $\mathbb{R}^\omega/U$ obtained by reducing $U$.

Question: We promise that
$F(g_1, \ldots, g_k)$ denotes the composition for each $F \colon \mathbb{R}^k \to \mathbb{R}$ and $g_1,\ldots ,g_k \colon \omega \to \mathbb{R}$.
Let $M$ be a subset of $\mathbb{R}^\omega$ and  $M^\wedge$ denotes the set of all
$F(g_1, \ldots, g_k)$ where $k \in \omega$,   $g_1,\ldots, g_k \in M$, and $\ F \colon \mathbb{R} ^k \to \mathbb{R}$  where $F$ is definable in $\langle\mathbb{R},1,0, +,\cdot,<\rangle $ without parameters.
Notice that, considering the case $k=0$, $\emptyset^\wedge =$ the set of all definable elements in $\mathbb{R}$.
We say that a filter $\mathcal{F}$ on $\mathcal{P}(\omega)$ is an $M$-ultrafilter if either $\{i \in\omega \mid g(i) < g'(i) \}\in \mathcal{F}$, $\{i \in\omega \mid g(i) = g'(i) \}\in \mathcal{F}$, or $\{i \in\omega \mid g(i) > g'(i) \}\in \mathcal{F}$ for each $g,g' \in M$.
Let $f \in \mathbb{R}^\omega$ and $\mathcal{F}$ be an $M^\wedge \cup \{f\} $-ultrafilter.
My question is: Is $\mathcal{F}$ an $(M\cup \{ f\} )^\wedge$-ultrafilter?
I know that $M^\wedge/\mathcal{F}$ is a real closed field.
Thus, by the $o$-minimality of the theory of real closed fields, for each definable functions $F_1, F_2 \colon \mathbb{R}^{k+1} \to \mathbb{R}$ and $g,g_1,\ldots , g_k \in M$, there are $h_1^-,\ldots, h^-_m,h_1^+,\ldots, h_m^+, h_1,\ldots,h_n \in M^\wedge$ where maybe $h_1^-$ and $h_m^+$ are  $-\infty$ and $+\infty$, respectively,  such that
\begin{align*}
 F_1(g_1,\ldots, g_k,g) \leq_{\mathcal{F}} F_2(g_1,\ldots,g_k,g) \iff \bigvee_{1\leq l \leq m}h_l^- <_\mathcal{F} g <_\mathcal{F} h_l^+  \lor  \bigvee_{1\leq l \leq n} h_l =_{\mathcal{F}} g.
 \end{align*}
But I don't know whether this is valid if we replace $g$ by $f$.
Comment: I still have to read the second paragraph but I don't know anything about $o$-minimality. I just want to ask you this: your statement implies that an $\{g\}^{∧} ∪ \{f\}$-ultratilfter is an $\{f,g\}^{∧}$-ultrafilter. But this is false, right? Take for instance $g=(0,0,0,…)$ and $f = (1,1/2,1/3,…)$. The filter of all the $\{n∈\,|\,n≥K\}$ for $K∈$ is then an $\{g\}^{∧} ∪ \{f\}$-ultratilfter but is not an $\{g,f\}^{∧}$-ultratilfter, right?
Comment: I have added a remark. In your case, $\{g\}^\wedge = \emptyset^\wedge$. By the way, you are not right. If $F\colon \mathbb{R} \to \mathbb{R}$ is definable, then $F| [0, \epsilon)$ is either strictly increasing, strictly decreasing, or constant for some $\epsilon >0$. Thus, the sequence $F(f)$ is strictly increasing, strictly decreasing, or constant,  eventually. So your filter is strong enough to compare $F(f)$ and $0$.
Comment: Ah, you're right, sorry.
Comment: Don't be. Thank you so much.
Answer: I have solved it.
Suppose that
\begin{align*}
 A := \{ i \in \omega \mid F(g_1(i),\ldots, g_k(i),f(i)) \leq 0 \} \notin \mathcal{F}.
 \end{align*}
Since $M^\wedge/ \mathcal{F} \models \mathrm{RCF}$ and $\mathrm{RCF}$ is an $o$-minimal theory, there are $h^-_1,\ldots, h^-_m,h_1^+,\ldots, h_m^+, h_1,\ldots,h_n \in M^\wedge$ where maybe $h_1^-$ and $h_m^+$ are  $-\infty$ and $+\infty$, respectively,  such that
\begin{align*}
 M^\wedge / \mathcal{F} \models
 \forall v \left( F_0([g_1]_\mathcal{F} ,\ldots, [g_k]_\mathcal{F} ,v) \leq 0
 \iff
 \left(
 \bigvee_{1\leq l \leq m}[h_l^-]_\mathcal{F} < v < [h_l^+]_\mathcal{F}  \lor  \bigvee_{1\leq l \leq n} [h_l]_\mathcal{F} = v.
 \right)
 \right)
 \end{align*}
Define
\begin{align*}
 X := \left\{ i \in \omega  \mid
 \mathbb{R} \models
 \forall v \left( F(g_1(i),\ldots, g_k(i) ,v) \leq 0
 \iff
 \left(
 \bigvee_{1\leq l \leq m}h_l^-(i) < v < h_l^+(i)  \lor  \bigvee_{1\leq l \leq n} h_l(i)= v
 \right)
 \right)
 \right\}
 \end{align*}
and
\begin{align*}
 Y := \left\{ i \in \omega \mid
 \mathbb{R} \models
 \left(
 \bigvee_{1\leq l \leq m}h_l^-(i) < f(i) < h_l^+(i)  \lor  \bigvee_{1\leq l \leq n} h_l(i)= f(i)
 \right)
 \right\}.
 \end{align*}
Since $\mathcal{F}$ is an $M^\wedge \cup \{f\}$ -ultrafilter, either $Y \in \mathcal{F}$ or $\omega \setminus Y \in \mathcal{F}$.
If $Y \in \mathcal{F}$, then  $X \cap Y \in \mathcal{F}$ and $\mathbb{R} \models F(g_1(i), \ldots , g_k(i) , f(i) )  \leq 0$ for each $i \in X\cap Y$, it is a contradiction.
Thus $\omega \setminus Y \in \mathcal{F}$.
For each $i \in X \setminus Y$, $\mathbb{R} \models F(g_1(i),\ldots , g_k(i), f(i) ) > 0 $ so that $[F(g_1,\ldots g_k , f)] _\mathcal{F} > _\mathcal{F} 0$.
Therefore, $(M \cup \{ f\} ) ^\wedge / \mathcal{F}$ is totally ordered.


Study convergence of $\int_{0}^{\infty} \frac{e^{\sqrt{x}}}{e^x + 1}$

Question: Study convergence of $$\int_{0}^{\infty} \frac{e^{\sqrt{x}}}{e^x + 1}$$
First of all, I can only use the comparison test or the limit comparison test, but I don't know to witch series compare it.
Is known that polynomials of grade $n \gt e^{x}$ and that $\sqrt{x} \lt x$ and so $e^{\sqrt{x}} \lt e^{x}$. Any hints how to proceed ? Thanks in advance.
Answer: Use $0\le e^{\sqrt{x}}\le e^{x/2}$ for $x\ge4$, $0\le\frac{e^{\sqrt{x}}}{e^x+1}<\frac12e^4$ for $x\in[0,\,4)$.
Comment: Sorry, I don't follow. Why would I want to find an upper bound for $x \in [0,4)$ if I need to find if the integral converges when x tends to infinity.
Comment: I think i got it. Since the $\int_{4}^{\infty} f(x) = arctan(e^{\sqrt(x)}) = \frac{\pi}{2} - L$. What is not natural to me though, is to know to what compare it so easily. It took me some time to realise that.
Comment: @Karl Just in case the $\int_0^4$ part diverges. So we check the contributions either side of $4$. I knew a comparison to a more slowly-growing exponential function would help, so it boiled down to comparing $\sqrt{x}$ to $x/2$ (say).
Answer: The function $\displaystyle f(x) := \frac{e^{\sqrt{x}}}{1+e^x}$ is clearly continous in the interval $[0,\infty)$.
As $x$ approaches $0$ it's perfectly integrable and as $x$ approaches $+\infty$ it decays as a negative exponential. So its integral is finite.


Error with dependencies when syncing Gradle

Question: I have used firebase as a backend to my application and, as a consequence, I am using firebase auth with firebase UI for authentication but I'm facing an error:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support:support-vector-drawable:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // firebaes dependancies.
    compile 'com.firebaseui:firebase-ui-auth:2.1.1'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'

        testCompile 'junit:junit:4.12'
    }

    apply plugin: 'com.google.gms.google-services'

The error I am getting is:
Error:Failed to resolve: com.android.support:customtabs:25.4.0
Install Repository and sync project
Open File
Show in Project Structure dialog

 and
Error:Failed to resolve: com.android.support.constraint:constraint-layout:1.1.0-beta1
Install Repository and sync project
Open File
Show in Project Structure dialog

and
Error:Failed to resolve: com.android.support:cardview-v7:25.4.0
Install Repository and sync project
Open File
Show in Project Structure dialog

I went aside with some answers to similar questions in this forum and went to SDK Manager> SDK Tools > Uppdate repositories. But it did not work!!
Any Ideas where this error is coming from?? I am guessing it is because of the android SDK version, Is that a correct guess?
Edit: I am putting %USERPROFILE% instead of my user folder name.
Comment: Possible duplicate of [How do I add a library project to Android Studio?](https://stackoverflow.com/questions/16588064/how-do-i-add-a-library-project-to-android-studio)
Answer: Nope. You are trying to download an unexisting repo. Where did you get the 25.4.0 versioning from? Anyhow. if you are targetting Nougat you should replace all 25.4.0 to 25.3.1'
Also, dont use 26.+. It's highly discouraged as Android Studio itself will tell you. There's no need to do such a thing.
Comment: Good. But at least remove the `26.+` thing. It will save you headaches. Trust me.
Comment: I have found a solution but I do not know if it is correct. I just reinstalled Google repository packages again and add google maven dependencies then adb kill-server and start-server. The problem seems to be resolved but I am not sure whether it is temporarily or permanently resolved.
Comment: I have removed all of these packages with 26.+ since I downloaded the whole google repository. I am not sure of what I am doing, but the code is executed fine.
Comment: Nice. I don't need it, but for future references, make sure you upvote/mark answers as correct when someone helps you. Otherwise you will be seen as a *help vampire* and you will likely not be helped in the future.
Comment: Thanks for that generous help, time and effort. I really appreciate it Mr @Chisko
^_^
Comment: I already have made an upvote but it is not shown to the public regarding the forum policies.


How to change center mode position using Carousel Anything - The Plus Addon for Elementor

Question: I'm using Carousel Anything - The Plus Addon for Elementor, using center mode with 2 columns visible, and it look like this
The image of the carousel

However, I would like to switch center mode to the left column. I could not figure it out the code to do that. Can someone help me with this. Thanks very much for your support.
Comment: Note: The current center mode column is bigger and have opacity: 1; while the normal one is smaller and opacity: 0.7.
Answer: You don't need to write code to do this. Enter Elementor editor and while editing, swipe the carousel right and save
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).


Meta-analyses for variance rather than means

Question: What are the main complications / differences when conducting a meta-analyses where the metric of focus is not effect size (i.e., means) per se, but instead estimates of variances from models?
Nods to literature are also welcome.
Answer: In my opinion you can perform a meta-analysis for almost everything. The key point is to be able to refrain from using its results inappropriately. Accordingly, you can pool variances, for sure, but why so, and how?
There can be cases in which you want to focus on variability of an instrument rather than on its average effect, as primary feature to choose it, so using the variance might make sense.
Yet, how can you weigh appropriately each study as the variance is already used as main effect? You could weigh by sample size, possibly. Otherwhise, you could simply build a linear model in which study variance is the dependend variable and study size and study effects are independent variables.
I would like to see the actual application, though. It would be an interesting test to the strenght and robustness of meta-analytic approaches.


Equation of a Pair of Straight Lines.

Question: If $ax^2+2hxy+by^2$ be the two sides of the parallelogram and $px+qy=1$ is one diagonal then prove that the other diagonal is $y(bp-hq)=x(aq-hp)$.
By reading the question I just understood that the given diagonal is not through origin. Second diagonal is through origin and contains the mid point of the given diagonal but could not proceed further
Comment: Can you find out the points where they meet as sides and diagonal meet in 2 points
Answer: If you solve the diagonal equation simultaneously withvthe pair of sraight lines, eliminating $y$, you get the quadratic in $x$:
$$x^2(aq^2-2hpq+bp^2)+x(2hq-2pb)+b=0$$
Considering the sum of roots, the midpoint of the diagonal has $x$ coordinate $$\frac{x_1+x_2}{2}=\frac{pb-hq}{aq^2-2hpq+bp^2}$$
Likewise, the $y$ coordinate can be deduced directly by swapping $p$ for $q$ and $a$ for $b$, resulting in:
$$\frac{y_1+y_2}{2}=\frac{aq-hp}{aq^2-2hpq+bp^2}$$
Now you can write down the gradient of the other diagonal which passes though the origin and the result follows immediately.

Equation of a Pair of Straight Lines.


Real Analysis Integrability

Question: Let $I:=[a,b]$, let $f:I\to\Bbb R$ be continuous, and let $f(x)$ greater than or equal to $0$ for all $x \in I$. Prove that if $L(f)=0$, then $f(x) = 0$ for all $x \in I$.
Should I show by contradiction?
Comment: What is $L(f)$ in this question?
Answer: Assume by contradiction that $f$ is not identically zero.
Then $f(x_0)>0$ for some $x_0$. By continuity you get that there exists some $\delta$ so that
$$f(x) > \frac{f(x_0)}{2} \,;\, \forall x \in [x_0-\delta, x_0+\delta] \,.$$
Can you see how does this contradict the fact that $L(f)=0$?
Comment: I do not see it right off the bat, how does that show a contradiction?
Comment: @JacksonHart What is $\int_{x_0-\delta}^{x_0+\delta} \frac{f(x_0)}{2}dx$?

Real Analysis Integrability


why so much XHR polling when using app engine Channel API

Question: I am trying to use the App Engine Channel API to avoid polling for updates in my client. The problem is that I see an continuous stream of XHR packets sent in the Chrome console after starting a socket. They all say:
XHR finished loading: GET "http://localhost:8080/_ah/channel/devcommand=poll&channel=xxxOMITTEDxxx-channel-yyyOMITTEDyyy-zzzOMITTEDzzz-1&client=1". jsapi:5406goog.net.XhrIo.send jsapi:5406goog.net.XhrIo.send jsapi:5352goog.appengine.DevSocket.poll_

I would not expect any XHR messages until the server tries to send a message. I am using the Python dev_appserver.
Maybe I am doing something wrong in my Javascript. I am successfully requesting a token from the server. When my client receives the token, I start the socket like this:
function listen_to_channel(msg) {
  console.log('--- server response to channel request: ' + JSON.stringify(msg));

  // open a channel socket
  var channel = new goog.appengine.Channel(msg.token);

  var socket = channel.open();
  socket.onopen = function(){ console.log('socket.onopen')};
  socket.onmessage = function(msg){ console.log('socket.onmessage: ' + msg.data)};
  socket.onerror = function(err){ console.log('socket.onerror: ' + err.description + ', ' + err.code)};
  socket.onclose = function(){ console.log('socket.onclose')};
}

I run that code from jQuery, like so:
$(document).ready(function() {
    $.get('/admin/channel', {clientID:1}, listen_to_channel, 'json')
});

I link the dependencies like so:

The example code is clear that the socket should be created within the  tag of the HTML DOM. Is this the cause of my problem? If so, what does creating the socket within the  tag do differently?
Answer: Polling is how the channel-API is simulated in the SDK, so what you're seeing is expected.
Comment: Ah! Thanks. Do you have a reference?
Comment: You can see the code: https://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/devappserver2/channel.py


Should one scale the predictors for option pricing?

Question: I am not sure to know when one should scale the data used for feeding a NN.
I am fitting an NN to the B&S formula. I compute the option pricing for different parameters value (strike price, asset's price...).
And I don't know if I should scale my data.
Answer: In general, you should normalize your input using some method. This happens for at least two reasons:
1) Inputs of different magnitudes will affect differently the weights of the neural network. This will make the convergence more difficulty.
2) If the input are larger it can cause the saturation of the intermediate units of the neural network.
Comment: I think you not have any problem if you normalize (scale) these features (predictors). Look: the order of magniture of the strike prices and interest rates may be completelly different. Imagine the effect (bad one) that will happen if you do not normalize your features!
Comment: OK thanks for the advice Daniel ! If you don't mind, I ll leave the question option, perhaps someone has another point of view on the question.
Comment: That I know, it is for that reason that I am asking. However, I don't know if it's common practice to do that for option pricing, and if perhaps certain parameters should be kept the same.
Comment: What parameters are you talking about? Exactly?
Comment: sorry I don't do enough statistics to have my vocabulary exactly accurate. I meant the features / predictors. The one I am talking about here are : "strike price, maturity, interest rate, initial asset value, vol of vol..."


Compute Var(x=X1+X2+...+Xn)

Question: Compute $Var(X_1+X_2+...+X_n)$ given $X_1,X_2...$ are iid.,$EX=\mu,Var(X)=\sigma ^2$,and $Var(N)=\sigma [n]^2$,
N is a random variable of nonnegative integers independent  with X,
and my solution is:
$Var(X_1+X_2+...+X_n)$
$=E(E((X_1+X_2+...+X_n)^2)-(E(X_1+X_2+...+X_n))^2)$
$=E(E(X_1^2+X_2^2+...+X_n^2)-(n\mu )^2) $
I've already proved $E(X_1+X_2+...+X_n)=n\mu$ and it's
$=E(E(X_1^2)+E(X_2^2)+...+E(X_n^2)-(nμ)^2)$
(And it is $E(X^2)=\mu^2+Var(X)=\mu ^2+\sigma ^2$)
$=E(n(\mu ^2+\sigma ^2)-(n\mu)^2)$
$=(\mu ^2+\sigma ^2)E(N)-\mu ^2*E(N^2)$
But the key given is $\sigma ^2*E(N)+\mu ^2*Var(N)$,I wonder if there is something wrong with my solution? Thanks for your help!
Comment: What's $X$ and what role does the random variable $N$ play? (Yes, I can *guess* what you mean but that's not the point.) Stating all definitions and assumptions clearly at the beginning of the question, increases the readability of your question quite a lot.
Comment: Your answer would be right if $\mu^2 (E(N) - E(N^2))$ were $\mu^2 Var(N)$. Cancelling $\mu$ from both sides says that it'd be right if
$$
E(N) - E(N^2) = Var(N).
$$

That's almost correct, isn't it? So does that lead you to an algebra error somewhere?
Comment: You are advised to read [this](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to improve your typesetting.
Comment: I suspect that not $\text{Var}(X_1+\cdots+X_n)$ but $\text{Var}(X_1+\cdots+X_N)$ must be calculated.
Comment: yes thanks Sassatelli, it's my first time on this site hh
Comment: I'm sorry saz but there is no more info from the question...
Comment: Yes John I've tried to find it but failed...
Comment: @drhab but there is no more info about X and I got lost ..
Answer: $\mathbb{E}\left(X_{1}+\cdots+X_{N}\mid N\right)=\mu N$ so that: $$\mathbb{E}\left(X_{1}+\cdots+X_{N}\right)=\mu\mathbb{E}N$$
$\mathbb{E}\left(\left(X_{1}+\cdots+X_{N}\right)^{2}\mid N\right)=\sigma^{2}N+\mu^{2}N^2$
so that: $$\mathbb{E}\left(X_{1}+\cdots+X_{N}\right)^{2}=\sigma^{2}\mathbb{E}N+\mu^{2}\mathbb{E}N^{2}$$
Working out:$$\text{Var}\left(X_{1}+\cdots+X_{N}\right)=\mathbb{E}\left(X_{1}+\cdots+X_{N}\right)^{2}-\left[\mathbb{E}\left(X_{1}+\cdots+X_{N}\right)\right]^{2}$$
we find:
$$\text{Var}\left(X_{1}+\cdots+X_{N}\right)=\sigma^{2}\mathbb{E}N+\mu^{2}\mathbb{E}N^{2}-\mu^{2}\left[\mathbb{E}N\right]^{2}=\sigma^{2}\mathbb{E}N+\mu^{2}\text{Var}N$$

Edit:
$$\mathbb{E}\left(\left(X_{1}+\cdots+X_{N}\right)^{2}\mid N=n\right)=\mathbb{E}\left(X_{1}+\cdots+X_{n}\right)^{2}=$$$$\sum_{i=1}^{n}\sum_{j=1}^{n}\mathbb{E}X_{i}X_{j}=n\mathbb{E}X_{1}^{2}+n\left(n-1\right)\mathbb{E}X_{1}X_{2}$$
Here $\mathbb{E}X_{1}^{2}=\text{Var}X_{1}+\left(\mathbb{E}X_{1}\right)^{2}=\sigma^{2}+\mu^{2}$
and $\mathbb{E}X_{1}X_{2}=\mathbb{E}X_{1}\mathbb{E}X_{2}=\mu^{2}$.
This leads to: $$\mathbb{E}\left(\left(X_{1}+\cdots+X_{N}\right)^{2}\mid N=n\right)=n\left(\sigma^{2}+\mu^{2}\right)+n\left(n-1\right)\mu^{2}=n\sigma^{2}+n^{2}\mu^{2}$$
and consequently: $$\mathbb{E}\left(\left(X_{1}+\cdots+X_{N}\right)^{2}\mid N\right)=\sigma^{2}N+\mu^{2}N^{2}$$
Comment: Thanks for your answer! But I can't figure out as X are iid, why E((X1+⋯+XN)^2∣N)=σ^2N+μ^2N^2 instead of just σ^2N? Thanks~
Comment: See my edit. Btw, what makes you think that $E((X_1+\cdots+X_N)^2\mid N)=\sigma^2N$?
Comment: I'm sorry to make this elementary mistake...Thank you for your patient explanation! Wish buckets of love.

Compute Var(x=X1+X2+...+Xn)


how to actually install PHP etc on a windows 2003 server

Question: We're just purchasing a dedicated windows 2003 server (in fact I think it's a VPS)
How do we actually go about installing software on to it? Simply searching for "installing PHP5 on windows server" just produces material about installing it as if one had access to the computer with a keyboard and mouse.
Am I being thick? I've had experience managing a linux server before but that had everything pre-configured and we accessed it via Web Hosting Manager.
I don't get the actual concept of connecting to a remote PC and...downloading files?
If there's any good books available please point me in the right direction.
Comment: If you don't get the concept of remotely connecting to a server and downloading files on it, [this is probably not an appropriate site for you, being for professional Systems Administrators.](http://serverfault.com/faq)
Answer: You need some sort of remote access. With windows, it's mostly either remote desktop, or in some special, rare cases, a special access console (software) to access the virtual machine (something like remote desktop, but the windows on the other side thinks it's a local display/io-device).
After getting that, you can follow the tutorials you've found.


Declaring variables before "{}" using ":" in class constructer

Question: I've been flipping through the SFML blueprints book to start getting my feet wet in graphics. I noticed in one of their code examples in their game class constructor:
Game::Game() : _window(sf::VideoMode(800,600), "SFML Title") {
     code code code...
}

The _window(sf::VideoMode(800,600), "SFML Title") being placed before the {}, not inside. Is this bad practice? What is doing this called? I'm still new to c++ but I haven't come across something like this yet.
Comment: It's good practice, it's called [member initializer lists](http://en.cppreference.com/w/cpp/language/initializer_list)
Answer:
Is this bad practice?

No, it's good practice. If the member is const qualified type or reference type, it's the only way to initialize that member in constructor.

What is doing this called?

It's called member initializer lists
Answer: That's called a member initialization list. They're part of the C++ language. A member initialization list allows you to initialize members during class initialization. One reason why they're  good practice is because they allow you to initialize const members when assigning won't work. For example, the following class definition won't work because const int member1 wasn't initialized with a value, nor can you assign to a const int because const makes it read-only.
class Game{
private:
    const int member_var; //won't work, needs to be initialized
    int member_var2;
public:
    Game() {} //Game constructor
};

With initialization lists, you're able to initialize const members like these and other variables by adding a colon after your constructor definition (but before the brackets to define it) and initializing members as needed, either with direct initialization (using "()") or uniform initialization (using "{}"). To initialize multiple members, separate them with a comma.
class Game{
private:
    const int member_var;
    int member_var2;
public:
    Game(): member_var(1), member_var2(2) {}
    //Uniform initialization is ": member_var{1}, member_var{2}"
};

In your example, the Game() constructor was defined outside the class definition (likely in another .cpp file) via Game::Game() with a member initialization list. I'm guessing _window is a class with one constructor that takes sf::VideoMode(800,600) and  "SFML Title" as arguments.


Could client side javascript act as a web spider?

Question: Could ajax be used on the client side javascript to function as an in-the-background web spider? You'll have to excuse the vagueness of this post because I really have no idea where to begin technically in terms of the code and there is nothing online about a program like this.
Comment: No.Because of cross domain restrictions
Answer: You can use a cors proxy type script in order to do these Ajax requests client side via javascript. Look on Github for 'cors proxy', and set that up in your Node.js environment, then pass all of your ajax calls client side through this proxy.
Answer: You cannot make ajax requests to different hosts, so no.
Comment: could you do it without ajax?
Comment: You can't "load" pages with javascript without ajax whitout actually navigating to that page. Once you navigate to another page your javascript does not run anymore.
Short answer this is not possible at all.
Answer: Yes its possible but with some restrictions, meant only to be done from a specially-configured browser, not for arbitrary users to just run:
For chrome, open it using the command-line parameter --disable-web-security.
now you can do cross domain and such.
I assume you just want it for using yourself as a server and not on a public web page.
Comment: could I make ajax requests to different hosts if I used the command-line parameter --disable-web-security


vpc subnet change wont let me start emr cluster

Question: I want to move our emr clusters to a new VPC (new subnets).
When the cluster is started, it fails on:
TerminatingService role EMR_DefaultRole has insufficient ec2 permissions. Refer to policy arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceRole for more information
and thats about it. The role nor its connected roles do not have any subnet specific or vpc specific definitions. Help ?
Answer: To solve this delete the current roles and create new default roles.
This AWS knowledge article might help you solve this problem.
EMR_DefaultRole is invalid
Summary:

The creation and deletion of instance profiles associated with the
  default roles are automatically handled by the console. This error can
  occur if the instance profile associated with the EMR_DefaultRole or
  EMR_EC2_DefaultRole is not configured correctly, or if the current
  configuration for the instance profile is no longer sufficient to
  launch an EMR cluster.
As a workaround, you can delete both EMR_DefaultRole and
  EMR_EC2_DefaultRole and the instance profile associated with them.
  Deleting a role does not automatically delete the instance profile, so
  you need to delete it manually.


How to display a node as multi-step?

Question: I have installed Multistep module and it worked well for forms (e.g. save node, edit node). But when I switched to "Manage Display" tab and add "Multistep Form" group, it didn't work. No multistep form block appeared in Structure->Block for displaying a node.
I have also tried "Div" for displaying field group, but it's just a collapsible box.
Is it possible to display node as multi-step?
Answer: It is possible to use node as multi step form with help of  page break field  Module . Enabled it and make it as one of the field where want in the node

How to display a node as multi-step?


Should assumptions be used for SIMPLE linear regression analysis?

Question: Should I use the same assumptions checking during the linear regression analysis as I use them for Multiple regression analysis? Can it be used at all?
in assumptions, I mean: 1.  multicollinearity; 2. normality; 3. influential cases; 4. homoscedasticity; and 5. autocorrelation.
Comment: Don't forget the linearity assumption.
Comment: The assumptions are the same. But note that if you're not doing inference (the usual normal theory tests, confidence intervals, prediction intervals etc) then you don't need to be making the assumptions. .... Given that both multiple and simple regression are linear, is it necessary to capitalize the word LINEAR in your title and body-text?
Comment: Are you sure about the title? Of course, you need some assumptions; linear regression is not completely free of assumptions. But that is perhaps not the real question here, or is it?
Comment: I meant the difference between assumptions for linear regression and multiple linear regression.
Comment: Based on you answer it really seems that you should change your title. Also, when replying to a comment, please use "@RichardHardy", otherwise I do not get notified of your comments.
Comment: Even if not doing inference, failure to satisfy certain assumptions can hurt.  For example in a very asymmetric residual distribution one might not even be best served by estimating means (which is what regression does).
Answer: The only "assumption" that goes away when you simplify a model from multiple regression down to linear regression is multicollinearity.  That's for a simple reason.  When you have one single independent variable, it does not have any other variables to be collinear with.  So, the issue evaporates.  Most all other assumptions entail testing the residual of your regression.  And, for the testing of residuals it makes no difference whether your regression has one independent variable (linear regression) or more than one independent variable(multiple regression).
Comment: Co-linearity is not an assumption.  It is a challenge although often it doesn't harm us.
Comment: Thank you for the answer! it may not be related here, but could I ask you one more question please: In multiply regression, how to calculate percentage of variance of specific variable using r squared and standardized beta?
Comment: for the upper post..
Comment: @Frankharell it is indeed an assumption on the relationship in the population, you have a sample so naturally it is something to think about
Comment: Geo, your earlier questions within your comments entails mainly calculating standardized regression coefficients.  It is very easy.  Let's say we calculate it for X1.  Its standardized coefficient of X1 = X1 reg. coefficient times X1 Standard deviation/Y Standard deviation.  Let's say X1 has a reg. coif. of 0.5 and a standard deviation of 3.  Meanwhile, Y has a standard deviation of 1.  X1 standardized coefficient: 0.5 times 3/1 = 1.5.


How to determine the max file upload limit in php

Question: How can the file upload size allowed by php settings be determined withing a php script?
Answer: The upload is limited by three options: upload_max_filesize, post_max_size and memory_limit. Your upload is only done if it doesn't exeed one of them.
The ini_get() function provides you with a short hand of the limit and should be converted first. Thx to AoEmaster for this.
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last)
    {
        case 'g':
        $val *= 1024;
        case 'm':
        $val *= 1024;
        case 'k':
        $val *= 1024;
    }
    return $val;
}

function max_file_upload_in_bytes() {
    //select maximum upload size
    $max_upload = return_bytes(ini_get('upload_max_filesize'));
    //select post limit
    $max_post = return_bytes(ini_get('post_max_size'));
    //select memory limit
    $memory_limit = return_bytes(ini_get('memory_limit'));
    // return the smallest of them, this defines the real limit
    return min($max_upload, $max_post, $memory_limit);
}

Source: http://www.kavoir.com/2010/02/php-get-the-file-uploading-limit-max-file-size-allowed-to-upload.html
Comment: Should be noted that this does not account for shorthand notation in ini files, so if you have a limit of "64M" it will be parsed as 64. Best to convert all to bytes before comparing.
Comment: Made the answer fit the needs.
Comment: I agree with Brady, most ini files I see now use shorthand notation.
Comment: See this conversion http://stackoverflow.com/questions/13076480/php-get-actual-maximum-upload-size
Comment: Another thing which may limit a file upload is runtime. Check max_execution_time and max_input_time.
Comment: Another thing which may prevent a large file transfer from completing successfully is the temporary directory filling up. PHP sends your file to a temporary loacation such as /tmp/phpE4oNJI, and then moves it to the destination. Check php.ini for upload-tmp-dir. I think the default is /tmp. If this directory is too small to hold your file, you can make it bigger, or change upload-tmp-dir to use a different directory.
Comment: Note: If any of the three ini setttings is set to "unlimited", this code will return 0 or -1. But you cannot say that 0 or -1 indicate no upload limit, as the two other settings might be >0.
Comment: People voting for buggy function. Nice! return_bytes() contains an error. You have to get a numeric part of $val before switch(), e.g $val = substr($val, 0, -1);
Answer: Use ini_get to get the current configuration value:
ini_get('upload_max_filesize')

Answer: Here's a single function, implementing the original idea from AoEmaster.
The function returns integer (amount of bytes).
function _GetMaxAllowedUploadSize(){
    $Sizes = array();
    $Sizes[] = ini_get('upload_max_filesize');
    $Sizes[] = ini_get('post_max_size');
    $Sizes[] = ini_get('memory_limit');
    for($x=0;$x<count($Sizes);$x++){
        $Last = strtolower($Sizes[$x][strlen($Sizes[$x])-1]);
        if($Last == 'k'){
            $Sizes[$x] *= 1024;
        } elseif($Last == 'm'){
            $Sizes[$x] *= 1024;
            $Sizes[$x] *= 1024;
        } elseif($Last == 'g'){
            $Sizes[$x] *= 1024;
            $Sizes[$x] *= 1024;
            $Sizes[$x] *= 1024;
        } elseif($Last == 't'){
            $Sizes[$x] *= 1024;
            $Sizes[$x] *= 1024;
            $Sizes[$x] *= 1024;
            $Sizes[$x] *= 1024;
        }
    }
    return min($Sizes);
}

If you want, you can combine it with the following function that renders the output as a human readable text.
function _Byte2Size($bytes,$RoundLength=1) {
    $kb = 1024;         // Kilobyte
    $mb = 1024 * $kb;   // Megabyte
    $gb = 1024 * $mb;   // Gigabyte
    $tb = 1024 * $gb;   // Terabyte

    if($bytes < $kb) {
        if(!$bytes){
            $bytes = '0';
        }
        return (($bytes + 1)-1).' B';
    } else if($bytes < $mb) {
        return round($bytes/$kb,$RoundLength).' KB';
    } else if($bytes < $gb) {
        return round($bytes/$mb,$RoundLength).' MB';
    } else if($bytes < $tb) {
        return round($bytes/$gb,$RoundLength).' GB';
    } else {
        return round($bytes/$tb,$RoundLength).' TB';
    }
}

Use it this way:
echo 'Max allowed upload size: '._Byte2Size(_GetMaxAllowedUploadSize());

A result could be:
Max allowed upload size: 500 MB
Answer: You can also change that size at runtime using the .htaccess file without the need to change your php.ini file
php_value upload_max_filesize 1224M
php_value post_max_size 1224M
php_value max_execution_time 3000
php_value max_input_time 3000

copy that code and put your file, then store that file with index file then you run your project you also capable to upload 1GB file
for more detail read this article
Answer: function return_bytes($val)
{
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);

    switch($last)
    {
        case 'g':
        $val *= 1024;
        case 'm':
        $val *= 1024;
        case 'k':
        $val *= 1024;
    }

    return $val;
}

function get_upload_max_filesize()
{
    $max_upload = return_bytes(ini_get('upload_max_filesize'));
    $max_post = return_bytes(ini_get('post_max_size'));
    return min($max_upload, $max_post);
}

Answer: You can set Maximum file upload size using ini_set()
  ini_set('post_max_size', '64M');
  ini_set('upload_max_filesize', '64M');

or
using the .htaccess file
php_value upload_max_filesize
php_value post_max_size

Comment: Some of these settings can be changed inside a .php script using ini_set, and some can't. See http://php.net/manual/en/ini.list.php for the full list. For example post_max_size says:

"PHP_INI_PERDIR  PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.3."

In order to decipher what "PHP_INI_PERDIR" means, see http://php.net/manual/en/configuration.changes.modes.php

PHP_INI_PERDIR  Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)

So post_max_size cannot be set in a PHP script via ini_set().


Join multiple tables in D7 Views

Question: I'm trying to create a View Block to display related information on a node.
I'm creating an image gallery where each image node is tagged with one/more taxonomy terms, and a block on each of those nodes then displays a list of users who have expressed an interest in the same taxonomy term(s).
So the node is tagged with e.g "landscape" and a user has a Profile2 profile in which they have have also selected "landscape" with a taxonomy ref field.
I'm having trouble building the view to achieve this. If I create a new view with a block and select that i'm displaying "Profiles" from the initial dropdown, views seems to remove some of the kinds of objects I can choose in the Contextual Filters or Relationships menus: Node isn't available for linking in a relationship.
If I go about in the "other direction" and make a view of Nodes, then try and create relationships backwards to the Profiles I want, I'm unable to select fields present in the Profile for output - the only fields available are those on the Node.
It seems that by choosing a specific kind of object to list, Views immediately excludes certain possibilities for joining.
Is this not possible? I know what the exact SQL would be, but I'd rather not write a module if a View would do.
Answer: Should the relationship not go via the taxonomy reference rather than direct profile to node? Or have I misunderstood what you've tried/want to achieve?
Comment: Doh, school-boy error. For some reason I was trying to go directly via the profile direct to the node! Eventual query basically was:

Build a view of profiles, relationship on profile "preferred tags", another relationship on taxonomy, then, another on "content using tag X" then a contextual filter on the current node ID from the URL.

Cheers for the help, bud!
Comment: Welcome! It can certainly be easy at times to lose sight of things behind the UI :-) Glad to help

Join multiple tables in D7 Views