django admin/options.py TypeError: 2 options needed, 3 given

Question: Edit: I have posted the full traceback below, as requested.
I needed some custom logic to happen before deleting a pages model, so I overloaded the delete() method. (I know this is bad form. I fixed it later, but it's important to express how I got into this mess)
With something like this:
def delete(self, *args, **kwargs):
    # Do some stuff...
    super(Pages, self).delete()

Unfortunately, this caused the following TypeError when I tried to delete the page via the admin interface: delete_model() takes 2 positional arguments but 3 were given
I decided that I needed to do things properly, and so I deleted the delete method overload, and implemented pre_delete logic via the following signal handler:
@receiver(pre_delete, sender=Pages)
def handle_page_delete(sender, **kwargs):
    obj = kwargs['instance']

    if(obj != None):
        tmp1 = obj.prev_id
        tmp2 = obj.next_id

    if(tmp1 != None):
        tmp1.next_id = tmp2
        obj.prev_id = None

    if(tmp2 != None):
        tmp2.prev_id = tmp1
        obj.next_id = None

I followed best practices by putting the handler in a signals sub-module and by registering it via ready() in an overloaded AppConfig in apps.py.
Unfortunately, I still got the same error: TypeError delete_model() takes 2 positional arguments but 3 were given
I then re-implemented the overloaded delete function as a stub, thinking that maybe I just needed to put the proper options in. So, I kept the signals logic around, and simply added the following back into my Pages model:
def delete(self, *args, **kwargs):
    super(Pages, self).delete(*args, **kwargs)

You'll note that this time I searched through the documentation, and I put the proper two *args, and **kwargs arguments.
But I still get the same TypeError: delete_model() takes 2 positional arguments but 3 were given
So finally, I commented out all custom deletion logic whatsoever, and only used the vanilla django codebase. I still get the same error: delete_model() takes 2 positional arguments but 3 were given
What gives? The exception location is inside my django installation itself, in django/contrib/admin/options.py. I've never had problems with the installation before, and I don't think I should consider that this is a problem with django itself. I really think I'm the one doing something wrong here, but I'm kind of stuck with no real idea of where to go from here.
Any help would be greatly appreciated. Thank you for your time.
Edit
As requested, the Full trace is as follows:
Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/admin/webcomics/pages/13/delete/

Django Version: 1.10.5
Python Version: 3.6.0
Installed Applications:
['webcomics.apps.WebcomicsConfig',
 'tinymce',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
  544.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
  211.             return view(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python3.6/contextlib.py" in inner
  53.                 return func(*args, **kwds)

File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/options.py" in delete_view
  1718.             self.delete_model(request, obj)

Exception Type: TypeError at /admin/webcomics/pages/13/delete/
Exception Value: delete_model() takes 2 positional arguments but 3 were given

Comment: Is there anything shown in the traceback prior to the error coming from options.py? I mean - you haven't named an attribute in either a model/(model)admin/similar `delete` somewhere or other?
Comment: What django version are you using?
Comment: Can you post the full trace?
Comment: That error doesn't seem to be coming from this code.
Comment: @Escher, Done. @schwobaseggl, I am using django version 1.10.5. @Jon Clements, I could always have missed it, but I did go through the code multiple times looking for stray `delete` keywords, but couldn't find any. :(
Comment: Can you post your admin.py and model definition for that `Pages` model?
Comment: @Escher O.O ... oh, my. And there the problem was all along, staring me in the face. I will post an answer detailing what happened, but the issue was with the admin.py. Thanks for bringing it up, Escher.
Answer: everyone. So, yes, I was doing something wrong. Thanks go out to Escher, who suggested that I have a look at my admin.py file. Turns out, there were some duplicate overloaded delete() and delete_model() methods I had forgotten to, poetically enough, delete. Everything cleared up shortly after I got rid of the duplicates. Jon Clements was right, as well.


Estou com erro no latex no windows 10 32 bits

Question: No Texmaker ou TexStudio sempre dá erro:
<code>Error: Could not start the command.
</code>
O que será?
Answer: Você já instalou o MiKTeX no Windows 10?
Baixe em:
http://miktex.org/download


Obter nome das propriedades de um Json

Question: Como faço para obter os nomes das propriedades de um Json utilizando a biblioteca Gson?
Exemplo de entrada:
{
   "Ficha":[
      {
         "nome":"nome",
         "sobrenome":"sobrenome",
         "idade":"idade",
         "endereco":"endereco",
         "empresa":"empresa",
         "telefones":[
            {
               "residencial":"residencial"
            },
            {
               "celular":"celular"
            }
         ]
      }
   ]
}

Saída esperada:
["nome", "sobrenome", "idade", "endereco", "empresa", "telefones", ...

Comment: olha escrevi errado tem que imprimir assim ["nome","sobrenome","idade"]....   os nomes da propriedades
Comment: Você fala na biblioteca `gson`, então a linguagem é Java, e não JavaScript, correto? Se for o caso, favor remover o tag `javascript` da pergunta.
Answer: Segue uma das forma de fazer oque você procura:

var json = {
  "Ficha": [{
    "nome": "nome",
    "sobrenome": "sobrenome",
    "idade": "idade",
    "endereco": "endereco",
    "empresa": "empresa",
    "telefones": [{
      "residencial": "residencial"
    }, {
      "celular": "celular"
    }]
  }]
};

var output = [];

for (property in json.Ficha[0]) {
  output.push(property);
  // Uma propriedade de cada vez
  alert(property);
}

// Caso deseje utilizar todas as propriedades de uma única vez
alert(output.join(' | '));
Answer: Usando o Gson, você pode usar o método entrySet para obter todas as propriedades de um JsonObject, como mostra o exemplo abaixo.
String json =
    "{" +
        "\"Ficha\":[" +
            "{" +
                "\"nome\":\"nome\"," +
                "\"sobrenome\":\"sobrenome\"," +
                "\"idade\":\"idade\"," +
                "\"endereco\":\"endereco\"," +
                "\"empresa\":\"empresa\"," +
                "\"telefones\":[" +
                    "{" +
                        "\"residencial\":\"residencial\"" +
                    "}," +
                    "{" +
                        "\"celular\":\"celular\"" +
                    "}" +
                "]" +
            "}" +
        "]" +
    "}";
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
JsonObject primeiraFicha = json.get("Ficha").getAsJsonArray().get(0).getAsJsonObject();
Set<Entry<String, JsonElement>> properties = primeiraFicha.entrySet();
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (Entry<String, JsonElement> property : properties) {
    if (!first) sb.append(",");
    first = false;
    sb.append(property.getKey());
}
sb.append("]");
System.out.println(sb.toString());

Comment: carlosfigueira poderia me mandar as importação esta dando erro
Comment: Você precisa `import` o JsonElement, JsonObject e JsonParser de com.google.gson além de `java.util.Map.Entry` e `java.util.Set`
Comment: vc mexe tambem com fasterXML

Obter nome das propriedades de um Json


From difference in means to distance between distributions

Question: Let X and Y be two random variables in $\mathbb{R}$. I'm looking for statements of the form: $E(X)-E(Y) \leq D(X,Y)$, where D() is a certain metric (e.g., total variation, KL-divergence, etc.) Not hoping for anything in full generality, but curious what such statements may look like.
For instance, if X and Y are random variables taking values over the same finite set in $\mathbb{R}$, then it's easy to show that there exists $c>0$ such that $|E(X-Y)|\leq c\cdot D_{TV}(X,Y)$ where $D_{TV}$ is the total variational distance. Are there more general statements of this kind, e.g., for continuous random variables with unbounded support?
Comment: $D_TV(X,Y) \leq 2$. So you cannot have such an inequality with $X$ and $Y$ unbounded.
Comment: Great point! Indeed, it shouldn't be possible to show this when E(X-Y) is large, but could some of thing of this kind be true if we know, say, E(X-Y) < 1?
Answer: As you consider KL-divergence then it's normal if the metric is defined not for all r.v.
$EX - EY \le \rho(X,Y)$ where $\rho(X,Y) = E|X-Y|$.
Moreover, $EX - EY \le \rho_1 (X,Y) \le \rho_p(X,Y)$ by Lyapunov's inequality where  $\rho_p(X,Y) = (E|X-Y|^p)^{\frac1{p}}$.
Comment: Thanks! In this particular case, we'd like to end up with either KL or TV on the right-hand side.


Normalization Interval variable

Question: I have to perform a regression.
My data set is composed of 12 independent(ration) variables
and 1 dependent(interval) variable.
After having performed a Normality test(kolmogorov-Smirnov) it resulted the none of the variables were normally distributed. It is common practice to normalise the variables before a regression. My question is: should I normalise also the dependent(interval) variable?
this represents a scale of quality. Would normalising it undermine the result or it's perfectly fine to normalise all the dataset and keep the dependent variable unnormalised?
Answer: Regression
First of all, for linear regression your variables doesn't have to be normally distributed. What you are interested in is if the residuals are normally distributed.
Simple linear regression is defined as:
$$y_i = \beta_0 + \beta_1x_i + \epsilon_i$$
where $\beta_0$ is an intercept, $\beta_1$ is a slope and $\epsilon_i$ is a residual. The regression line is an expected value for $y_i$ observation being a linear function of the explanatory variable:
$$E(y_i) = \beta_0 + \beta_1x_i$$
and there is some variance ($\sigma$) of residuals around this value:
$$ y_i \sim Normal(\beta_0 + \beta_1x_i, \sigma)$$
The relation between your explanatory and the dependent variable has to be linear with residuals normally distributed and having a stable (i.e. homoscedastic) variance. Below you can see a diagram illustrating this (source here). As you can see, it's not $X$ or $Y$ that are normally distributed, but the residuals centred around value estimated using the linear regression model.

Normalization
The second thing is normalization. We define it as follows:
$$z_i = \frac{x_i - \mu}{\sigma}$$
so that the resulting variable $z$ has mean of 0 and standard deviation of 1. This doesn't make this variable a normally distributed one. After transformation, it has a standard scale, so if you use this kind of transformed variable you'll get a standardized regression estimates (estimates with mean 0 and standard deviation of 1, i.e. $z$-scores).
Below you can find an example of 1000 values drawn from uniform distribution (left side) and the same values "normalized" (right side). The distribution on the right side is not more "normal" than it was before, the only thing that changed is it's scale.

So the only thing that changes in here is the scale of explanatory variable. The change is helpful because it enables you to get "scale free" estimates of regression parameters, what makes their interpretation easier because the regression parameters relate to the standard deviations. The same is with normalizing the dependent variable - the only thing that changes is scale, the data stays the same. This kind of data transformations are commonly used in multilevel modelling where centering (i.e. subtracting the mean) is commonly used.
Check those online lectures to find out more on linear regression.

Normalization Interval variable


( A ∩ B ) \ ( A ∩ C ) = ( A ∩ B ) \ C how to prove?

Question: I have to prove that. While I know this is true by thinking about it I'm having a lot of trouble actually writing the proof
Answer: The easiest and most intuitive way is probably to draw a diagram of the 3 sets. Showing the intersection areas between each pair of the sets and the intersection of all three sets. Once you have the diagram and it is clear why this formula is true, it should be easy to write a full proof from there.
Answer: If $x \in A \cap B \setminus A \cap C$, then $x \in A$ and $x \in B$, but $x \notin A \cap C$, whence $x \notin C$.
Therefore, $x \in (A \cap B) \setminus C$.
Answer: Before what's written below I'd like to make sure to explain the following: The intersection operator is "equivalent" to the logical "and", while the difference operator is likewise "equivalent" to ""and not"
$$\cap \sim \land ;\text{ } \text{ }\text{ }\text{ } \backslash \sim (\land \lnot) $$
I hope it's easy to see why
Whenever the proof is too hard (or you can't warp your head around it), bruteforce it
What I mean by using brute force when dealing with sets is writing everything down in logic
let's try to analyze $x \in (A \cap B )\backslash (A \cap C)$
This roughly translates to "$x$ is in A AND $x$ is in B, but $x$ is not in A AND C at the same time"
logically this would be $$(x \in A \land x \in B) \land \lnot(x \in A \land x \in C)$$
Now, we can transform that negation into $$(x \in A \land x \in B) \land (x \notin A \lor x \notin C)$$
Distribute around the "or" to get two cases
Case 1) $ x \in A \land x \in B \land x \notin A$
Case 2) $x \in A \land x \in B \land  x \notin C$
You can quickly check that Case 1 is a contradiction, so we can only have the case 2. So the set on the left can be written conditionally-logically as $\{x \mid x \in A \land x \in B \land  x \notin C\}$
Now let's look at the set on the right. $x \in (A \cap B) \backslash C$ roughly translates to "$x$ is in A AND B, but not in C"
Written logically this is $$(x \in A \land x \in B ) \land \lnot (x \in C)$$
which is just $x \in A \land x \in B \land  x \notin C$  just like the set on the right. So they're equal
If you find it hard to find a way to prove a "logical identity", you can go "Berserk Force" on it, taking an extra step to check that the truth tables for both expressions are the same. This is like extra-brute force


Prove that $[\mathbf{Q}(\sqrt{1+i},\sqrt{2}):\mathbf{Q}]=8$.

Question: I am trying to calculate the Galois group of the polynomial $f=X^4-2X^2+2$. $f$ is Eisenstein with $p=2$, so irreducible over $\mathbf{Q}$. I calculated the zeros to be
$\alpha_1=\sqrt{1+i},\alpha_2=\sqrt{1-i},\alpha_3=-\alpha_1$ and $\alpha_4=-\alpha_2$. Let $\Omega_f=\mathbf{Q}(\alpha_1,\alpha_2,\alpha_3,\alpha_4)=\mathbf{Q}(\alpha_1,\alpha_2)$ be a splitting field of $f$ over $\mathbf{Q}$. Since $\alpha_1\alpha_2=\sqrt{1+i}\sqrt{1-i}=\sqrt{2}$, we have $\Omega_f=\mathbf{Q}(\sqrt{1+i},\sqrt{2})$.
So if we can prove that $[\Omega_f:\mathbf{Q}]=8$, then we have $\#\operatorname{Gal} (f)=8$ and for $\operatorname{Gal}(f)\subset S_4$, we must have that it is isomorphic to the dihedral group $D_4$.
How do I go about proving $[\mathbf{Q}(\sqrt{1+i},\sqrt{2})]=8$?
Comment: Degree $8$ is proved [here](https://math.stackexchange.com/questions/2538096/galois-group-of-x4-2x22-apparent-contradiction?rq=1).
Comment: @DietrichBurde there is no need for a downvote, I was aware of that question but I did not find the explanation clear enough.
Answer: You have shown that your splitting field is $K=\mathbf Q(\sqrt {1+i}, \sqrt {1-i})$. The two fields $\mathbf Q(\sqrt {1\pm i})$ are obviously quadratic extensions of $\mathbf Q(i)$, and these are equal iff  $(1+i)(1-i)=2$ is a square in $\mathbf Q(i)$, iff $\sqrt 2\in \mathbf Q(i)$: impossible. Hence $K$ is a biquadratic extension of $\mathbf Q(i)$, and $[K:\mathbf Q]=8$.
Answer: Break it into towers.
Look at the two extensions $\mathbb Q ( \sqrt {1+i} )|_{Q(i)} $ and $\mathbb Q ( \sqrt {1-i} )|_{Q(i)} $.
Each has degree $2$ ( since $1+i$ and $1-i$ are primes in $\mathbb Z[i] $ which is a UFD ).
Their compositum is the field you are interested in i.e. $ \mathbb Q (\sqrt {1+i} , \sqrt {1-i} )$
At this point you can have a look at the question Finding degree of a finite field extension
I hope you have seen the similarity.
You have a UFD $\mathbb Z[i]$ , it's field of fractions $\mathbb Q(i)$ and you have adjoined square roots of two distinct primes $1+i , 1-i$.
By a similar argument as in the question above we argue the Galois group is of the form $\mathbb Z_2 ^k$ with $k\leq 2$.
But then you got $3$ distinct degree $2$ subextensions $\mathbb Q(\sqrt {1+i}), \mathbb Q(\sqrt {1-i}) ,  \mathbb Q(\sqrt {2}) $
This gives you $k\geq 2$
So the upshot is $$\mathbb Q(\sqrt {1+i}, \sqrt 2): \mathbb Q(i)=4$$
And conclusion follows.


Question about the limits of definite integrals

Question: Let me take an example that I've come across while studying Fourier series,
We all know that
$$\int_{-a}^{a} \sin \left( \frac{n\pi x}{a} \right) dx = 2 \int_{0}^{a} \sin \left(\frac{n \pi x}{a} \right) dx$$
So why is it that when evaluating both sides separately the results seem to differ?
I. $$\int_{-a}^{a} \sin \left( \frac{n\pi x}{a} \right) dx =  -\frac{a}{n \pi} \cos \left( \frac{n\pi x}{a} \right)_{-a}^{a} = -\frac{a}{n \pi} \left[ \cos (n\pi) - \cos(-n \pi) \right] = 0$$
II. $$2 \int_{0}^{a} \sin \left(\frac{n \pi x}{a} \right) dx = -\frac{2a}{n \pi} \cos \left( \frac{n\pi x}{a} \right)_{0}^{a} = - \frac{2a}{n\pi} \left[ \cos(n \pi) - 1\right] = \begin{cases}
 0, & \text{if } n\text{ is even} \\
 \frac{4a}{n\pi}, & \text{if } n \text{is odd}
\end{cases}$$
My question is, how can I also obtain $\frac{4a}{n\pi}$ from a direct integration from $-a$ to $a$ ? The expression $\left[ \cos (n\pi) - \cos(-n \pi) \right]$ seems to be always $0$, right? Regardless of $n$ being even or odd. Or am I missing something here?
Comment: The "We all know that" is wrong. The integral of an odd function over an interval $[-a,a]$ is always $0$. The integral over $[0,a]$ need not be $0$.
Comment: I think the assertion following the "we all know that" is not true, to begin with. The sine function is _odd_, so what we can easily see is that the integral is $0$... _not_ that the integrand is an "even" function, as that first displayed equality would suggest.
Comment: By the way, just to emphasize that $\int_{-a}^{a} f(x)dx = \int_{-a}^{0} f(x)dx + \int_{0}^{a} f(x)dx$ and if $f(-x)=-f(x)$ which is the case for the sine function, then $\int_{-a}^{0} f(x)dx = -\int_{0}^{-a} f(x)dx = \int_{0}^{a} f(x)dx$
Comment: @DanielFischer I see, but then why does my textbook makes the substitution then? If as you said, the integral of an odd function is always $0$ at $[-a,a]$ then it could have never been substituted to $[0,a]$ and yield a value other than zero. What's going on?
Answer: The statement after "We all know that" is completely false. $\sin(cx)$ for any $c$ is an odd function, so any integral on an interval symmetric around $0$ will give 0. The correct result is:
$$\int_{-a}^a\sin(cx)dx=\int_{0}^a\sin(cx)dx+\int_{-a}^0\sin(cx)dx,$$
and now do a change of variables on the second integral $u=-x$ and use the fact that $\sin(-x)=-\sin(x)$.


Multiple regression and OLS. How to choose the best "non-linear" specification?

Question: Let's say I have to make a multiple regression like:
$ Y_i = \beta_0 + \beta_1 x_i + \beta_2 w_i + ... +\beta_3 z_i + \epsilon_i $
Then I run a Ramsey RESET test upon it and discover that my linear specification is not good. What is the best way to cope with non-linearity? I know that I could specify a log-log model, a log-lin model, or add some powers on variables, or try interaction effects.
What I don't understand by reading Verbeek and Stock - Watson is: how to choose the best non-linear specification? Should I try all of them and then take a look at Akaike's Index (or Bayesian or Hannan Quinn)? Or is there a way to understand which specification is the best?
Sorry if I wasn't clear, English is not my native language.
Thank you in advance!
Comment: Definitely do NOT use AIC to select an optimal transformation of the dependent variable (which I think you were suggesting in the log-linear model). Likelihoods are not comparable between two models where the response has been transformed in different ways, so the AIC is not meaningful.
Comment: Of course you're right! My big mistake! So, would $ R^2 $ be a better indicator?
Answer: I've become rather enamoured of late with generalized additive modelling to handle non-linearity. The gam() function from the mgcv package for R makes things very easy as it incorporates automated generalized cross-validation to avoid overfitting.
Comment: Hi Mike. Thank you for your answer. Unfortunately (since my econometrics course is for beginners), I can use only one of the methods I've wrote about in my first question and only the program called gretl! Thank you again!
Comment: +1; @Luigi, that's a shame, because this approach really is the answer to your concern.  I believe gretl and R are somewhat similar, and R is also free, but *much* more extensive than gretl.  There are also a great deal of online tutorials, etc.; R may well be worth your while to learn.
Answer: I've never heard of gretl but a parametric version of the excellent gam suggestion by Mike is to use additive regressions such as restricted cubic splines (natural splines).  R and Stata make this easy to do.  With regression splines (piecewise polynomials) you can model almost any relationship that is fairly smooth, and you still get all the advantages of ordinary models (confidence limits, predictions, formulas, etc.).  A good default strategy is to figure what complexity the sample size and signal:noise ratio will support, translate that to the number of knots (join points) in the spline functions, and to fit those functions without later trying to simplify the model.  In R that would like like
require(rms)
f <- ols(y ~ rcs(x1,4) + rcs(x2,4)) # 4 knots for x1,x2 at default locations

Very few relationships in nature are linear, so it is good to learn about flexible nonlinear modeling.


Overestimated and underestimated predictions in regression

Question: I read somewhere,

In a regression problem, if the relationship between each predictor variable and the criterion variable is nonlinear, then the predictions may systematically overestimate the actual values for one range of values on a predictor variable and underestimate them for another.

Does anyone have an explanation to this behavior?
Comment: nonlinearity **is** the explanation, assuming you used a linear regression problem. Just draw some non-linear curve approximating some straight line.
Comment: consider, I have a dataset that it's target values range from -1 to 1. For test cases with target value near 1, I want to get predicted value larger than it's real value in test set. For example if the real value in a test case is 0.9, I want from my regression algorithm to predict it 0.95.
And for test cases with target value near -1, I want to get predicted value smaller than it's real value in test set. For example if the real value in a test case is -0.9, I want to my regression algorithm to predict it -0.95. Is it possible?
Comment: The question seems perfectly clear to me. I don't see that the OP *wants* to do this; they just seem to want to *understand* it, which I think is perfectly reasonable.
Comment: is there a way to customize this range of values?
Comment: Why do you want your algorithm to predict some wrong value?
Comment: ?? I still do not understand why you want this. Also, I do not see connection with the question as posted.
Answer: Here is a simple example (coded in R).  Hopefully the image is sufficiently obvious to explain how a nonlinear relationship (not model), when fit with a linear relationship, yields regions with predicted values that are systematically overestimated and underestimated.
set.seed(7439)                # this makes the example exactly reproducible
x = runif(50, min=0, max=15)  # X is uniformly distributed from 0 to 15
 # this is the true data generating process:
y = 3.7 - 2.5*x + 0.56*x^2 - 0.028*x^3 + rnorm(50, mean=0, sd=.3)
model = lm(y~x)               # here I fit a model with a linear relationship

windows()
  plot(x, y)                       # this plots the data
  abline(coef(model), col="gray")  # this plots the model's predicted values

Comment: If the model's functional from is appropriate, you should be fine.
Comment: thanks, but what happened when we have nonlinear relationship and also model it with a nonlinear algorithm?
Comment: thanks, but what happened when we have nonlinear relationship and also model it with a nonlinear algorithm? I saw overestimated and underestimated predictions in low and high values of targets respectively when using nonlinear model too.
Comment: This was just answered by @gung.  If you pick the correct functional form of the nonlinear model, you should be fine.  There shouldn't be a systematic underestimate or overestimate.
Comment: We can go a bit further to investigate the goodness of fit. `summary(model)
...
Multiple R-squared: 0.04939, Adjusted R-squared: 0.02959 F-statistic: 2.494 on 1 and 48 DF, p-value: 0.1208` You can observe the R-squared. It's too low. 2% indicates that the model explains almost none of the variability of the response data around its mean.
Comment: @MohammadKibria, R-squared is not goodness of fit (see [Is $R^2$ useful or dangerous?](https://stats.stackexchange.com/q/13314/)). You can have the same situation as here w/ R-squared as high as you like.


Finding a Basis for a Vector Space V Spanned by $S = \{v_1, v_2, v_3\}$

Question: I have a vector space $V$ spanned by $S =\{ v_1 = \sin^2x,\ v_2 = \cos^2x,\  v_3 = \cos2x\}$.
For the first part of the problem, I'm required to show that $S$ is not a basis for $V$ and in the second part, I need to find a basis for $V$.
I know that $S$ is not a basis for $V$ because the Wronskian of the three functions is equal to $0$, meaning the vectors are linearly dependent; however, I can't seem to figure out how to go about finding a basis for $V$.
I understand a basis to be a set of linearly independent vectors spanning $V$, but how would I find that set?
Comment: $v_1$ and $v_2$ forms a basis for $V$. Note: $cos(2x)= cos^2(x)-sin^2(x)$.
Comment: $\dots =2\cos^2x-1=1-2\sin^2x$.
Answer: Hint:
$$
v_3=\cos 2x= \cos^2 x- \sin^2 x= v_2-v_1
$$
so it is a linear combination of $v_1,v_2$,
but
$
a \sin^2x +b \cos^2 x=0 \quad \forall x
$
only if $a=b=0$


Burnside lemma application

Question: The problem is to find rotationally indistinguishable necklaces formed from beads of 2 colors with exactly 3 beads of each color i.e, each necklace is of length 6. If $X$ is the set of all possible permutations of these 6 beads, then $|X| = 6!/(3!)^2 = 20$. I tried to apply Burnside Lemma to this by considering the cyclic group $C_6$ of rotations and get $\frac{1}{6}(20+2)$: 6 is the order of the cyclic group, 20 for the identity element, $2!=2$ if you rotate the necklace by 2 beads. I dont think that there are any elements of X fixed for any other rotations. But this answer is obviously wrong, as it is not an integer.
Can you please help explain where I went wrong and how I can apply Burnside Lemma properly (or why I can't use it here if that is the case)?
Comment: You have to add up Fix(g) for all 6 elements of the group
Comment: Thanks! I thought I checked all the elements of the group and that the only cases where there were fixed elements were for identity and rotation by 2 beads. For the 2 bead rotation the fixed elements are (1, 2, 1, 2, 1, 2), (2, 1, 2, 1, 2, 1) [1 and 2 are colors]. Looking at them now, it looks like they are fixed for even rotation by 4 beads which adds another 2 to the summation. I also wrote a small program to check if there are any other fixed elements for other rotations and there are none. That makes the answer to be 4 instead of a fraction which matches what my program generates.
Answer: You just forgot the rotation of $4$ beads (the inverse of the rotation of $2$ beads)  which adds another $2$ at the numerator and we finally obtain
$$\frac{20+2+2}{6}=4$$
that is $(1,1,1,2,2,2)$, $(1,1,2,1,2,2)$,  $(1,1,2,2,1,2)$, $(1,2,1,2,1,2)$.
Comment: Yes, got it now. Being a novice in group theory I started doubting whether I made some other basic error. Accepting your answer.

Burnside lemma application


Como Melhorar/Otimizar este codigo?

Question: Possuo o seguinte codigo, e gostaria de saber se tem como melhorar, e como melhorar este codigo:
            $user = $_SESSION['nome_usuario'];
            $data = date('Y-m-d H:i:s');
            $lote = $this->request->data['lote'];
            $lote1 = $this->request->data['lote1'];
            $lote2 = $this->request->data['lote2'];
            $lote3 = $this->request->data['lote3'];
            $lote4 = $this->request->data['lote4'];
            $lote5 = $this->request->data['lote5'];
            $lote6 = $this->request->data['lote6'];
            if(!empty($lote)){
                $loteQtd = $this->request->data['qtdLote'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote = NULL;
            }
            if(!empty($lote1)){
                $loteQtd = $this->request->data['qtdLote1'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote1."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote1 = NULL;
            }
            if(!empty($lote2)){
                $loteQtd = $this->request->data['qtdLote2'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote2."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote2 = NULL;
            }
            if(!empty($lote3)){
                $loteQtd = $this->request->data['qtdLote3'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote3."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote3 = NULL;
            }
            if(!empty($lote4)){
                $loteQtd = $this->request->data['qtdLote4'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote4."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote4 = NULL;
            }
            if(!empty($lote5)){
                $loteQtd = $this->request->data['qtdLote5'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote5."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote5 = NULL;
            }
            if(!empty($lote6)){
                $loteQtd = $this->request->data['qtdLote6'];
                $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
                VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote6."'".','."'".$data."'".','."'".$user."'".')';
                $this->LotesMp->query($query);
            }else{
                $lote6 = NULL;
            }

Basicamente ele grava cada lote em uma linha no banco de dados, gravando no máximo 7 lotes, para 7 lotes ate que não fica muito extenso, mas caso seja necessário gravar 20 - 30 lotes, iria ter centenas de linhas.
Answer: Eu utilizei o contador do loop para concatenar com a string que representa a chave do array recebido da requisição.
$user = $_SESSION['nome_usuario'];
$data = date('Y-m-d H:i:s');
$lotes = $this->request->data();

for ($i = 0; $i < count($lotes); $i++) {
    $keyLote = 'lote';
    $keyLoteQtd = 'qtdLote';

    if ($i > 0) {
        $keyLote = $keyLote . $i;
        $keyLoteQtd = $keyLoteQtd . $i;
    }

    $lote = $lotes[$keyLote];

    if ($lote != '') {
        $loteQtd = $lotes[$keyLoteQtd];
        $query = "INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item,"
                ." lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)"
                ." VALUES ('$id', '$fornecedor', '$item', '$produto', '$loteQtd',"
                ." '$lote4', '$data', '$user')";

        $this->LotesMp->query($query);
    }
}

Evite usar a função empty() para verificar se variáveis do tipo string estão vazias (Comparação de tipos). Veja o seguinte caso:

$foo = 'null';
$bar = '0';

var_dump(empty($foo)); //false
var_dump(empty($bar)); //true

Comment: pois mas como ele falou conforme o numero de lote cresce ele teria que implementar mais algo na array ou seja 'lote7' =>  'qtdLote7' etc...
Comment: Não me atentei a este detalhe, vou atualizar a resposta. Valeu pela observação!
Comment: @ScrapBench, atualizei a resposta! Valeu xD
Comment: Bem limpinho o codigo muito bom
Answer: Boa tarde Alex
Eu recomendaria fazer uma iteracao por uma array e criar estas querys de forma dinamica exemplo
if(!isset($data))
   {
     return;
   }

$totalDeDataLotes = count($data);

for ($i=0; $i < $totaldelotes; $i++) {
  if ($i == 0) {
      $lote[$i] = $this->request->data['lote'];
  }
  $lote[$i] = $this->request->data['lote'.$i];
}

// a partir de aqui o seu $i sera a quantidade maxima de elementos na sua array $lotes
$a = 0;

while ($a <= $i) {
  if(!empty($lote[$i])){
    if ($a == 0) {
        $loteQtd = $this->request->data['qtdLote'];
    }

    $loteQtd = $this->request->data['qtdLote'.$a];
    $query = 'INSERT INTO lotes_mp (lote_nota, lote_nota_for, lote_item, lote_mp_id, lote_mp_qtd, lote_id, map_data, map_usuario)
               VALUES ('."'".$id."'".','."'".$fornecedor."'".','."'".$item."'".','."'".$produto."'".','."'".$loteQtd."'".','."'".$lote."'".','."'".$data."'".','."'".$user."'".')';
               $this->LotesMp->query($query);
  }
  else {
    $lote[$i] = NULL;
  }
$a++
}

Como Melhorar/Otimizar este codigo?


Proof of floor function is monotone

Question: Can anyone give a hint to approach this question? I have no idea
so far,
$f(x_1) = \lfloor x_1 \rfloor = n_1$ where ; $n_1 \leq x_1 < n_1 + 1$
$f(x_2) = \lfloor x_2 \rfloor = n_2$ where ; $n_2 \leq x_2 < n_2 + 1$
$x_1 < x_2 $ should imply $f(x_1)<f(x_2)$ (for increasing)
Comment: I'd review your definition of monotone. As stated, just check $x_1,x_2$ very close together.
Comment: But since you are trying to prove $P\to Q$, I'd start by assuming $\neg Q$ and use it to show $\neg P$
Comment: I think your definition should be that f is non-increasing or non-decreasing, but I would do as the next step is think about what you can deduce when $n_1=n_2$ or $n_1 < n_2$?
Comment: thank you for ideas
Answer: With what you have so far, I would try a direct proof.
Note: The definition of monotonic function is:
If for all $x$, $y$ such that $x \geq y$, then $f(x) \geq f(y)$.
The definition you stated is for strictly increasing.
Let $x_1, x_2 \in \mathbb{R}$.
Suppose $x_1 \leq x_2$, then
$f(x_1) = \lfloor x_1 \rfloor = n_1 \leq x_1 \leq x_2 < n_2+1$.
This implies $x_1 <n_2 +1 = \lfloor x_2 \rfloor + 1 = f(x_2) +1$
so we have $f(x_1) \leq x_1 \leq n_2 +1 <f(x_2) + 1$.
In conclusion, we now have $f(x_1)<f(x_2)+1$. We know that $f(x_1), f(x_2)$ are both integers, so what conclusion can we make about $f(x_1)$ and $f(x_2)$ ?

Proof of floor function is monotone


Service event_subscribe before path_processor_inbound

Question: I have ha service with tag: event_subscribe (KernelEvents::REQUEST) with priority 30 and in the same module a service path_processor_inbound with priority 29
The problem is: in event_subscribe Service creo a Constant but the service path_processor_inbound is called before.
I tried all the variants of priority, but it is not the problem.
Comment: _in event_subscribe Service creo a Constant but the service path_processor_inbound is called before_ 29 comes before 30 so that's right isn't it?
Comment: No, i want call first event_subscribe
Comment: Please edit your question, it currently says the opposite
Comment: ! U undestand priority ?
"The priority value is optional and defaults to 0. The higher the priority, the sooner it gets executed."
Comment: Oh I see, Symfony and Drupal have different definitions of "priority". In Drupal's API, a lower number means a higher priority; a numerical running order if you will. I'd post your code and describe the methods you're using to confirm the priority is being set properly etc
Comment: Now i try: (same problem)

module_event_subscriber:
    class: Drupal\country\EventSubscriber\ValidateCountry
    tags:
      - {name: event_subscriber,  priority: 20 }

  module_subscriber.path_processor:
    class: Drupal\country\PathProcessor\OutboundPathProcessor
    tags:
      - { name: path_processor_inbound, priority: 30 }
      - { name: path_processor_outbound, priority: 30 }
Comment: I didn't explain that very well - I was just explaining that Drupal's API does things one way and Symfony's another. You're dealing with Symfony's API here so the way you originally had it was correct, the problem must be elsewhere
Comment: ! my serivice.yml is correct, priority is correct
Answer: Both priorities are for different queues. If you set a priority for an event subscriber this is only for the specific event you subscribe to. In this example you subscribe to KernelEvents::REQUEST. Then you can only move up and down in the list of all other subscribers to this event.
You can find more information and a list of the D8 events here:
https://api.drupal.org/api/drupal/core!core.api.php/group/events/8.2.x
Path inbound/outbound processors are not even events. These are handled by the PathProcessor Manager and the priority set here is again only for the list of all other path processors.
Comment: ! can retrive a list with queque priority ?
Comment: I've checked, path processors are called dependent on the status of your cache and what module you've installed 5 or 10 times per request. So there is no single event you can target. But you can try to increase the priority for the KernelEvents:REQUEST subscriber until  you have the result you want.
Comment: There is a great debugging tool from Symfony, Web Profiler. In Drupal this is included in the Devel module.
Comment: ! when path_processor don't have a queue specific ?
Comment: ! 30000000 priority, same problem. It's not a prority problem


Delta distribution from the correlation/covariance function of two operators

Question: From Gardiner, it is known that if the correlation function of the operators $X(t)$ such that
$$
\left<X(t)X^{\dagger}(t^{\prime})\right>=\frac{\gamma}{2}e^{-\gamma|t-t^{\prime}|}
$$
It is further mentioned that the limit of $\gamma\rightarrow\infty$ corresponds to a delta function $\delta(t-t^{\prime})$, since
$$
\int_{-\infty}^{\infty}\frac{\gamma}{2}e^{-\gamma|t-t^{\prime}|}dt^{\prime} =1
$$
and
$$
\lim_{\gamma\longrightarrow\infty}\frac{\gamma}{2}e^{-\gamma|t-t^{\prime}|}dt^{\prime}=0
$$
for $t\neq t^{\prime}$. I simply do not see how these two conditions lead to the delta function $\delta(t-t^{\prime})$. What is going on here?
Edit:
I understand that the first condition is simply the normalization requirement for the delta function. However, I still do not see how the delta function arises. The manifestation of the delta function implies that $X(t)$ is a gaussian white noise
Answer: Let $\phi\in C^\infty_C$.  Then clearly we have
$$\int_{-\infty}^\infty \phi(t')\frac\gamma2 e^{-\gamma|t-t'|}\,dt'\overbrace{=}^{\gamma(t-t')\mapsto t'}\frac12 \int_{-\infty}^\infty \phi(t-t'/\gamma)e^{-|t'|}\,dt'$$
Using the Dominated Convergence Theorem, we find that
$$\lim_{\gamma\to\infty}\int_{-\infty}^\infty \phi(t')\frac\gamma2 e^{-\gamma|t-t'|}\,dt'=\phi(0)$$
which implies that in distribution
$$\lim_{\gamma\to\infty}\frac\gamma2 e^{-\gamma|t-t'|}=\delta(t-t')$$
as was to be shown!

Interestingly there is not anything special about the function $\gamma2 e^{-\gamma|t-t'|}$.  In fact, for any function $d( t)\in L^1$ such that $\int_{-\infty}^\infty d(t)\,dt=1$, then the Dominated Convergence Theorem guarantees that for any $\phi\in C_C^\infty$ and $\gamma>0$
$$\lim_{\gamma\to \infty}\int_{-\infty}^\infty \phi(t') \gamma d(\gamma(t-t'))\,dt'=\lim_{\gamma\to \infty}\int_{-\infty}^\infty \phi(t-t'/\gamma)d(t')\,dt'=\phi(t)$$
Comment: Thank you for your response. I am unfamiliar with the Dominated convergence theorem, or its application in this case at the very least, so I will look into it. I want to ask about the first line, where you did $\gamma(t-t^{\prime})\rightarrow t^{\prime}$. Here, you are only changing the variables right? Can you flesh out the steps in detail?
Comment: @kowalski You're welcome.  My Pleasure.  The DCT is a powerful theorem that provides sufficient conditions under which interchanging a limit and an integral is justifiable.  As far as the change of variables, it should be straightforward.
Comment: And feel free to up vote an answer as you see fit


How do I enable clean URLs with Nginx?

Question: I'm using Drupal 7.x. I have achieved to make it work without clean URLs.
Investigating, I have understood that I should create a vhost for each drupal site and enable clean URLs with the following code.
if (-e $ REQUEST_FILENAME) {
     rewrite ^ / (. *) $ / index.php? q = $ 1 last;
}

Alternatively, I could use this code.
location / {
         [... ]
         error_page 404 = @ drupal;
         [... ]
}

location @ drupal {
         rewrite ^ (. *) $ / index.php? q = $ 1 last;
}

However, I've also seen that without creating a vhost can enable clean URLs (like Apache).
I tried on both lines in my setup but I do not get a result.
When I enable clean URLs it always displays the word Nginx (The localhost).
What is the right way to enable clean URLs?
This is my configuration in /etc/nginx/sites-available/default.
server {
        listen   80; ## listen for ipv4; this line is default and implied
        listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /usr/share/nginx/www;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }

        location /doc/ {
                alias /usr/share/doc/;
                autoindex on;
                allow 127.0.0.1;
                deny all;
        }

        location /images {
                root /usr/share;
                autoindex off;
        }
        # Only for nginx-naxsi : process denied requests
        #location /RequestDenied {
                # For example, return an error code
                #return 418;
        #}

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/www;
        }

        #Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                try_files $uri =404;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                # With php5-cgi alone:
                #fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                fastcgi_pass unix:/tmp/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }
}

I have not created any vhost on my server; neither do I know how.
Comment: Have you seen/tried the following, from Drupal docs? http://drupal.org/node/976392
Comment: Have a look at https://github.com/perusio/drupal-with-nginx. It has all the configuration options you're likely to need to getting Drupal running on a Nginx server.
Comment: @geerlingguy Yes. This part of code I added to my default file in site-available and, when I enter to my site I get error 500.
Or i need to create a vhost?
Answer: I have next that work successfully:
  location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass unix:/tmp/php5-fpm.sock;
 }

Comment: i added `@rewrite` and `location @rewrite{}` in my file `/etc/nginx/sites-available/default` and restartn nginx but doesn't work for my. When i enable cleans url, display the localhost.
Comment: 2Eduardo: so you mean that http://site.com/index.php is working and open front page for you?
Comment: Yes. I can view the Front Page.. But no the others pages
Comment: hmm, can you pastebin your code again?
Comment: works fine for me

How do I enable clean URLs with Nginx?


Pivot chord but different scale. ( Ex. G; C and C; C ) is it possible to use them as a pivot chord to one another?

Question: Even though the scales are different,
G; C - lydian , C; C - Ionian .
Is it possible to use this as a pivot chord to modulate to one another ?
If it is possible, how ?
Comment: 'Even though the scales are different'. How. Doesn't G contain the same notes as C Lydian? It's the 'home' that is different.
Comment: @Tim What I'm asking is,
from G key, the C chord ( IV ) scale is Lydian.and from C Key, the C chord ( I ) scale is Ionian.
even though they are the same C chord, the scale are different from each other.

So is it possible to see this two as a pivot chord connection between G key and C key,and see the G key's C ( IV ) chord as C key's tonic ( I ) and allowed to proceed ?

and is this how pivot chord work ?
Comment: Plenty of information about this on Wikipedia: https://en.wikipedia.org/wiki/Modulation_(music)#Common-chord_modulation
Answer: Common chord modulation uses chords common to both keys. That just makes life simple, and sounds natural. Sometimes called diatonic pivot chord modulation. Thus, let's say we go from key G to key C.
The chords common to both G and C are Am and Em, as well as the obvious G and C. So using any as a pivot chord will facilitate modulation. The other chords available in those keys - Dm, F, Bm, D, Bo and F#o usually won't work as pivot keys. Except D, when moving from C to G, where it's going to work, as it's the dominant of the new key - why wouldn't it work - but, it's not part of the C inventory (although D7 contains C), so it'll sound quite abrupt - not what pivot chords are about.
So, basically, both G and C are pivot chords of each other.
Comment: Tim, in fact you *need* the D7 for a convincing modulation to G. The C is the pivot chord and the D7 confirms its purpose. Otherwise, there is no modulation, just a chord change or modal transition at best.


Is there a common language effect size for Cramer's V?

Question: There is a common language effect size (CLES) defined for Cohen's d (such as probability of superiority). Is there anything similar for Cramer's V or generally for r family (measure of association) effect size?
Comment: Cramer's v is for categorical variables. What does superiority means in that context?
Comment: The probability of superiority of E over C is the probability that a randomly chosen value from the E distribution is greater than a randomly chosen value from C. It is kind of  jargon-free version of Cohen's d. I don't know yet what CLES for Cramer's V would look like.
Answer: In their review of common language effect sizes (CLES), Mastrich & Hernandez (2021) do mention counterparts for a couple of r family effect sizes (see the table at the end of this answer), but they do not mention a CLES counterpart to Cramér's V.
However, for 2X2 contingency tables that examine the frequency of success versus failure of a treatment and control groups, they mention the binomial effect size display (BESD) as a CLES analogous to the $\phi$ coefficient (phi). The absolute value of the $\phi$ coefficient happens to equal Cramér's V for 2X2 contingency tables.
So in theory, in this specific situation, you could use the BESD as a common language effect size for Cramér's V – with all the important caveats related to using the BESD in general, at the risk otherwise to make an erroneous interpretation of the table, e.g. see the paper by Randolph & Edmondson previously linked, in particular pp. 4-5. For 2X2 tables, definitely check if it's a better idea to use odds ratio, risk ratio, and risk difference, as effect size measures.
In addition, Cramér's V does not have a sign, so from a practical point of view you might also have to take extra precautions to convert it correctly to the BESD – be careful not to mix up the treatment and the control group in your calculations.
For other situations than 2X2 treatment-control contingency tables, the absence of a CLES analogous to Cramér's V (or other effect size based on the chi-square statistic, like Cohen's $\omega$ or Tschuprow's $T$) may come from the fact that two very different contingency tables can have the same chi-square-based effect size. Given that, translating an effect size like Cramér's V directly to a CLES is probably not a straightforward thing to do - assuming this is even possible.
In addition, an effect size like Cramér's V, while it may be useful in the research process, is not necessarily what you want to communicate to an audience unfamiliar with statistics. For instance, the interesting thing about your table may be specific cells deviating a lot from independence; or the fact that a specific row or column is very different from others. Cramér's V won't inform you about all of this, so a CLES based on Cramér's V won't either.
Here is a related question you may find interesting: interpreting Cramer's V results.

In case you don't have access to the Mastrich & Hernandez's paper, here is a list of the CLES they identified along their "regular" effect size counterpart, and the original references:

"regular" effect size
CLES counterpart
Reference

Cohen's d (T-Test)
$CL_d$
https://doi.org/10.1037/0033-2909.111.2.361

Post-hoc Cohen's d (One-way ANOVA)
$CL_{d-All}$
see previous

Mann-Whitney U
A
https://doi.org/10.1037/1082-989x.7.4.485 ;  https://doi.org/10.2466/11.IT.3.1 ;  https://doi.org/10.1037/1082-989X.13.1.19

$\phi$ (2x2 contingency tables)
BESD
https://doi.org/10.1037/0022-06220.127.116.11

Pearson's $r$
$CL_r$
https://doi.org/10.1037/0033-2909.116.3.509

Kendall's $\tau$
$B_p$
https://doi.org/10.3758/s13428-018-1089-5

Multiple regression coefficient (no interaction)
$CL_{\beta j}$
https://doi.org/10.1037/apl0000296

Multiple regression coefficient (with interactions)
$CL_{\beta}$
see previous

Mahalanobis Distance D
$CL_D$
https://doi.org/10.1177/2168479014542603

Odds ratio
Number needed to treat
https://doi.org/10.1016/S0895-4356(01)00510-8

Note that one of the two authors offer an online tool to convert these "regular" effect sizes to their CLES counterparts: https://ivanhernandez.com/software/clescalculator.html
References
Mastrich, Z., & Hernandez, I. (2021). Results everyone can understand: A review of common language effect size indicators to bridge the research-practice gap. Health Psychology, 40(10), 727–736. https://doi.org/10.1037/hea0001112
Randolph, Justus J. and Edmondson, R. Shawn (2005) "Using the Binomial Effect Size Display (BESD) to Present the Magnitude of Effect Sizes to the Evaluation Audience," Practical Assessment, Research, and Evaluation: Vol. 10, Article 14.
DOI: https://doi.org/10.7275/zqwr-mx46


How to remove an ASPNET Runtime?

Question: I have an ASPNET Core Runtime that needs removed, but the means I've discovered doesn't seem to be working right.  This is Version 2.1.17, which is old and needs gone.  It is on a Windows 10 domain-joined machine.
Searching around I found that there's a dotnet uninstallation tool, but it didn't list that Runtime as an option.  Further digging around seemed to indicate that if I removed the correct SDK I should be able to take the Runtime out with it.
The command used here was dotnet-core-uninstall remove --sdk 2.1.513
This took out the 2.1.513 SDK alright, but 2.1.17 still shows up in the list of Runtimes when I invoke dotnet --list-runtimes, but isn't listed as something that can be uninstalled anymore if I use dotnet-core-uninstall list instead (which just has a blank space where Runtimes might otherwise be).
Is there another way to yank this out?  Folder is owned by SYSTEM so I would have to mess with permissions, but would that cause other issues?  It doesn't appear to be used and the associated SDK is gone, so it doesn't serve any more use (and 2.1.25, a more recent replacement, is on the system).
Answer: Windows 10 - Try this:
Go to Setting ==> Apps & Features ==> Search Then Select Your Verstion ==> Select Uninstall
See Link Below:
https://docs.microsoft.com/en-us/dotnet/core/install/remove-runtime-sdk-versions?pivots=os-windows

How to remove an ASPNET Runtime?


Finding average number of rolls for recursive rolls on success

Question: If there is more appropriate terminology to better phrase my question, please edit.
Imagine I have a 3 sided die: two faces marked 0, one face marked 2
Whenever a two is rolled, two more rolls are to occur. How do I determine the average number of rolls that will occur?
I tried figuring this out based on an explanation of exploding dice (http://axiscity.hexamon.net/users/isomage/rpgmath/explode/) but I'm not sure I'm even headed in the right direction.
p(number of rolls)

p(1) = 1/3
p(3) = 1/3 * 2/3 * 2/3
p(5) = 1/3 * 1/3 * 2/3 * 2/3 * 2/3
p(7) = 1/3 * 1/3 * 1/3 * 2/3 * 2/3 * 2/3 * 2/3
p(n) = n+1/3^n

Solve for the sum of p(n) ???
Are those probabilities correct or do i have to include the alternate ordering (ex: p(5) = 1/3 * 2/3 * 1/3 * 2/3 * 2/3)
what about a 3 sided die: 0,1,2 where 1 = +1 roll and 2 = +2 rolls?
what about a 20 sided die: 15 zero faces, 3 two faces, 1 three face, and 1 five face?
Curious why in the heck I care? In an effort to learn python i thought it'd be fun to generate a random dungeon. Now i'm curious about the probabilities of the random (or should I say psuedo-random) generation.
I tried digesting the question/answers linked below ... snow crash! If you do help me, please, please, feed me via spoon. I am a statistics baby.
How to easily determine the results distribution for multiple dice?
Help with probabilities on a game I am making
Now i'm going to read http://www.diku.dk/hjemmesider/ansatte/torbenm/Troll/RPGdice.pdf while I wait for enlightenment
Thanks in advance for said enlightenment.
Comment: You could take a look at the first example of the wikipedia article: http://en.wikipedia.org/wiki/Geometric_series and see if it helps?  The expected number of rolls is your $\sum_i i p(i)$
Comment: This is not a simple problem because if you start with a 2, your next 2 rolls can be 2, 2, and then you're looking at the next *4* rolls, and so on. That, I think makes it not just a simple geometric series problem, but a variant of a [branching process](https://en.wikipedia.org/wiki/Branching_process), and I think it's probably best solved with [generating functions](https://en.wikipedia.org/wiki/Probability-generating_function). See, for example, sec 3.7 [here](http://www.am.qub.ac.uk/users/g.gribakin/sor/Chap3.pdf), but you can find a lot more on this approach.
Answer: The solution method is mentioned in the title: recursion.
The expected number of rolls $e$ is the sum of:

$1$ for the first roll and
The expected number of subsequent rolls if the first roll is a 2.

In the latter case, the expected number of subsequent rolls is $2e$ because the whole process is started over twice (independently).  Because the latter case occurs with probability $1/3$, we obtain the recursive relationship
$$e = 1 + (1/3)\times (2e)$$
whose solution is $e=3$.
For the generalizations of this question, similar recursive equations will be obtained (although they might be a little more complicated) and are almost as easy to solve.

For the sceptical--and everybody should be when it comes to probability questions :-)--here's R code to simulate the experiment.
roll <- function() 1 + if (runif(1) < 1/3) roll() + roll() else 0

system.time(x <- replicate(10^6, roll())) # Do a million experiments
average <- sum(x) / length(x)
variance <- sum(x^2) / length(x) - average^2
se <- sqrt(variance / length(x))
c(average-3*se, average, average+3*se)

Sample output:
   user  system elapsed
  14.82    0.04   14.86

[1] 2.994785 3.009526 3.024267

The simulation average is $3.01$, which is reasonably close to $3$.  (I use three standard errors to assess the precision because the distribution is highly skewed: draw a histogram as hist(x) to see.)
Comment: I tried to apply this method on my second scenario (1d3, sides 0,1,2) but I must be setting it up incorrectly. `e = 1 + 1/3 * 1e + 1/3 * 2e` which reduces to `e = 1 + e` which is putting me in jeopardy of breaking some mathematical laws. Anyone fix my blunder?
Comment: You're actually getting the right answer! In your second scenario the expectation is infinite. Think about it: on average, each throw of the die is going to lead to (0 + 1 + 2)/3 = 1 more throws. You shouldn't expect this always to end.  (It's a better model for population growth than it is for game play.)
Comment: Thanks I see it now. It's actually more of a population I'm trying to model. Population of rooms and passages of dungeons. :) On a side note are you really only 13?
Answer: With @whuber's help, here is a slight variation on the conditioning argument. Take the die with 3 sides of 0, 0, and 2 and let $R$ be the number of rolls. With probability $2 \over 3$ the process ends in 1 step with a roll of 0. With probability $1 \over 3$, the process will have $1 + 2E[R]$ steps. So $$E[R]=1 \left({2 \over 3} \right)+ \left[1+2E[R] \right]\left({1 \over 3} \right). $$ Solving for $E[R]$ we get $$E[R] = 3.$$
Comment: +1. But you sound a little uncertain :-).
Comment: I am, as confirmed by your answer!


SQL Unmatched Delete

Question: Say I have two tables, records and recordsclean. Now both of these tables have 15 columns of information. I want to compare them using just one unique column and identify the unmatched results. Once I find those unmatched results I want to remove them from one table.
SELECT  email
FROM    records
WHERE   id NOT IN
(
       SELECT  email
       FROM    recordsclean
);

Now I'm using email in this instance but likely I'm going to use something more unique like registration numbers. I'm just testing it with email addresses. So this produces a list of emails found in records that are not found in recordsclean. The table records is going to hold historical data that I plan to keep indefinitely where as recordsclean is going to be a fresh set of information. I want to compare the full version of records to the new recordsclean and then identify / remove anything that matches from recordsclean.

Data is added to records.
New data is added to recordsclean.
SQL command runs and identifies matching records in both.
SQL command runs and removes any matching records from recordsclean only.
Comment: What's your question? You have lots of "I want X" statements, but nowhere have you said what problem you're having.
Comment: Why are you comparing `id` to `email` from the other table? Shouldn't it be `WHERE email NOT IN`?
Comment: Are you asking how you can compare more than one column at a time, not just `email`?
Answer: If you want to compare multiple columns and find all the rows that don't match, use a LEFT JOIN pattern rather than NOT IN.
SELECT rc.*
FROM recordsclean AS rc
LEFT JOIN records AS r
    ON rc.col1 = r.col1 AND rc.col2 = r.col2 AND rc.col3 = r.col3 ...
WHERE r.id IS NULL

To delete them, just change it to a DELETE query.
DELETE rc
FROM recordsclean AS rc
LEFT JOIN records AS r
    ON rc.col1 = r.col1 AND rc.col2 = r.col2 AND rc.col3 = r.col3 ...
WHERE r.id IS NULL

SQL Unmatched Delete


How to add custom CSS to the highcharts.js anchor  tags with links

Question: I am attempting to an  tag on the names of my categories to re-direct to a different page if the title is clicked on. At the moment my css class names aren't applying any styling. When inspecting element I see that the title I wrapped around in the  tag has a class of "highcharts-anchor" I'm attempting to either override highcharts-anchor, or add custom css to it to display the look that I would like. I've attempted to add a color: red to highcharts-anchor but it has no effect to my graph.
Also in my second title, the anchor tag is only applied to the first line of text, I am attempting to have the entire 3 rows of text in "2. Most Sold Online Stores Using Facebook Advertisements" to be clickable, at the moment "Most Sold Online Stores Using" is the only text that is linking to another page.
Here is a code snippet of what I am attempting to do:
      xAxis: {
        categories: [' 1. Highest Sales. ', '2.  Most Sold Online Stores Using Facebook Advertisements '],
        labels: {
          align: 'left',
          x: -180,
        }
      },

.anchor-text {
  color: red;
  font-size: 20px;
  font-weight: bold;
}

.highcharts-anchor {
  color: red;
}

Here is a link to my jsfiddle https://jsfiddle.net/bs1o2yth/10/
Answer: You can simply use formatter to color and add anchor tags to your labels.
formatter function return the value of labels and other data. Just check which pos you want to color with and add your relevant anchor tag. pos will from 0 to 4 in your case as you have five labels only.
I have recreated your example and added anchor tags to all of the labels which you can click on and visit the href link.
Run snippet below to see it working.

Highcharts.chart('container', {

  chart: {
    type: 'bar',
    marginLeft: 200
  },

  xAxis: {
    categories: ['1. Highest Sales.', '2. Sed pretium aliquet dapibus.', '3. Donec mollis sit amet elit.', '4. Donec mollis sit amet elit.', '5. Donec mollis sit amet elit.'],
    labels: {
      align: 'left',
      x: -180,
      formatter: function() {
        if (this.pos == 0) {
          return '' + this.value + '';
        } else if (this.pos == 1) {
          return '' + this.value + '';
        } else if (this.pos == 2) {
          return '' + this.value + '';
        } else if (this.pos == 3) {
          return '' + this.value + '';
        } else if (this.pos == 4) {
          return '' + this.value + '';
        } else {
          return this.value
        }
      }
    }
  },

  plotOptions: {
    series: {
      dataLabels: {
        enabled: true,
        format: '{y} %'
      }
    }
  },

  series: [{
    data: [{
      y: 5,
      color: "#00FF00"
    }, {
      y: 10,
      color: "#FF00FF"
    }, {
      y: 7,
      color: "blue"
    }, {
      y: 3,
      color: "yellow"
    }, {
      y: 7,
      color: "blue"
    }]
  }]

});


Como salvar HTML em Mysql

Question: Estou com um impasse em relação a armazenar um HTML no BD.
Estou utilizando a  propriedade em php: htmlentities($_POST['codhtml']) para realizar esta operação. Porém ao salvar um código como:
Leve a alegria do Natal para sua casa !

No banco fica armazenado:
<span class="frase-aditivo mover" id="adt6-enable" style="transform: translate3d(-2px, 202px, 0px); cursor: move; touch-action: none; -webkit-user-select: none; z-index: 1004; border: 3px dashed red; font-size: 112px; font-family:

Ou seja, por algum motivo o código  é perdido sempre que há uma URL ou apos "font-family:".
Qual a melhor maneira de realizar esse salvamento ?
PS. Estou utilizando LongText.
Obrigado =D
/* CONTINUAÇão CODIGO*/
$("#mt_finalizar").click(function(event) {
      var codhtml = 'Leve a alegria do Natal para sua casa ! ';

      $.ajax({

            type      : 'post',

                url       : 'salvarDados.php',

                data      : 'codhtml='+codhtml
                            +'&motivoid=2'
                            +'&formatoid=2'
                            +'&motivonome=Nome',
                dataType  : 'html',

                success : function(txt){
                     alert("Sucesso,");
                },
                error: function(result) {
                    alert("Erro ao Salvar");
                }
      });

$resultado = $this->conexao->exec("INSERT INTO tabela (col1,col2,col3,col4,col5,col_codhtml,col6) VALUES(2,2,2,2,2,'$codhtml','Nome')");

Comment: @MayronCeccon péssimo hábito. Ocupa muito mais espaço, e não tem vantagem nenhuma. Além disso é um processo de codificação e um de decodificação a mais totalmente desnecessário. Fica a sugestão de aprender melhor a usar o DB e os recursos da linguagem para melhorar seus aplicativos.
Comment: Eu utilizo o base64_encode e o base64_decode quando salvo HTML no banco.
Comment: Cara, sei que o tipo blob salva arquivo e tals, acho válido tu testar com ele.
Comment: Tentei utilizar este base_64 porém a String é interrompida da mesma maneira. Vou tentar utilizar o tipo blob.
Comment: @user48796 seu problema não deve estar no DB, provavelmente está no jeito que está fazendo o insert. Mesmo que funcionasse, base64 só iria disfarçar o problema. Só que se não postar o código na pergunta, não vai dar certo. Provavelmente sua pergunta já foi resolvida neste post: http://pt.stackoverflow.com/questions/21318/70
Comment: @Bacco Obrigado pelo apoio ! Acredito que o erro esta na hora que passo por paramentro o HTML, quando ele encontra o '&' ele interpreta como um novo parametro... Teria uma solução para isso ?
Answer: Na parte do JS troque isso:
data      : 'codhtml='+codhtml

por isso:
data      : 'codhtml='+encodeURIComponent(codhtml)

O encodeURIComponent serve para "escapar" os caracteres especiais que normalmente são usados em valores de URL ou POST.
Na parte do PDO troque isso:
$resultado = $this->conexao->exec("INSERT INTO tabela
(col1,col2,col3,col4,col5,col_codhtml,col6)
VALUES(2,2,2,2,2,'$codhtml','Nome')");

por isso:
$resultado = $this->conexao->exec('INSERT INTO tabela
(col1,col2,col3,col4,col5,col_codhtml,col6)
VALUES(2,2,2,2,2,'.$this->conexao->quote($codhtml).',"Nome")');

(quebrei as linhas só pra facilitar a leitura)
O quote troca os caracteres que podem conflitar com a Query, evitando que aspas e caracteres de escape corrompam a string. Ele também acrescenta aspas nas "pontas" da string
O ideal mesmo seria usar prepared statements. Veja exemplos nessa questão:

Como prevenir injeção de código SQL no meu código PHP?
Comment: Olá amigo, não conhecia essa propriedade no Jquery. Funcionou perfeitamente. Obrigado !
Comment: Que bom que resolveu. Só um detalhe, o encodeURIComponent não é do jQuery, é do Javascript mesmo. Mesmo se não usar jQuery, ele funciona.

Como salvar HTML em Mysql


JavaFX Canvas Rendering Performance

Question: I work on a JavaFX application and have to draw a lot (4000) of arc's.
I'm using the JavaFX Canvas method strokeArc of the graphic context.
The application performs very weak, but not the calls of the methods strokeArc, I think the delay occurs later, maybe at the rendering.
The results is, that the application does take a delay about 5 seconds to show the arc's on the gui.
Is there a faster way to draw the arc's in JavaFX?
Answer: No, there isn't. Canvas is the fastest.
You didn't provide a MCVE. I just tried a simple application. Works pretty fast, 4000 arcs drawn in 6ms. The application window shows up immediately. Here's the code:
<code>import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.stage.Stage;

public class ArcTest extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        Group root = new Group();
        Canvas canvas = new Canvas(300, 250);

        GraphicsContext gc = canvas.getGraphicsContext2D();

        root.getChildren().add(canvas);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();

        drawShapes(gc);

    }

    private void drawShapes(GraphicsContext gc) {

        long time = System.currentTimeMillis();

        gc.setFill(Color.GREEN);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(5);
        for( int i=0; i < 4000; i++) {
            gc.strokeArc(10, 160, 30, 30, 45, 240, ArcType.OPEN);
        }

        System.out.println( System.currentTimeMillis() - time);
    }
}
</code>
Unless you provide some code with more information (BlendMode, etc) it's hard to help you.
Comment: Maybe the built-in JavaFX Canvas Graphics Performace Optimizer realizes that drawing 4000 times an identical arc can be replaced by a single one here :-)
Comment: @jojo2100: you should phrase your question correctly then. 4000 and 70000 is a HUGE difference. The arcs are written into a GrowableDataBuffer and painted later. That's why you have that delay.
Comment: Thank you. I've tried your source code and it's fast for 4000 arcs.
The problem is, that I was wrong with the number of arcs. I draw not only 4000 arcs, I have to draw 70,000 arcs. And for this, your source code is also slow. I think there is no better solution?
Comment: Please try your test program with 70,000 arcs. You will see, the code is finished after 25 milliseconds, but the Java rendering has a very long delay.
Comment: @mipa yesterday: no, there's no optimizer like that
Comment: @Roland: I know, it is my fault. I have not realized this huge number of arcs before. So you mean, that the memory allocation of this buffer takes some time?
Is there an possibility to get my application responsive, like with an task on a seperate thread?
Comment: @jojo2100: Not the memory allocation, the drawing. You are facing the same problem that I have with [the particles](http://stackoverflow.com/questions/31613669/performance-for-particle-system). I doubt that you'll get it more responsive. I tried by splitting my app into several canvases, doing it parallel and then merging them. Didn't give any performance improvement.
Answer: JavaFX Canvas implements immediate mode graphics. That's an engine where you tell it everything it will render every frame. Usually there's an object like GraphicsContext that represents a state machine that you modify before individual draw calls to get whatever style of drawing you want.
You may find that immediate mode graphics engines (like most platform's Canvas implementations) are utterly convenient but fairly slow at large scales.
When you want to draw a LOT of the same type of thing you need to start using the graphics card more directly. While the JavaFX Canvas does leverage graphics cards it doesn't optimize for what you're trying to do. Possibly the simplest approach to this are shaders. Shaders are essentially little rendering programs that OpenGL can run.
If you need to use JavaFX there are a few ways to use OpenGL with JavaFX. I'll offer a starting point here.
This is OpenGLFX, it will give you probably the simplest entry point for getting a shader running in your JavaFX application.
https://github.com/husker-dev/openglfx
I found that it wasn't especially elegant in the past but has streamlined a lot in the last year.
There are a lot of resources out there for learning OpenGL. For your purposes you should go through the first few tutorial here.
https://learnopengl.com/
Once you are ready to draw your arcs with OpenGL you probably will want to create a VAO (a common OpenGL arrayed data structure) with your arc data, upload that data to the gfx card, and render a vertex shader and fragment shader. OpenGLFX will take care of putting the result on the screen from the GFX card for you.
I imagine there are already plenty of algorithms and methodologies out there for rendering arcs simply or finely.

Of course if your arcs never need to change you could also just render it once with JavaFX canvas then use getSnapshot on the canvas to cache a picture of it and render that instead.

JavaFX Canvas Rendering Performance


Recording data using Jack Audio Kit from Python

Question: i am new to jack audio connection kit and don't know work around. i am able to run Jack PortAudio server.
my expectation is to record 60 second audio and save recorded Audio into .wav file.
i am using Python27 and JACK-Client==0.4.6.
Below is the code. please somebody edit this to record and save as .wav file.
import jack
import numpy

client = jack.Client('MyGreatClient')

client.inports.register('input_1')
client.outports.register('output_1')

in2 = client.inports.register('input_2')
out2 = client.outports.register('output_2')

client.midi_inports.register('midi_in')
client.midi_outports.register('midi_out')

client.activate()

client.connect('system:capture_1', 'MyGreatClient:input_1')
client.connect('MyGreatClient:output_1', 'system:playback_1')

client.connect(out2, 'system:playback_2')
in2.connect('system:capture_2')

Thank You.
Answer: Not that is relevant to your problem (yet), but why are you using outdated versions of Python and the package?
Then you could look into the play_file example to see how the basic interaction with files and JACK works while using the API. It is not trivial unfortunately.
However, recording and writing is a very valid application as well, but there is no basic example yet. I believe the block buffering and file interaction should happen in a similar fashion as in the play example. Therefore, it would be awesome to figure out how to do that with soundfile and create an example in the code base. The maintainer and other users (like myself) should hopefully be able to assist you with that. :)


SFTP to EC2 Windows Instance

Question: So i've setup a windows instance, but can't seem to FTP into it.  After much research, i've discovered SFTP is the way forward.
I've setup my security group, adding the following rule:
 SSH  tcp  22  22  0.0.0.0/0
Using the public DNS name supplied in the console, i try to SFTP in using Filezilla & Cyberduck, but they just time out.
I know the next step is sorting out the key pairs, but i doubt that'll do me any good if my server isn't even accepting connections.
Any idea what i've missed?
EDIT:
Looking at the Filezilla logs, its looks like the server isn't responding to the connection requests...
<code>12:51:29    Status: Connecting to ec2-122-248-248-178.ap-southeast-1.compute.amazonaws.com...
12:51:29    Response:   fzSftp started
12:51:29    Command:    keyfile "D:\Users\berling\Lacie Fuj Sync\Freelancing\AWS_Public_Key.ppk"
12:51:29    Command:    open "email@example.com" 22
12:51:49    Error:  Connection timed out
12:51:49    Error:  Could not connect to server
</code>
Do i need to install an SFTP/SSH server on the server? I was under the impression it was already setup for Amazon servers for some reason... am i wrong about that?
Comment: Seems you have configured ppk properly, but not sure about username and other parameters, I'm following steps mentioned in this video and successfully connected using filezilla: http://y2u.be/e9BDvg42-JI
Answer: The rule you have set up - SSH tcp 22 22 0.0.0.0/0 - where is that? Your firewall, or at the EC2 end? And why 0.0.0.0? I would recommend using real IP addresses.
Check why the connection is timing out - is SFTP getting past your firewall? Is it getting blocked at the EC2 end - firewall or network logs will be your friend here.
Have you confirmed it is timing out before starting the handshake? Check SSH logs.
Do you have an SFTP server running and configured correctly? Some require all configs to be set before they are happy - your comment that you haven't yet sorted key pairs makes me wonder if this one only accepts certificate auth.
Check those and see how you do.
Comment: As for setting up SFTP on the server, i was under the impression that the Amazon AMIs had SFTP ready to go... or am i wrong about that?  If i am, any recommendations on a solid and free/cheap SFTP server i can install?
Comment: hey Rory,

Thanks for the info... i setup with 0.0.0.0 as i ftp from dynamic IPs.. i'll lock it down to springloops IP once its all working and i can deploy code from there every time.  That rule is on the EC2 end, in the security groups assigned to the VM.  I dont have a local firewall, so dont think the issue is local.

I'll check all logs I can find and see if they give me any clues.
Comment: If your using Linux AMI (Amazon AMI or Ubuntu) you can directly sftp since it's running SSH server. But if you're running Windows instance, I think you need to install SSH/SFTP server first.
Comment: I reckon you're probably right Rodney.  I think i'll just open up port 21 and use FTP for now.. i'm still just evaluating EC2, dont want to waste too much time on unnecessary activities.
Comment: @Jeeby have you been able to resolve the issue? I have the same one now :/
Comment: @OndrejTokar Nope I never resolved it. I was just trialling EC2, and gave up soon after I hit this roadblock.
Comment: @Jeeby, thank you for your answer. That is a shame. Though I think to make it work you need to install a Git, setup SSH keys, upload the public one onto AWS and then do some configuration in registry and then it will work. (All that is in AWS tutorial...) I expected it would be simpler.
Answer: Install WinSSHD on your EC2 instance.  It provides RDP, SFTP, Console access - all over port 22.
Install Tunnelier on your client.
Answer: I haven't tried this particular package, but Cygwin, and Services for Unix provide OpenSSH version.
Copssh claims to install openssh, and allow migration/configuration of users:
http://sourceforge.net/projects/sereds/files/Copssh/4.0.4/

SFTP to EC2 Windows Instance


create ajax autocomplete field like stackoverflow

Question: How to create ajax autocomplete field,like Tags field in Stackoverflow that user can remove tag with remove icon after insert tags on fields.(with Mootools or jQuery)
Comment: what, like this: http://mootools.net/forge/p/mootagify
Answer: You could use the Meio.Autocomplete Class to achieve this behaviour.
I am using it for exact the task you were asking for. Have a look at this page for details on how to use it.


Strict standards: Redefining already defined constructor for class Object in path\cake\libs\object.php on line 54

Question: I am trying to configure MS-MSQL database on cakephp (Not mysql).
My Wampserver is 2.2e-php5.4.3-httpd2.2.22-mysql5.5.24-32b on my laptop (which is windows x64-bit.
I already invited these two dlls to run sql server
extension=php_sqlsrv_54_ts.dll
extension=php_pdo_sqlsrv_54_ts.dll
I've got these two errors in running cakephp 1.3
Strict standards: Redefining already defined constructor for class Object in C:\wamp\www\project\cake\libs\object.php on line 54

Strict standards: Non-static method Configure::getInstance() should not be called statically in C:\wamp\www\project\cake\bootstrap.php on line 38

I also install WampServer2.1e-x32 it didn't work :(
Any help plz
Answer: you are using newer php version. in php 5.4, E_STRICT is part of E_ALL
in cake 1.3, open file /cake/bootstrap.php and change the error_reporting like this

error_reporting(E_ALL & ~E_STRICT & ~E_DEPRECATED);
Comment: Hiding errors is not a feasible solution. According to me it is more important to resolve fatal/warnings/notice errors first if it is possible. Thanks
Comment: Isn't there a solution to change the cake-sources, so that error is fixed instead of ignoring it? **How would you fix object.php on line 54 so it will not throw the strict warning?**
Comment: Yes Arun, resolve all errors is number one priority but there is some case when you're in the middle of deadline and you must run the application ASAP for your company/client, and that apps built by someone you don't know. This must be temporary fix. Thanks for your suggestion
Comment: make sure your display_error is enabled in php.ini or by using ini_set('display_errors', 1);
Comment: after using this `error_reporting(E_ALL & ~E_STRICT & ~E_DEPRECATED);` it gives me a blank page... i am using xampp v3.1.x.x with PHP Version 5.4.7 and i am working with cakephp 1.2
Answer: Your cakephp version is old, and has problems with the latest version of PHP.
You could try updating your CakePhp version. Seems that your are using the 1.3 version, so update to the latest one.
You could find it
https://github.com/cakephp/cakephp/archives/1.3
Only replacing the cake/ folder with the new one, you fix this problem.
If you are new to CakePHP, then it is better to learn the Latest framework 2.2.1. You will be easily installed this framework with your Wamp.
Comment: This should have been marked as the correct answer. Had the same issue after updating to php 5.4. Updating cake from 1.3.12 to 1.3.17 fixed the issue. Keeping your cake up to date should be a best practice
Comment: Thank you for you answer I will try that. But this framework(that is cakephp 1.3) is an existing framework and it is working properly with WampServer2.1e-x32 .... What I impose is **it can't connect to SQL SERVER database** properly
Comment: At the below of the error you are getting, there might be a link `context`. Click on it and check. Remember you provided the correct database connection string in `$default` or otherwise you will have to use `$useDbConfig`.
Comment: I tried the newest version of cakephp 2.2.1. it gives me database error: `Notice (8): Undefined index: datasource [CORE\Cake\Model\ConnectionManager.php, line 258]`
`Cake is NOT able to connect to the database.`

`Datasource class could not be found.`
Comment: Hi Arun! There is no link for context.
Comment: The cakephp/archives/1.3 is gone, but you could get older versions you clone the cakePHP Project on github:

https://github.com/cakephp/cakephp/

and then [checkout the right revision for your version.](http://www.botsko.net/blog/2010/01/08/download-old-cakephp-versions/)
Answer: Go into your Config/core.php and look for the error handler configuration:
Configure::write('Error', array(
    'handler' => 'ErrorHandler::handleError',
    'level' => E_ALL & ~E_DEPRECATED,
    'trace' => true
));

and replace 'level' with this:
...
'level' => E_ALL & ~E_STRICT & ~E_DEPRECATED,
...

Answer: The solution is to update the cake 1.3 version to the last release currently the 1.3.21 .
click here to download the last release :
https://github.com/cakephp/cakephp/tags


How to get the HTTP response headers in Rebol3?

Question: The read and write commands in Rebol, when passed a URL! parameter, can get you either a binary response or an error.  So in the "one-off" style of doing a GET or a POST there is nowhere to get the response headers from.
result: read http://www.rebol.com

In this post about how to do it in Rebol2, it suggests you have to open a port! and get it from the port's local/headers field:
Rebol - HTTP response headers
This works in Rebol2, for instance
hp: open http://www.rebol.com
result: read hp
probe hp/locals/headers/Content-Encoding

But in Rebol3, when I open a port and try this the locals field of the port is empty.  How to achieve the same behavior in Rebol3?
Answer: One (long-winded) solution:
target: http://www.rebol.com/
port: make port! target
; make alterations to port/spec here, e.g.
; port/spec/method -- HTTP method
; port/spec/headers -- [set-word value] block of headers
; port/spec/content -- content
port/awake: func [event][
    switch event/type [
        connect [read event/port false]
        done [true]
    ]
]
open port
response: query port
wait [port 1]
close port
probe response

Answer: Is this what you're looking for?
>> hp: open http://www.rebol.com/
>> to string! read hp
== {<!doctype html>

<meta name="generator" content="REBOL WIP Wiki"/>
<meta name="date" content="16-Feb-2014/15:58:59-8:00"/>
<meta name="rebol-version" content="188.8.131.52.2"/>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta name="Description" content="REBOL: a lightweight computer language with ad
vanced semantics. ...

>> query hp
== make object! [
    name: %/
    size: 7118
    date: none
    type: 'file
    response-line: "HTTP/1.1 200 OK"
    response-parsed: 'ok
    headers: make object! [
        Content-Length: 7118
        Transfer-Encoding: none
        Last-Modified: "Sun, 16 Feb 2014 23:58:59 GMT"
        Date: "Sat, 05 Apr 2014 08:19:34 GMT"
        Server: "Apache"
        Accept-Ranges: "bytes"
        Connection: "close"
        Content-Type: "text/html"
    ]
]


.NET Core console app fails from task scheduler with 0xC0000005

Question: I have written a simple .NET Core console app (which writes some log files, hits a database and sends some emails). Triggering the task by double-clicking on the .exe within Windows works fine.
However when attempting to trigger the task through Task Scheduler it immediately fails with the code 0xC0000005. This failure happens when actually triggered on it's schedule or by right-clicking the task within the Task Scheduler app and clicking 'Run'. The first thing the app attempts to do is write something to a log file, which never happens.
The same server has a bunch of other .NET console apps (not .NET core) that are configured with exactly the same permissions and user accounts and they work fine.
In the event log there's a record that reads:

Faulting application name: StorePlay.ClientEmailer.exe, version:
  184.108.40.2069, time stamp: 0x58224b03 Faulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000 Exception code: 0xc0000005
  Fault offset: 0x00007ffaef1d8955 Faulting process id: 0xe0c Faulting
  application start time: 0x01d301e534cdde90 Faulting application path:
  C:\storePlay\Tasks\Client Emailer\StorePlay.ClientEmailer.exe Faulting
  module path: unknown Report Id: 1bc8be44-744c-452e-a945-997d64d1d87b
  Faulting package full name:  Faulting package-relative application ID:

This is all on a machine running Windows Server 2016
Comment: Did you ever figure out the answer to this question, I am having the same problem and I tried to use my own credentials for the scheduled task
Comment: First thing to check is windows logs, do you have an exception with stacktrace. (The stacktrace part here is important)
If it is your own application, try to handle unhandledexceptions.
Answer: I searched and tried all kinds of solutions and the one that worked for me was to set the Start In option. Normally someone could have the full path in the Program/Script text box after browsing, which is how most tasks I have seen run. It appears that .Net Core console app needs to run with the optional path so it can find the appsettings.json if you are using one.
https://stackoverflow.com/questions/43595119/schedule-a-net-core-console-application-on-windows-using-task-scheduler
Comment: I joined this community only to upvote that answer. 4h searching
Comment: same here, just one thing to specify, in Program/scipt textbox, just keep the name of the program not the whole path,  when I was trying, I just copied that path and pasted in the "Start" textbox and it wasn't working, may be helpful for some other dumb like me
Comment: You saved my life. I was trying to use the task scheduler to run an asp.net core app at system startup but could not make it run. After setting the root folder of the app to the "Start in" text box as you mentioned above, it worked!
Comment: thanks @breadtruck! This is so unusual than regular apps. saved me some time.
Answer: It could be that the error is because of permissions. Usually the taskscheduler runs a task with the system account and when you run the exe in usual way on windows, then you run it with your credentials.
You should be able to set your credentials on the task it self under task scheduler or create a user that has the permissions that it needs.
Edit: Did not see the age of the question until after posting an answer, but if it helps anyone else, then great :)
Comment: Hi Setorica and welcome to ServerFault. Yes, around here we're in fact more concerned with general answers, good for everyone experiencing a similar problem.
Comment: how to set permissions in task scheduler? where to find that setting? I created an administrator user and set for my scheduler but still get same error as above in question.
Comment: When you create a task in the task scheduler, then in the General tab, there should be settings for Security Options, where you can change which user account should run this task. Also you can set if it should be run as elevated/admin by checking the 'Run with highest privileges' checkbox.
Answer:
Above setting in Actions and General tab of Task Scheduler worked for .NET Core 2.1 Console App, Windows Server 2019.


Callkit example or sample for Android platform along with agora.io calling service

Question: and thank you in advance for helping, I am using agora.io calling service in many applications calling module the issues I currently facing is that I have never found any perfect sample for callkit that works perfectly with my calling service i.e agora.io.
Answer: Agora.io has example for iOS Callkit here.
Unfortunately, I could not find one for Android.
Due to this question, Android does have similar things like Callkit, but it's full of bugs, so no one wanna try it any more.
Comment: exactly I have discussed with Agora.io technical team that why not you guy creates an example of Callkit for Android as for IOS. they replied that for IOS it is essential but for android, it is not that's why.


Obsolete syntax warning in dlmread

Question: I'm completely new to Matlab, so I've been tying out the various IO functions to see how they operate.  Here I try to construct a matrix from a tab-delimited spreadsheet:
<code>%Matrix test
M = dlmread('MyFile.txt', '\t', 1);
disp(M);
</code>
The output:
<code>>> MatrixTest
Warning: Obsolete syntax. C must be specified with R.
> In dlmread (line 91)
  In MatrixTest (line 2)
    0.3800    0.2900    0.0400    0.2900  -22.2000
    0.4600    0.4500    0.0200    0.0700  -22.2500
    0.4900    0.1500    0.0200    0.3400  -66.7700
    0.1000    0.8100    0.0200    0.0700  -81.7500
    0.1200    0.5700    0.0500    0.2600  -49.5000
    0.3000    0.6000    0.0300    0.0700  -57.4700
    0.4200    0.0900    0.0100    0.4800  -56.3500
    0.2600    0.2800    0.2900    0.1700  -79.7900
    0.4800    0.0300    0.4000    0.0900  -76.8500
    0.2600    0.0100    0.1400    0.5900  -28.6600
    0.2900    0.5000    0.1900    0.0200  -21.5700
    0.1400    0.8300    0.0200    0.0100  -31.2700
    0.0200    0.4700    0.1300    0.3800  -93.1500
    0.0400    0.5000    0.3500    0.1100  -16.9500
    0.1100    0.0100    0.1300    0.7500  -11.0500
    0.2000    0.6700    0.1200    0.0100  -44.7900
    0.3900    0.3600    0.1700    0.0800  -18.7300
    0.1500    0.3300    0.0600    0.4600  -48.4500
    0.3900    0.0800    0.2300    0.3000  -60.6100
    0.3400    0.3600    0.2200    0.0800  -33.0800
    0.1400    0.7800    0.0200    0.0600  -60.5000
    0.3600    0.6300    0.0100         0  -46.6700
    0.1600    0.4800    0.0700    0.2900  -38.2800
</code>
The code works as expected, but apparently I've used obsolete syntax (or maybe the issue is with the dlmread function?).  Anyway, what is the more appropriate way to perform this same operation?
Thanks in advance.
Comment: Per [the documentation](https://www.mathworks.com/help/matlab/ref/dlmread.html) (and the warning), a column input needs to be specified in addition to a row input.
Comment: What makes you think this is obsolete? If it's an editor prompt, it usually corresponds to a note in the docs (there isn't one) and there is usually an alternative suggested. There are many ways to read ascii files, depending what you want to do...
Comment: I think it is obsolete because of the warning issued in the output.  It's the second line above:
" Warning: Obsolete syntax. C must be specified with R."
I don't know what 'C must be specified with R' means, but it doesn't seem to be suggesting an alternative.
Answer: Try using this
<code>%Matrix test
M = dlmread('MyFile.txt', '\t', 1, 0);
disp(M);
</code>
Here, for ignoring first column - use:
<code>%Matrix test
M = dlmread('MyFile.txt', '\t', 1, 1);
disp(M);
</code>
Thanks

Obsolete syntax warning in dlmread


HTTPS Redirect Causing Error "Server cannot append header after HTTP headers have been sent"

Question: I need to check that our visitors are using HTTPS.  In BasePage I check if the request is coming via HTTPS.  If it's not, I redirect back with HTTPS. However, when someone comes to the site and this function is used, I get the error:

System.Web.HttpException: Server
  cannot append header after HTTP
  headers have been sent. at
  System.Web.HttpResponse.AppendHeader(String
  name, String value) at
  System.Web.HttpResponse.AddHeader(String
  name, String value) at
  Premier.Payment.Website.Generic.BasePage..ctor()

Here is the code I started with:
<code>// If page not currently SSL
if (HttpContext.Current.Request.ServerVariables["HTTPS"].Equals("off"))
{
    // If SSL is required
    if (GetConfigSetting("SSLRequired").ToUpper().Equals("TRUE"))
    {
        string redi = "https://" +
        HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() +
        HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString() +
        "?" + HttpContext.Current.Request.ServerVariables["QUERY_STRING"].ToString();
        HttpContext.Current.Response.Redirect(redi.ToString());
    }
}
</code>
I also tried adding this above it (a bit I used in another site for a similar problem):
<code>// Wait until page is copletely loaded before sending anything since we re-build
HttpContext.Current.Response.BufferOutput = true;
</code>
I am using c# in .NET 3.5 on IIS 6.
Comment: Just to follow up - this is what I changed based on Brian's answer below:

    HttpContext.Current.Response.Redirect(redi.ToString(), true);
    return;
Answer: Chad,
Did you try ending the output when you redirect?  There is a second parameter that you'd set to true to tell the output to stop when the redirect header is issued.  Or, if you are buffering the output then maybe you need to clear the buffer before doing the redirect so the headers are not sent out along with the redirect header.
Brian
Comment: Thanks Brian!  You da man.  I added the second parameter "true" to end the response, and added "return;" in the next line to be sure the page stopped running.

    HttpContext.Current.Response.Redirect(redi.ToString(), true);
    return;
Answer: This error usually means that something has bee written to the response stream before a redirection is initiated. So you should make sure that the test for https is done fairly high up in the page load function.
Comment: It is currently the first thing done in the BasePage constructor, so it should be about the first thing done overall.