1sigma error on the mean

Question: My x and y data (n) have a non normal distribution. I'm measuring the mean of the distribution (I'm using Python):
x_m=np.mean(x)
y_m=np.mean(y)

I would like to measure error that represent the standard deviation of the mean (from the 16th and 84th percentile). Do you think this is the right way to do it?
y1=(numpy.percentile(y,16))/n
y2=(numpy.percentile(y,84))/n

Are there any other possibility to measure such an error?
Thank you for your help.
Answer: I'm afraid you've gotten confused. The standard deviation of a random variable is defined according to a simple formula, namely:
$$ \sigma_y = \sqrt{E[(Y - \mu_y)^2]}$$
(This can be re-arranged in various ways, so you may see somewhat different formulae too--see the wikipedia page linked above).
Now, for a normal distribution, it turns out that about 68% of the data (i.e., the 16th - 84th percentiles), lie within one standard deviation of the mean, but this in no way implies that the standard deviation is, in general, connected to those percentiles.
If you want to report standard deviations, calculate them with the formula above and go from there.
Edit: As @User603 points out, one could use percentiles to derive a (weak) lower bound on a standard deviation using Chebyshev's Inequality. Chebyshev's inequality is usually paraphrased as saying that "most" values are near the mean. In particular, at least $100(1 - 1/(k^2))$ percent of the values are within $k$ standard deviations of the population mean, regardless of the distribution. Note that these bounds are pretty loose--and they get even looser when you have sample means and standard deviations instead of population values--so this is of great theoretical interest, but rarely used to analyze data.
Therefore, I'd reiterate my suggestion that you just calculate the standard deviation directly. In numpy, it's just:
numpy.std(y, ddof=1)

(The ddof keyword argument gets you a less-biased estimate of the sample standard deviation; see the numpy std docs for more details).
Comment: err: 'but this in no way implies that the standard deviation is, in general, connected to those percentiles.' A bit too [strong?](http://en.wikipedia.org/wiki/Chebyshev%27s_inequality#Statement)
Comment: @user603:  I would not regard a lower bound for the standard deviation which is usually very weak as a connection
Comment: @user603, that's a fair point, but I'd argue that if you actually want an estimate of the standard deviation, you're much better off with one of the actual sample estimators. Also, Chebyshev only holds for *population* values. I think it's possible to find a similar bound for sample mean/standard deviations, but it's a bit more involved; I think the formula is due to Saw, Yang, and Mo, 1984. Given the nature of the OP's question, I suspect that this might be getting a little far afield, but I'll edit something in.
Comment: @Matt I need the error to plot error bars on the median. So, if I use numpy.std as you suggest do I obtain symmetric error bars?
Comment: You only get one number, so if you +/- standard deviation, so they will have to be symmetric. If you're reporting medians, however, maybe the median absolute deviation or the interquartile range might be a more typical choice, since they "go together" well.

1sigma error on the mean


BIND slave transfers within a local network

Question: I'm trying to have two BIND servers keep their zones in sync.  Usually easy enough.  The tricky bit is that while both servers have external IPs, they are also on the same local subnet with internal IPs (I know name servers should be geographically separated... just humour me).  They are both behind the same NAT router forwarding all traffic respectively.  However when one server sends packets to the other external address they actually appear on the internal interface.  In this situation Bind refuses to acknowledge the response and tries the transfer again.
The notifications from master to slave works fine, it's only when the slave requests a zone transfer from (eg.) 220.127.116.11 and gets a response from 192.168.0.1 that there is a problem.
Is there any way to allow this behaviour in bind?
Comment: You should request the transfer and receive it using the private IPs.
Answer: If both are behind the NAT router and have private IP addresses, you should be using those private IPs within the network rather than the public addresses.  Configure BIND to use the private IPs for the master section on the secondary server, and add an also-notify option to the primary server and ensure the secondary's private IP is listed in the allow-transfer option on the primary as well.


Relation between integrals of powers of a function

Question: Let's assume we have a function $f: I \subset \mathbb{R} \rightarrow \mathbb{R}^n$. (For simplicity, we can first assume that in also only maps in $\mathbb{R}$.) We set $\langle f^k \rangle= \int_I f(x)^k dx$.
Assuming the function fulfills
$$\langle f^k \rangle=c \langle f^{k+1} \rangle, \quad c \in \mathbb{R}$$
for $k \in \{1,...,N\}$, do we know what the function $f$ is?

I know the constant function $f=C$ with $\langle f^k \rangle=C \cdot x^k$ fulfills the relation. But are there other functions?
Answer: No, there is no other such function, provided that $N$ is at least 3.
In that case we have:
$$\langle f^2\rangle=c\langle f^3\rangle\\
\langle f^3\rangle=c\langle f^4\rangle$$
or simply
$${\langle f^2\rangle\over\langle f^3\rangle}={\langle f^3\rangle\over\langle f^4\rangle}$$
or
$$\langle f^2\rangle\langle f^4\rangle=\langle f^3\rangle^2$$
But wait, that's the Cauchy–Schwarz inequality in integral form for $f$ and $f^2$:
$$\left(\int_If(x)g(x)dx\right)^2\leqslant\int_If(x)^2dx\int_Ig(x)^2dx$$
...only we want an equality instead, and it is known to turn into equality only when $f$ and $g$ (in our case, $f$ and $f^2$) are scalar multiples of each other. Q.e.d.

On a side note, $N=2$ is not enough: there are such non-constant functions that ${\langle f\rangle\over\langle f^2\rangle}={\langle f^2\rangle\over\langle f^3\rangle}$.


Why does 'del' work differently in different scenario? Please guide

Question: In the below given code:
a=0
def somefunction():
    a='xyz'
    print(a)
del a
somefunction()
print(a)

The output for above code is

xyz
print(a)
NameError: name 'a' is not defined

Now in different code
a=0
def anotherfunction():
    global a
    a='xyz'
    print(a)

del a
anotherfunction()
print(a)

The output here is

xyz
xyz

Here del doesn't delete the a variable.
Whereas in the below code
a=0
def anotherfunction():
    global a
    a='xyz'
    print(a)

anotherfunction()
print(a)

del a
print(a)

The output here is

xyz
xyz
print(a)
NameError: name 'a' is not defined
Comment: Not sure what exactly is your question. `del` deletes the variable, then you reassign it by calling `anotherfunction`.
Comment: @Selcuk Ok. It is because I have code global a in anotherfunction().
Answer: Basically, what you need to know is scope and namespace in Python.
Please see the Python tutorial on python.org., especially pages 70 to 72.
I am reproducing them here for your benefit:
Comment: Please refrain from posting screenshots or links as the only explanation. If ever something happens to the (image) host, this answer would become useless. Also the contents of screenshots are not easily machine-readable or copy-pastable.
Comment: @NisrinDhoondia Just go to python.org and search for documentation. This would be one of them.
Comment: @Tejas Shetty, Thanks and can you please share the full link of the tutorial
Comment: agreed @BramVanroy. I am currently quite busy. So, I thought better to post something than not post anything at all.
Comment: Two years should be enough. Can you please fix it now? (But ***without*** "Edit:", "Update:", or similar - the question/answer should appear as if it was written today.)


Behavior of Pascal's triangle in $n\mod m$ where $m>2$, any fractals?

Question: If Sierpinski Triangles are found in
Pascal's Triangle under modulo 2 what happens when we view Pascal's Triangle under modulo $m$ where $m>2$? Do fractals appear and if so for which numbers?
Related question, can we predict any behaviors if $m$ is prime?
I looked at $m=3$ with about fifty rows and saw a complicated pattern of upwards and downwards facing triangles be highlighted, but was unsure if the patterns were forming a fractal.
Comment: I wrote a python script about 3 years ago that looked at something similar. It would highlight entries in Pascal's triangle that were equivalent to $0 \pmod m$ for any $m$. You got some interesting looking shapes with triangles, as you said. I will share it when I get home and if I remember.
Comment: I did something on this a long long time ago when I was trying to prove the famous result $$\binom{pa}{pb} \equiv \binom{a}{b}\pmod {p^3}$$ when $p>3$ is prime. Definitely got interesting results when $m$ is prime, and there are fractal-like properties.
Answer: For prime $m=p$ you have Lucas' theorem. It might not be obvious, but this gives a fractal structure to the binomial coefficients, modulo $p$.
(From here out, $m$ is an arbitrary integer, not $p$, because this is the statement from Wikipedia.)
It says that if $m=\sum_{i=0}^k m_i p^i$ and $n=\sum_{i=0}^k n_ip_i$ are the base $p$ representations (so $0\leq m_i,n_i<p$) then:
$$\binom{m}{n}\equiv \prod_{i=0}^k \binom{m_i}{n_i} \pmod p$$
Specifically, then, this means that if $0\leq a< b<p^k$ and  and $M,N$ are any non-negative integers, then:
$$\binom{Mp^k + a}{Np^k+b} \equiv 0\pmod p$$
This gives big blocks where Pascal's triangle is zero, as in Sierpinski.
More generally, we might want to ask about modulo prime powers.
This answer gives some details on Andrew Granville's result for modulo prime powers. Don't know how "fractal" that result is. It seems to be not as "fractal" is the result
for primes, but it is hard to tell.
If it is, then modulo any number $M$, Chinese Remainder Theorem says that Pascal's triangle looks like the overlay of the fractals for each of the prime powers in the unique factorization.
Without Granville, if $M$ is square-free, there will be a fractal structure, modulo $M$.
Answer:
Do fractals appear and if so for which numbers?

Here is what happens experimentally for $m=3..8$ for the first $100$ rows:
All of the pictures are for $C(n,k) \text{ mod } m=0$:

I see fractal strucutre for all the cases, however for primes it's much more simple than for composite numbers, which fits with Thomas' answer.

If we pick $C(n,k) \text{ mod } m=l,~l = 1,2,\dots,m-1$ we also obtain some kind of fractal structures, but different and usually more complicated than for $l=0$.

There is this excellent page which explains a lot about the topic, and with pictures (unlike most papers).
Namely, the pattern for compostie $m$ is a combination of patterns for their prime factors.


Convert JsonPatchDocument to string C#

Question: I am using Newtonsoft.Json.JsonConvert.SerializeObject to convert a JsonPatchDocument<T> to string but it's value property (which is in JObject format) doesn't seem to be converted to string.
Here is what it looks like:
Here is the JSON I am using to create patchDocument object
[
  {
    "path": "/expenseLines/",
    "op": "ReplaceById",
    "value": {
        "ExpenseLineId": 1,
        "Amount": 4.0,
        "CurrencyAmount": 4.0,
        "CurrencyCode": "GBP",
        "ExpenseDate": "2021-11-01T00:00:00",
        "ExpenseType": "TAXI"
    }
  }
]

This JSON is successfully deserialized to JsonPatchDocument object but when I try to serialize it back to JSON, I lose value property (as shown in the picture by red arrows).
Any help would be appreciated :)
Answer: I can't reproduce your problem, can you provide more information? I got stuck during your second serialization. But I used using System.Text.Json to complete your needs, you can look at:
Model:
public class Test
    {
        public string path { get; set; }

        public string op { get; set; }

        public TestValue testValue { get; set; } = new TestValue();

    }

    public class TestValue
    {

        public int ExpenseLineId { get; set; }

        public double Amount { get; set; }

        public double CurrencyAmount { get; set; }

        public string CurrencyCode { get; set; }

        public DateTime ExpenseDate { get; set; }

        public string ExpenseType { get; set; }
    }

TestController:
[ApiController]
    public class HomeController : Controller
    {

        [Route("test")]
        public Object Index()

        {

            var patchDocument = new Test();
            patchDocument.path = "/expenseLines/";
            patchDocument.op = "ReplaceById";
             patchDocument.testValue.ExpenseLineId = 1;
           patchDocument.testValue.Amount = 4.0;
             patchDocument.testValue.CurrencyAmount = 4.0;
           patchDocument.testValue.CurrencyCode = "GBP";
            patchDocument.testValue.ExpenseDate = DateTime.Now;
            patchDocument.testValue.ExpenseType = "TAXI";
            var options = new JsonSerializerOptions { WriteIndented = true };

           // var content = JsonConvert.SerializeObject(patchDocument);
           // string content1 = JsonConvert.SerializeObject(patchDocument.Operations);

            string jsonString = System.Text.Json.JsonSerializer.Serialize<Test>(patchDocument);

             string jsonString1 = System.Text.Json.JsonSerializer.Serialize(patchDocument, options);

            return jsonString;
        }

Result:

Hope this helps you too.
Comment: This is exactly what I needed @Chaodeng . Now, when I use `System.Text.Json.JsonSerializer.Serializer()` I am able to convert `JsonPatchDocument` to string. Before, I was using `Newtonsoft.Json.JsonConvert` and I presume Newtonsoft somehow ignores the `value`.  Thank you for your help :)

Convert JsonPatchDocument to string C#


Como mudar a cor de apenas um elemento num form-group com vários outros?

Question: Olá!
O que acontece comigo é o seguinte:
Estou usando o Bootstrap Validator para validar os campos do meu formulário. Porém, ao rodar a página, os campos estão ficando da seguinte forma. Perceba que o campo "Código" está desativado. Foi validado apenas o "Razão Social". Gostaria que apenas este campo aparecesse em vermelho.

O problema é que tenho que manter ambos os campos no mesmo form-group para que fiquem na mesma linha. Separando os campos em form-groups diferentes, a cor muda corretamente, mas os campos ficam desalinhados. Abaixo meu HTML.

Há alguma forma de aplicar a cor somente para os campos que eu desejar?
Answer: Para manter a estilização separada, você não pode usar mais de um campo de formulário dentro do elemento com a classe form-group.
Veja em: http://getbootstrap.com/css/#forms-inline. Mesmo com cada campo em um "form-group", eles ficam na mesma linha, nesse caso você pose usar uma classe adicional para os campos que devem ficar em linhas separadas.
Answer: Você não irá aplicar a cor somente para os campos que desejas – pelo contrário, você irá excluir as cores dos campos que não desejas.
Para isso, você adicionará à propriedade excluded do bootstrapValidator os campos que estiverem :disabled:
$(formSelector).bootstrapValidator({
    excluded: ':disabled'

    [...]
});

Comment: Olá Guilherme!

Legal, obrigado pela resposta! Mas neste mesmo formulário tenho outros campos que ficam posicionados na mesma linha que não estão desativados, e o mesmo problema ocorre. Neste caso, eu desejaria que a cor fosse aplicada de acordo com cada campo que eu validasse, mas quando eu valido apenas um da mesma linha, os outros aplicam já a cor antes mesmo de eu clicar. Há alguma propriedade que possa resolver isso?
Answer: Acredito que deva criar um código CSS separado para este campo ou retirar CssClass="form-control" do txtCodigo.
Comment: Oi Rogers! Obrigado pela resposta!

Se eu retirar o CssClass="form-control", o campo perderá os atributos aplicados pelo css do Bootstrap. E tenho outros campos abaixo onde ocorrem o mesmo problema, sendo que estes não estão desativados. Sabe me dizer se há outra alternativa? Obrigado!
Answer: Inverta o seu código para ficar da seguinte maneira:

        <input />

        <input />

Dessa forma, você terá as colunas separadas do form-group e poderá validar separadamente os inputs.


Proving $\;\int_{\Bbb R^n_+}e^{-\langle a,x \rangle}dx_1...dx_n = \frac{1}{a_1\cdot... \cdot a_n}$

Question: Denote $\Bbb R^n_+:=\{(x_1,...,x_n): x_i > 0 \;\;\; 1\leq i \leq n \}$. Prove:
$$\int_{\Bbb R^n_+}e^{-\langle a,x \rangle}dx_1...dx_n = \frac{1}{a_1\cdot... \cdot a_n}$$

What I tried:
$$\int_{\Bbb R^n_+}e^{-\langle a,x \rangle}dx_1...dx_n =\lim_{t \to \infty}\int_{(0,t)^n}e^{-\langle a,x \rangle}dx_1...dx_n = \prod_{i=1}^n \int_0^\infty e^{-a_ix_i}dx_i$$
From here it's pretty easy to finish, but the problem I'm facing is explaining why it is ok to assume that $a_i > 0$ for all $i$. Is it even true? or do I need to be told that in the question?
Comment: The assumption that $a_i>0$ for all $i$ cannot be missed, I think.
Comment: Maybe you can parametrize $\mathbb{R}_+^n$ by a radius $r>0$, $n-2$ angles $\phi_1,\ldots,\phi_{n-2}\in[0,2\pi)$ and one azimuthal angle $\theta \in [0,\pi/2)$.
Answer: The factorisation into single integrals is fine, but for the finite result you do need to be told that each $\Re a_i\gt 0$. If even one $a_i$ has real part $\le 0$, say $a_1$, the $\int_0^\infty\exp(-a_1x_1)dx_1$ factor diverges.


Evaluating Multivariable Limit $\lim\limits_{(x,y) \to (0,2)} \frac{\sin(xy)}{x}$

Question: Question: Evaluate the limit $$\lim\limits_{(x,y) \to (0,2)} \frac{\sin(xy)}{x}$$
My first thought is that the limit looks a lot like the single variable $\lim\limits_{x \to 0} \frac{\sin(x)}{x} = 1$. Regardless of what $y$ is (as long as it is real) $xy \to 0$. Hence I am wrongly concluding that the entire limit evaluates to $1$. I guess the ratio of the convergence is not the same as in the single variable case, hence it may not be 1. However, I am unsure how to evaluate it properly.
Comment: The map is not defined for $x=0$. Can you fix that?
Comment: My bad, the $y \to 2$
Answer: Your idea is correct but we need some correction, indeed since $xy\to 0$ we have that
$$\lim\limits_{(x,y) \to (0,2)} \frac{\sin xy}{x}=\lim\limits_{(x,y) \to (0,2)} \frac{\sin xy}{xy}\cdot \frac{xy}{x}=\lim\limits_{(x,y) \to (0,2)} \frac{\sin xy}{xy}\cdot y=1\cdot2=2$$


Integrate $\int \frac{1}{x^3}e^{-x^2}dx$

Question: $$\int \frac{1}{x^3}e^{-x^2}dx$$
What I did?
put $1/x^2 = t; $
then $\int \frac{1}{x^3}e^{-x^2}dx$ will trasform into $\frac{-1}{2}\int e^{-1/t}dt$
I don't understand how to proceed there after.
EDIT:
This problem was given to me by my student. I inquired her, she corrected the problem as $\int \frac{1}{x^3}e^{-x^{-2}}dx$  that makes the problem very simple. Sorry for troubling you all.
Comment: I am surprised this would be homework. There is no elementary function whose derivative is $\frac{1}{x^3}e^{-x^2}$.
Comment: You would have to quote the problem exactly. *Numerical* evaluation of related definite integrals would be possible, or a Fundamental Theorem of Calculus question, but not an indefinite integral question, unless they first define the exponential integral function
Comment: @AndréNicolas: There is alos "Self-Learning" Tag. Its not a problem given to me in a class or something. I'm doing problems by self from a 1st year Bachelor's level book.
Answer: You might try $u=x^2,\ du=2xdx$.  Then $\int \frac{1}{x^3}e^{-x^2}dx=\frac 12\int\frac 1{u^2}e^{-u}du$, which can be integrated by parts using the Exponential integral, but not using more elementary functions.


sendmail and LDAP-based aliases

Question: Environment: CentOS 7.9, Sendmail 8.14, OpenLDAP 2.4
I'm trying to get sendmail to read its aliases from an LDAP database (this has worked with NIS for years, but NIS is fading into the twilight). My mail server is an LDAP client.
In mailserver:/etc/mail/sendmail.mc:
define(confLDAP_DEFAULT_SPEC, `-H ldaps://ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org" -d "uid=sendmail,dc=myoffice,dc=mycompany,dc=org" -M simple -P /etc/mail/secret')dnl
define(`ALIAS_FILE',`ldap:-k (&(objectClass=nisMailAlias)(cn=%0)) -v "rfc822MailMember",/etc/aliases')dnl

Deriving that first line was painful, since my web-fu was poor as I searched for documentation on the sendmail K macro for LDAP. This page was the best I could find, and it appears to be for an older version of sendmail.
When I restart sendmail on the mail server and try to use the aliases database, the response is:
# sendmail -bv sysadmin
ldap_init/ldap_bind failed to ldaps://ldap.myoffice.mycompany.org in map Alias0: Protocol error
sysadmin... deliverable: mailer local, user sysadmin

Note when I revert back to the NIS version, the alias resolves; this is the output I was expecting:
# sendmail -bv sysadmin
myname... deliverable: mailer local, user myname

In mailserver:/etc/openldap/ldap.conf:
BASE    dc=myoffice,dc=mycompany,dc=org
URI     ldaps://ldap.myoffice.mycompany.org ldaps://ldap-replica-1.myoffice.mycompany.org ldaps://ldap-replica-2.myoffice.mycompany.org

SIZELIMIT       unlimited

TLS_CACERT /etc/mail/certs/certs-latest/__myoffice_mycompany_org.cer
TLS_CACERTDIR /etc/mail/certs/certs/certs-latest

__myoffice_mycompany_org.cer is in PEM format and contains the certificate chain and a wildcard certificate for my site, *.myoffice.mycompany.org.
For authentication and searches outside of sendmail, the LDAP searches on via the mail server's LDAP client configuration appear to work just fine. Here are my tests, all of which produce the results I expect:
# Authentication-type searches
ldapsearch -LLL -x -H ldaps://ldap.myoffice.mycompany.org "(uid=myname)"
ldapsearch -LLL -x uid=myname -b dc=myoffice,dc=mycompany,dc=org
ldapsearch -LLL -x uid=myname

# Mail-aliase-type searches
ldapsearch -x -h ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org" "cn=sysadmin"
ldapsearch -x -H ldaps://ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org" "cn=sysadmin"
ldapsearch -H ldaps://ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org" "(cn=sysadmin)" -D "uid=sendmail,dc=myoffice,dc=mycompany,dc=org" -y /etc/mail/secret

The output of the last three commands is identical, and demonstrates that I set up the aliases on the LDAP server according to misc.schema:
# extended LDIF
#
# LDAPv3
# base <ou=Aliases,dc=myoffice,dc=mycompany,dc=org> with scope subtree
# filter: cn=sysadmin
# requesting: ALL
#

# sysadmin, Aliases, myoffice.mycompany.org
dn: cn=sysadmin,ou=Aliases,dc=myoffice,dc=mycompany,dc=org
cn: sysadmin
objectClass: nisMailAlias
objectClass: top
rfc822MailMember: myname

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1

Note that for the last ldapsearch above, in order to try to debug what's going on, I created a separate user uid=sendmail,dc=myoffice,dc=mycompany,dc=org on my LDAP server, with the clear-text password in /etc/mail/secret.
In sendmail.mc, I have also tried:
define(confLDAP_DEFAULT_SPEC, `-h ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org"')dnl

define(confLDAP_DEFAULT_SPEC, `-H ldaps://ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org"')dnl

but the results were the same.
Just to confirm that account myname exists (though I doubt that's the issue):
# ldapsearch -LLL -x uid=myname -b dc=myoffice,dc=mycompany,dc=org
dn: uid=myname,ou=People,dc=myoffice,dc=mycompany,dc=org
uid: myname
cn: Bill Myname
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
shadowLastChange: 17316
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 11230
gidNumber: 10130
homeDirectory: /myoffice/desktop/home/myname
gecos: Bill Myname,Room 321,x2280

What am I missing? Or to put it another way, how are the LDAP lookups in sendmail different from LDAP lookups in the rest of CentOS?
Edit:
I found a web page that suggested that the problem might be that sendmail on CentOS 7 may use certificates in its NSS store instead of just the text files in the CERT_DIR directory. I followed the directions suggested on that page:
cd /etc/openldap/certs
certutil -A -d . -n "Myoffice 2022" -a -i /etc/mail/certs/certs-latest/__myoffice_mycompany_org.cer -t "CT,c,"

But this made no changes in sendmail's LDAP+aliases behavior.
Comment: I guess my first recommendation would be, "why are you using sendmail? Use a more modern mailer with a less baroque (arguably "broke") configuration syntax.", but if you're determined to go down this painful route, consider turning up the logging in your LDAP service so that you can see exactly what queries sendmail is making (if any). If you can't do that, then consider (a) using `ldap://` instead of `ldaps://` and capturing the traffic with `tcpdump`, or (b) if that's not possible, set up an `ldap` to `ldaps` proxy so that you can accomplish the same thing with an extra step.
Comment: The answer to your question: Because I've spent years configuring sendmail to do what I want it to do. Switching to a different MTA means potentially disrupting services for my users. I know that postfix is described as a superior MTA, but if everything works in sendmail (mailer tables, access lists, mailing-list routing), a better configuration syntax just doesn't seem to be a compelling enough reason.
Answer: Thanks to larsks's suggestion, I have the answer. It turned out that olcLogLevel on my LDAP server was already set to -1. I hunted through the logs, which I thought I'd done before, but evidently not carefully enough. I found the message:
send_ldap_result: err=2 matched="" text="historical protocol version requested, use LDAPv3 instead"

It turns out that sendmail 8.14 by default uses the LDAPv2 protocol, which was made obsolete with LDAPv3 many years ago. A web search showed me the procedure to add the option on my LDAP server to accept v2 connections:
In allow_bind_v2.ldif:
dn: cn=config
add: olcAllows
olcAllows: bind_v2

Then I issued the command
# ldapmodify -H ldapi:// -Y EXTERNAL -f allow_bind_v2.ldif

Going back to my mail server, I discovered that a simple configuration was sufficient in my sendmail.mc:
define(confLDAP_DEFAULT_SPEC, `-H ldaps://ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org"')dnl

After restarting sendmail, I got the results I expected:
# sendmail -bv sysadmin
myname... deliverable: mailer local, user myname

While this worked, it seemed incredible to me that after all these years that even a relatively older version of sendmail couldn't support LDAPv3. Now that I knew what to look for, I found this page which explained how to get sendmail to use LDAPv3: add -w 3 to the confLDAP_DEFAULT_SPEC:
define(confLDAP_DEFAULT_SPEC, `-H ldaps://ldap.myoffice.mycompany.org -b "ou=Aliases,dc=myoffice,dc=mycompany,dc=org" -w 3')dnl

With that, I could turn off bind_v2 on my LDAP server:
In remove_bind_v2.ldif:
dn: cn=config
delete: olcAllows

ldapmodify -H ldapi:// -Y EXTERNAL -f remove_bind_v2.ldif

Sendmail alias resolution still worked just fine.
While I acknowledge that this entire situation+solution tends to confirm larsks' argument about sendmail, I've now got something that works. Time to move on to the next problem.

sendmail and LDAP-based aliases


G is a graph with n points.If it exists a number c > 0,,makes that g(G) ≥ cn.(g(G) is the girth of the G).How to prove that e(G) ≤ n + o(n)?

Question:
Suppose $G$ is a graph with $n$ points. If it exists a number $c > 0$, makes that $g(G) ≥ cn\cdot\left(g(G) \text { is the girth of the G}\right)$. How to prove that $e(G) ≤ n + o(n)$?

I want to use mathematical induction to solve this question, but there is no good idea of using mathematical induction. I want to change this question to a normal graph that only has cyclic with length $[cn]$, and try to think the situation has the most edges, but I failed.
Answer: I have solve this question by myself.Just think about c=1/2^n(n=0,1,2,3...),and for graph G, divide points of G to two part and use mathematical induction to n will solve this question.


Can we localize WIX msi and bundle using language selection UI at runtime?

Question: We have an MSI and Bundle created  in Wix. I need to localize both of these in such a way that language selection GUI will be popped-up and language can be selected by the user at run time. Would be really appreciated if anybody can help me on this.
For MSI, i am working on creating another bootstapper for bringing-up with language selection combobox and invoke the tranfomed MSI  with the required transform(using command shell). I am still not sure about the feasibilty of this approach. I am facing issue in creating combo box in customized UI of bootstapper and invoking batch command to run this msi in the required language.
For Bundle - I am still working on finding a method. if anybody has any idea/samples for this.
It will be helpful if anybody can help me with this issue or provide me with an another alternative method to meet above requirement.
Thanks,
Answer: The recommended method (and for that matter, the method used by most MS products), is as you describe.

Create an MSI localized for each language
pick a base and generate MST's
Package the MSTs, the MSI and the bootstrapper, which will
present the language selection dialog and call MSIEXEC, passing TRANSFORM=language.mst as an argument

After the MSIEXEC process has started, all localization is finalized, so to speak.  Any selection must go on outside the MSI system.
See this codeproject article for an example.
Comment: You dont need to call MSIEXEC. Simply bundle the msi using `MsiPackage` and create a child node ``
Comment: @durgesht, the question references creating a custom bootstrapper, which would have to call `MSIEXEC` directly.  WiX Bundles just simplify the generation of such bootstrappers - one way or another, the `TRANSFORMS` property gets passed to the MSI system.
Answer: UI selection for MSI

Create an MSI localized for each language
Pick a base and generate MST's
Package the MSTs, the MSI into a bootstrapper.
Customize the HyperlinkTheme.xml to include radio button for selecting each language.
Use the Variable tag to link radio button from UI to .wxs file
Include the msi property in the msi tag and hard code the path to MST's and InstallCondition attribute to differentiate each selection
Use the latest version of wix for this feature support.

Bundle support only automatic base detection there is no support for UI selection
Comment: Where did you add the radio button? The `` element of a theme doesn't allow a child of type `RadioButton`. Can you show (an excerpt of) the theme that you've created?
Answer: I guess this may help you:
creating language selection dialog using WiX.
there is a limitation that custom UI for language selection is created using C# based custom bootstrapper. This may lead to the requirement of .Net framework on host machine.


Initial-boundary value problem for PDE

Question: I need a little help with solving IBVP for hyperbolic and parabolic equations like these:
$$
hyperbolic:
\left\{\begin{matrix}
\frac{\partial^2u}{\partial t^2}=\frac{\partial^2 u}{\partial x^2}+1\\
u(0,t) =u(1, t) =0\\
u(x,0) = 0\\
u_t(x,0)=x
\end{matrix}\right.
\\parabolic:
\left\{\begin{matrix}
3\frac{\partial u}{\partial t}=4\frac{\partial^2 u}{\partial x^2}\\
u(0,t) =u(5, t) =0\\
u(x,0) = x
\end{matrix}\right.
$$
Don't even know where to start.
I'm not actually asking for full solution, but would appreciate it if you could give me direction. Links to tutorials and examples are also highly welcomed.
Update:
Second equation looks like 1 dimensional heat conduction equation: $u_t = c^2u_{xx}$ with $c=\frac{2\sqrt{3}}{3}$.

Ok, for the second one method of separation of variables could be applied.
We assume that $u$ can be written as a product of single variable functions of each independent variable, $u(x, t) = X (x)T (t)$. Substituting this guess into the heat equation, we find that $XT′ =c^2X′′T$. Dividing both sides by $c^2$ and $u = XT$, we then get $\frac{1}{c^2}\frac{T'}{T} = \frac{X''}{X} = \lambda$. This leads to two equations: $$
T′ =c^2\lambda T\\
X'' = \lambda X
$$
giving $$
T(t) = Ae^{c^2λt}\\
X(x) = c_1e^{\sqrt{\lambda}x} + c_2e^{\sqrt{-\lambda}x}$$
The aim is to force our product solutions to satisfy both the boundary conditions and initial conditions.

Is it possible to use this method for the first equation?
Comment: And the first one is a nonhomogeneous wave equation. Both problems can be solved by eigenfunction expansion method (see, e.g., Farlow, Partial differential equations for scientists and engineers)
Answer:
Is it possible to use this method for the first equation?

Yes, the same method works. You first need to find the eigenfunctions of the corresponding homogeneous problem (let me denote them as $e_i(x)$, these are $X(x)$ in your solution, there is a countable number of them), then you represent your non-homogeneous term (in your case $f(x,t)=1$) as a series using the found eigenfunctions $f(x,t)=\sum f_i(t)e_i(x)$, and then look for the solution in the form $u(x,t)=\sum T_i(t)e_i(x)$ (just plug this expression in your equation). For the unknown functions $T_i(t)$ you'll get differential equations which take into account $f_i(t)$.
Again, all the details with great care are shown in the book I referenced above in my comment.

Initial-boundary value problem for PDE


x range is invalid. Maybe timefmt wrong

Question: I have the following script
set datafile separator ","
set grid

set autoscale

set timefmt "%y-%m-%d %H:%M:%S"
set xdata time

plot 'test.txt' using 1:2 with lines

Data
2017-09-01 13:15:29,615,668
2017-09-01 13:15:29,615,666
2017-09-01 13:15:29,614,666
2017-09-01 13:15:29,615,666
2017-09-01 13:15:29,615,665
2017-09-01 13:19:52,614,660
2017-09-01 13:19:52,615,661

I want to plot this data which was generated by postgresql. Since hours i cant figure out why i get
gnuplot> plot 'test.txt' using 1:2 with lines
                                             ^
         "strom-plot.txt", line 9: x range is invalid

Any hint would be appreciated.
EDIT: I am on gnuplot 5.0 patchlevel 5 debian stretch
Answer: The issue is an error in your timefmt argument. You should be using %Y instead of %y. From help timefmt:

Format       Explanation
%y           year, 0--99
%Y           year, 4-digit

This works here:
set datafile separator ","
set grid

set autoscale

set timefmt "%Y-%m-%d %H:%M:%S"
set xdata time

plot 'test.txt' using 1:2 with lines

Result:
Comment: Thanks, I had the same error message, and adding `set datafile separator ","` fixed it.

x range is invalid. Maybe timefmt wrong


Fabric - run as an a different user, but non-sudo

Question: I want to do
sudo su - some_user
source virtualenv/bin/activate
pip install psycopg2 gunicorn django-modeltranslation

using fabric.
If I do
with sudo_settings(sudo_user="some_user"):
     with prefix("source virtualenv/bin/activate"):
         sudo("pip install psycopg2 gunicorn django-modeltranslation")

I get

The directory '/home/coby/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

followed by an exception with
Traceback (most recent call last):
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main
 status = self.run(options, args)
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/commands/install.py", line 324, in run
 requirement_set.prepare_files(finder)
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/req/req_set.py", line 380, in prepare_files
 ignore_dependencies=self.ignore_dependencies))
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/req/req_set.py", line 554, in _prepare_file
 require_hashes
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/req/req_install.py", line 281, in populate_link
 self.link = self._wheel_cache.cached_wheel(self.link, self.name)
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/wheel.py", line 68, in cached_wheel
 self._cache_dir, link, self._format_control, package_name)
File "/<home>/some_user/virtualenv/lib/python3.5/site-packages/pip/wheel.py", line 129, in cached_wheel
 wheel_names = os.listdir(root)
PermissionError: [Errno 13] Permission denied: '/<home>/<sudo_user>/.cache/pip/wheels/cd/07/05/fa31adf8c1d71f5979e4329601d36c883f063ed0e99e5e29fa'

UPD: pip install psycopg2 gunicorn --no-cache-dir works.
Comment: were you able to run the first set of command in the server without fab?
Comment: yes, I was able to run the first set of commands on the server through SSH.
Answer: In shell you run source after sudo which is right because source is a shell builtin that affects the current environment.
You have to do the same with fabric: run sudo() and call source inside it, not outside.
Your current fab code is equivalent to
source virtualenv/bin/activate
sudo su - some_user
pip install psycopg2 gunicorn


python regex to exclude multiple words

Question: I need to parse a file like this:
Nmap scan report for pc15393.foster.xxx.com (192.168.2.211)
Nmap scan report for lab-776.foster.xxx.com (192.168.2.212)
Nmap scan report for 78T458Y.foster.xxx.com (192.168.2.213)

I'd like to get rid of "Nmap scan report for" and get the following:
pc15393.foster.xxx.com (192.168.2.211)
lab-776.foster.xxx.com (192.168.2.212)
78T458Y.foster.xxx.com (192.168.2.213)

If I use the following regex: extract = re.findall (r'for.*',line)
I get everything starting from "for" but that's wrong.
Can anyone help me?
Thanks a lot
Knud
Answer: Here you go. Clearly replace my_file.txt with your file. This was python 2.7.12
#/usr/bin/env python
import re
pattern = re.compile("Nmap scan report for (.*)")
for i, line in enumerate(open('my_file.txt')):
    for match in re.finditer(pattern, line):
        print match.group(1)

Answer: If you want to get only this data, better use awk.
cat yourfile | awk '{print $5 $6}'

If give information you want.

python regex to exclude multiple words


How to express an invalid argument such as "affirming the consequent" in propositional logic?

Question: For example, say you want to write a symbolic statement for affirming the consequent. You could write it in the following two ways
$$
(P \to Q, Q) \to P
$$
or
$$
\frac{P \to Q, Q}{P}
$$
Which one should be used? Is it mostly a difference in taste/preference, or is one more favourable than another, or perhaps are there circumstances where one is used instead of the other?
Comment: The first one can be recovered using the general form $(\Gamma, \varphi)$ where the *set* $\Gamma$ of formulas is the set of premises and $\varphi$ is the conclusion. Thus, MP will be $(\{ \alpha \to \beta, \alpha \}, \beta)$.
Comment: Having said that, regarding the title question, you may simply write: $P \to Q, Q \nvDash P$ that means: "the conclusion does **not** follow from the premises".
Answer: I have never seen the first one … and for good reason: it uses the symbol $\to$ both as a logic symbol (a symbol of the language of logic) as well as a meta-logic symbol (a symbol that is used to say something about logic), and you really want to separate those two.
But the second way is a pretty standard to express an inference, sure! Another common notation is $P \to Q, Q \therefore P$
Comment: Ah, then [wikipedia](https://en.wikipedia.org/wiki/Affirming_the_consequent) has an error. I am not surprised.
Comment: I suppose a follow up question would then be, what is better to use, the one with the turnstile, or the one with the horizontal bar/fraction format?
Comment: @Kalcifer The turnstile is used more in text (i.e. in a paragraph), while the horizontal bar is used either for emphasis of a particular result or when the deductions need to be graphically organized in a way — e.g. constructing a tree, either a semantic or proof-theoretic one. Both are perfectly fine to use, but I'd guess the turnstile is more frequent.
Comment: @Kalcifer Yeah, that notation in the Wikipedia page is unusual at best  … and I would say that overloading the $\to$ symbol like that is confusing and just really inappropriate.
Comment: Great answer except I don't believe using the turnstile $\vdash$ to express an invalid argument such as $P \to Q, Q \vdash P$ is correct because the turnstile means that a conclusion is provable from a set of premises and the premises $P \to Q, Q$ do *not* prove $P$ in propositional logic.
Comment: @RyRytheFlyGuy 'provable' means 'provable using a certain set of inference rules', so ultimately 'provability' is always relative to a particular proof system. Indeed, we really should always index the turnstyle, and say something like $\phi \vdash_{S} \psi$ to say that 'system $S$ can derive $\psi$ from $\phi$'.  Of course, we typically assume that whatever proof system we work with is sound and complete, so then $\vdash$ collapses to $\vDash$, and as such we can remove the system reference. But at least theoretically, a proof system can 'prove' invalid inferences
Comment: @Bram28 Yes, what is provable is relative to the formal system in question. The OP stated propositional logic was being used (in the title). In that case, the turnstile $\vdash$ is not an appropriate way of expressing the argument $P \to Q, Q \vdash P$.
Comment: @RyRytheFlyGuy But different proof systems can be defined relative to propositional logic, including ones that allow invalid inferences. Anyway, I think a much better reason not to use the $\vdash$ is that the OP simply wants to express this inference or argument, rather than make a claim about the provability of this inference. So, the horizontal line is good, and so would the $\therefore$... and so you're right, the $\vdash$ is probably not good, but I would say not so much for the reason you state.
Comment: Looks like I have homework to do! Thanks for the feedback, @Bram28
Comment: @RyRytheFlyGuy And thank you for yours!  Made me realize that $\vdash$ is indeed not a good way to express an inference, thanks!
Answer: You seem to want a means of expressing an argument without actually asserting it is valid or invalid. So, if you want to express that $P$ allegedly follows from the premises $Q, P \to Q$, then the convention is to use a symbol such as the colon ":" or therefore sign "$\therefore$" or even the double slash "//"as follows
$$ Q, P \to Q : P \\
   Q, P \to Q \therefore P \\
   Q, P \to Q \text{ // } P \\ $$
I've seen these symbols often used to express arguments whose validity is not yet decided. Such arguments may be referred to as sequents. Tomassi expounds on this idea in his book Logic beginning on page $43$.
I do not suggest using the turnstile "$\vdash$" to formally express an argument unless your intent is to assert the conclusion is provable from the premises in a given system. This is because the turnstile "$\vdash$" has a very specific meaning, that is, a sentence of the form
$$ P_1,P_2,...,P_n \vdash C $$
not only alleges that $C$ follows from the premises $P_1,P_2,...,P_n$ but also makes the stronger claim that $C$ is in fact a logical consequence of the premises, provable from the formulas $P_1,P_2,...,P_n$ using the inference rules of the given system.
So, if you cannot prove $P$ is a logical consequence of the premises $Q, P \to Q$ in the system you're working with, then using the turnstile to express
$$ Q, P \to Q \vdash P $$
would be patently incorrect. In fact, the argument $ Q, P \to Q : P $ is an invalid argument form referred to as "affirming the consequent" in all propositional systems I'm aware of (although it could certainly be a valid argument in other systems). In such cases, writing
$$ Q, P \to Q \nvdash P $$
would be correct, stating that $Q, P \to Q$ does not prove $P$.
I also agree with the comments made about using the arrow and horizontal bar.
Answer:
How to express an invalid argument such as "affirming the consequent"
in propositional logic?

We can say that $((P\to Q)\land Q) \to P$ is a contingency, i.e. it is sometimes true, and sometimes false.
The truth table:

Specifically, we can formally state that $(((P\to Q)\land Q) \to P)\iff (Q\to P)$
The truth table:


How to create a link from node view and pass information to a webform

Question: In Drupal 8, I have a webform field attached to a node with the Link to form formatter enabled.
Can I add the ID of that node in the Link custom attributes (YAML) textarea to display a block view of some node fields?
My goal is to be able to use a contextual filter on the block view to display the node information like title and some other fields around the form
Comment: What's your end goal? I'm not quite following.
Comment: I have a just my question see above
Answer: I don't think webform link field can be used to accomplish this as the purpose of Link custom attributes (YAML) is for HTML TAG attributes like
target: _blank

You can use field_token_value to create a field on the node that has tokens as input. Install and enable the module and then add a token field.

The value of this field would be an HTML link with query parameters added (nodetitle in this example) you can browser for all available tokens under field value.

Then on the webform side you have to enable query parameter to populate fields by going to the settings of the webform > form > form behaviours > prepopulate > Allow all elements to be populated using query string parameters.

And then on the field to display the query parameter include the appropriate token.  Here adding the nodetitle to the subject field default value.

For token field to be populated a node needs to be saved.


Percorrer uma lista dentro de outra Lista

Question: Olá eu sou iniciante em Python e gostaria de saber se tem como percorre uma lista dentro de outra lista, eu tentei fazer um exemplo, mais tá dando esse erro: "TypeError: 'int' object is not subscriptable", se alguém puder me ajudar, desde já agradreço
result = ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
for i in range (len(result)): # procurar em todas as listas internas
for j in range (i):
    print(result[i][j])

Answer: Este erro ocorre, porque você está tentando percorrer um número.
Utilizando o seu exemplo, ele tenta iterar os elementos 'spam' e '1'. Como eles não são uma lista, ocorre o erro.
Uma maneira de resolver este problema é colocando uma verificação antes de percorrer os itens internos.
result = ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
for i in result:
    print(i)
    if type (i) == list:
       for j in i:
           print(j)

Eu mudei um pouco a maneira que eu faço a iteração, mas é possível utilizar a sua maneira de percorrer as listas.
Comment: Muito obrigada pela ajuda!


updated constraints in traitCollectionDidChange have no effect

Question: With my autolayout, I am trying to implement a special case for the smallest screens, when my icons need to be smaller.  I am changing the constraint for the icons in traitCollectionDidChange().  However, the change has no effect.  I've tried adding SetNeedsLayout, SetNeedsDisplay, UpdateConstraints, etc, and nothing works.
If I change these constraints when the view is initialized, then the change works -- but that doesn't help me when the user rotates the device and I need the change to happen again.  However, it's interesting to note that traitCollectionDidChange() is called at the launch of the program, but if I make the constraint changes within that function, they don't work. They only work if I set the new constraints in the init() function of the view.
It could be that this function is called AFTER the constraints are used, except Apple tells us to use this function for just this purpose, to change layouts etc when rotating.  I don't want to use WillTransitionToSize because only the ViewController is called with that function, not views.  But I will probably try that next.
traitCollectionDidChange() is definitely being called, at startup and when I rotate.  It's just that my changes don't do anything.  Any ideas?
Any ideas?
<code>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {

    super.traitCollectionDidChange(previousTraitCollection)

    // smaller icon constraints for iPhone 5/SE

    if let constraint = (self.imageView!.constraints.filter{$0.firstAttribute == .width}.first) {
        print("cwide \(constraint.constant)")
        if UIScreen.main.bounds.size.width <= 320 {
            constraint.constant = 20.0
            self.radius = 4

        }
        else {
            constraint.constant = 32.0
            self.radius = 8
        }

    }

    self.updateConstraints()
}
</code>
Comment: Is this in a subclass of `UIView` or `UIViewController`? If it's in a controller that last call needs to call `self.view` rather than `self`. You can also try calling `layoutIfNeeded()` on the view, I have had very good luck with that method.
Comment: It's a UIView subclass.  I just tried adding layoutIfNeeded() and it didn't help unfortunately...
Comment: So I ran into an issue where custom fonts didn't work unless I waited a little less than a second before setting them. It was as though something else was setting the font. Maybe the same thing is happening here?? If you extract all your code into another method and fire it 1-2 seconds laterite might work. Then you can narrow down the time frame to the smallest value or fire it multiple times (which is what we ended up doing). It's a pretty obnoxious work around but it might work.
Comment: ugh! it probably is something like that.  I actually just decided to forget about the constraints and changed the size of the subview manually in the custom draw function of its parent's view. That is working, but if it stops then I will give your suggestion a try.
Comment: this doesn't work for adding constraints to tableview cells/headers.  it seems to be called after reloadData stuff.  if i add constraint in a view/cell's init, stuff is fine.
Answer: I had a similar feature and i turned out that I had forgotten to install the constraints in the Interface Builder.


Robust estimation of kurtosis?

Question: I am using the usual estimator for kurtosis, $$\hat{K}=\frac{\hat{\mu}_4}{\hat{\sigma}^4}$$, but I notice that even small 'outliers' in my empirical distribution, i.e. small peaks far from the center, affect it tremendously. Is there a kurtosis estimator which is more robust?
Answer: There are several. You will find an exhaustive comparison in
this link to an ungated version of the paper (proper reference at the bottom of this answer).
Because of the constraints of the problem, the breakdown of the most robust of these algorithms (the L/RMC) is at most 12.5%. An advantage to the the L/RMC is that it is based on quantiles and remain interpretable even when the underlying distribution has no moments. Another advantage is that it does not assume symmetry of the distribution of the uncontaminated part of the data to measure tail weight: in fact, the algorithm returns two numbers: the RMC for the right tail weight and the LMC for the left tail weight.
The robustness of an estimator can be measured by its breakdown point.
However, the notion of breakdown point is a complicated one in this
context. Intuitively, it means that an adversary would need to control at least 12.5% of your sample to make this estimator take on arbitrary values (that is to be understood as an arbitrary value within the range of values that the estimator can return, since the measure of tail weight is always in $[0,1]$ by construction: no amount of contamination can for example cause the algorithm to return -1!). In practice, one finds that one can replace about 5% of the sample with even very pathological outliers without causing the most affected of the estimates (there are always two) to depart too much from the value it had on the uncontaminated sample.
The L/RMC is also widely implemented. For example you can find an R implementation
here. As explained in the article linked above, to compute the L/RMC, you need to compute the MC (the estimator implemented in the link) separately on the left and right half of you data. Here, (left) right half are the sub-samples formed of the observation (smaller) larger than the median of your original sample.

Brys, Hubert, Struyf. (2006). Robust Measures of Tail Weight.
Comment: Aren't these alternative measures of tail weight rather than robust estimators of kurtosis per say? This may be what he really wants. but it is not exactly what he asked for. Do any/all of these estimators converge to kurtosis for large samples?
Comment: Pearson's kurtosis measures outliers (rare extreme observations), plain and simple.  So what are you looking for instead? A measure of "peakedness"? First, that is not at all what Pearson's kurtosis measures. Second, if you want a measure of "peakedness", you first have to define what that means. If you can define it, you can estimate it. One possibility is the second derivative of the pdf of the standardized data, evaluated at the peak. (You're welcome).  I am sure there are others.
Comment: Actually, I give three mathematical theorems that relate kurtosis to the tails of the distribution, so these cannot be falsified: (i) For all distributions with finite fourth moment, kurtosis is between E(Z^4 * I(|Z| >1)) and E(Z^4 * I(|Z| >1)) +1. (ii) In the sub-class for which the density of Z^2 is continuous and decreasing on (0,1), the "+1" can be replaced by "+.5". (iii) For any sequence of distributions having kurtosis -> infinity, E(Z^4 * I(|Z| >b))/kurtosis -> 1, for any real b. It's all here: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4321753/
Comment: Summary from the paper: At uncontaminated data satifying the conditions on convex ordering of Van Zwet (under which the measure of kurtosis is meaningful) they converge to a monotone function of kurtosis.

Robust estimation of kurtosis?


Printing a function on a content type page?

Question: So if I have a custom function with a DB query within template.php such as
function innovista_get_page_children() {

 $result = db_query("SELECT link_path FROM {menu_links}");
 return $result;

}

and I have a content type specific template page, then how do I echo the results in the template file?
I tried this:
<?php
$results = innovista_get_page_children();
foreach($results as $result){
    print $result;
}
?>

I get the following error

Recoverable fatal error: Object of class stdClass could not be
  converted to string in include() (line 83 of
  /var/www/vhosts/vidanlawnes.co.uk/innovista2/sites/all/themes/innovista/node--level_1.tpl.php).

If I remove print $result; and replace with print 'hello'... e.g
<?php
$results = innovista_get_page_children();
foreach($results as $result){
//print $result;
print 'hello ';
}
?>

It echoes hello out multiple times, so the query is providing results, but I can't seem to print them as $result. Any ideas?
Thanks for your time
Answer: The error message itself is clear I think. You are trying to print an object as a string.
otherwise, your query seems correct.
function innovista_get_page_children() {

 $result = db_query("SELECT link_path FROM {menu_links}");
 return $result;

}

<?php
$results = innovista_get_page_children();
print '
';
foreach($results as $result){
    print_r($result);
}
print '
';
?>

Now you will see a formatted variable information of each $result.
it will look like
stdClass Object (
  [link_path] => admin/structure/views
)

So when you print the results, it will be like,
<?php
    $results = innovista_get_page_children();
    foreach($results as $result){
      print $result->link_path;
      print '
';
    }
?>

However, keep in mind that it's never OK to print link paths or database queries like this. It will cause huge performance problems and will arise security problems.
Try to use url() and/or l() functions for links (suggested it because you seem to make a link).
Also, in most cases, there is a function for core/contrib modules to retrive data.
Comment: Thank you. The query will be more complex (not printing the link_path but using it for another query). When I have finished my function in Drupal, I will post another question on Drupal Answers to ask for improvement suggestions...I'm aware I'm new to Drupal development and so I can probably do most things more efficiently than my first attempts. Thank you.
Comment: welcome :)
database queries are something that you should pay more attention to security and performance.that's why I suggested using url() l() and other simple functions when possible. Those functions are well written and in most cases, performance-friendly.
Good luck!
Answer: Every theme function/template runs hook_preprocess_HOOK() and hook_process_hook() before executing the function/template. hook_preprocess_HOOK is where you'd want to set up any new variables. The hook is passed an array of variables by reference, and you add to that array. The key of the array becomes the name of the variable in your template. People often try to keep all the logic out of the template file in this way. For example to set up a variable $foo in a page template (ie what's used for theme('page', ...)) you could do this.
/**
 * Implements hook_preprocess_page().
 */
MYMODULE_preprocess_page(&$vars) {
  $vars['foo'] = 'bar';
}

Comment: Hey, I have just made my question more specific with the error it throws. Could you give me advice on how to apply your solution (if it is still valid) to my problem? Thanks so much
Comment: @slawrence10 The error is because you're trying to `print` an object. You can see [an example in the docs for using `db_query()`](http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7#comment-7019). As things stand your code isn't very Drupally (!) - are you trying to create a block or a page (or something else)?
Comment: I'm going to get the child items of a page to print out in a page template.
Comment: @slawrence10 what exactly do you want to print out? A link? If so, what should be the text?
Comment: Hey Andy, sorry the function will be more complex I just boiled down the whole query, because such a basic thing as echoing the variable wasn't working...I now see I should have used the format $result->link_path

When I've completed my full solution, I will create another Drupal Answers questions asking for improvements and suggestions. I realise I may be doing many things inefficiently as I'm new to Drupal development. Thank you for your time!
Comment: @slawrence10 OK; I've edited my answer to show you how to add a variable to the page template. From page.tpl.php (or any [suggestions used in its place](http://drupal.org/node/1089656)) you should be able to `print $foo;`. So just put your DB code in the preprocess and create appropriate variable(s) for the template code to be as simple as possible.
Answer: First I dont suggest  put your function in template.php directly, (you can put in in custom module)
I suggest you act more professionaler in function, This code showed your are begginer in drupal developing,
however . this code have to work because template.php function in exist form basic drupal bootstrapping.
Your problem is your function maybe  not return anything and $var will be empty.
When I was begginer in drupal put my global fuction in themplate.php and use them in every where i want,  test something like this
function myfunction() {

      $result = db_query("SELECT field FROM {table} WHERE field = 'query' ");
       if ($result)
       return $result;
       else
       return "sorry,no result";
     }

and in your tpl file
<?php
      $myvar = mytheme_myfunction();
      print $myvar;
?>

I know this is not principle method but sometimes we just need it just work. :)
Comment: Hey, check the updated edit. The query definitely has results, because if I use foreach to echo a string "hello" for each result then it does, but when I try and print the actual $result it gives me an error.


Select Tag with different methods and actions per options

Question: would it be possible to somehow create a select dropdown that automatically sends it to a specific action (I can use onchange => this.form.submit) but the problem is that every option will lead to a different method and action.
For example
Select
  option 1: Delete # This should redirect to a @post method: delete
  option 2: Do Something #this should redirect to do_something_posts method: get
basically each option should be able  to do a different 'redirect to an action'
Thanks!
Comment: you can make use of ajax, then get the value of the select element value. then you can make use of that value to do your process
Answer: Yes you can do in rails way
<code><%= select_tag("id", options_for_select(list), data: {url: your_path, remote: true, method: :post_or_get}, prompt: "please...") %>
</code>
This will hit your action with selected value of select tag.
Comment: problem with this is that the url and method will be dependent on whatever  option they select, unless I add a jquery feature though I'm hoping there's some rails way


Hetzner netscan abuse

Question: A few days back I have received the abuse notification from Hetzner datacenter. There seems to be a netscan going on my server. What I don't understand is that why the destinations are the local network IPs? What does that mean and how should I stop it ? Below is the email they sent me :

Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 33342 =>   192.168.1.122 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 33249 =>   192.168.1.123 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 54650 =>   192.168.1.124 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 50813 =>   192.168.1.125 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 43352 =>   192.168.1.126 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 53177 =>   192.168.1.127 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 58477 =>   192.168.1.128 7
  Fri Jun 15 21:02:46 2018 TCP    MY SERVER IP 33213 =>   192.168.1.129 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 58466 =>   192.168.1.130 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 51264 =>   192.168.1.133 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 53684 =>   192.168.1.134 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 51751 =>   192.168.1.135 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 54523 =>   192.168.1.136 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 42139 =>   192.168.1.137 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 51317 =>   192.168.1.138 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 34863 =>   192.168.1.139 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 43767 =>   192.168.1.140 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 34036 =>   192.168.1.141 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 36163 =>   192.168.1.143 7
  Fri Jun 15 21:02:47 2018 TCP    MY SERVER IP 43617 =>   192.168.1.145 7
  Fri Jun 15 21:02:48 2018 TCP    MY SERVER IP 56095 =>   192.168.1.149 7
  Fri Jun 15 21:02:48 2018 TCP    MY SERVER IP 51691 =>   192.168.1.150 7
Comment: https://serverfault.com/questions/218005/how-do-i-deal-with-a-compromised-server
Answer: Your server has been compromised. You should save your data, format the disks, reinstall everything and secure it up with strong passwords and even better ssh access with keys only (nopassword option), all unnecessary services turned off.
Comment: Not necessarily. Mis-configured apps will lead to this. For instance, QB will trigger Hetzner alerts see: https://www.reddit.com/r/qBittorrent/comments/gr3hgr/qbittorrent_scanning_ports_on_local_network_while/

Hetzner netscan abuse


How do i find this limit WITHOUT L'hôpitals rule

Question: How do I find
$$\lim_{x\to 0}\frac{(x+4)^{3/2}+e^x-9}{x}$$
without l'hôpital rule? I know from l'hôpital the answer is 4.
Comment: To help explain the hint, $\lim_{x\to 0}\frac{f(x)-f(0)}{x-0}=f'(0)$, by the definition of derivative.
Comment: I've tried conjugates because the x+4 equation is technically a sqaure root but that didn't work.
Comment: Apart from that I've been googling and trying to find methods (and desipher the hint suggested below)
Answer: Hint: The expression equals
$$ \frac{f(x) - f(0) + g(x) - g(0)}{x-0}$$
if you choose $f,g$ appropriately.
Comment: @LLlAMnYP: No L'Hospital's Rule works by differentiating and then taking a limit. Here it is just shown that the limit in question is a derivative namely $(f - g)'(0)$ for suitable $f, g$. Recognizing a limit as a derivative and recognizing a $0/0$ indeterminate form and further applying L'Hospital on it are two different things and first one is simpler. In general using L'Hospital's Rule to evaluate limits of type $\lim_{x \to a}\dfrac{f(x) - f(a)}{x - a}$ is a bad idea and it may not work all the time.
Comment: @LLlAMnYP Look at it this way: The approach I'm suggesting would be feasible in the first few weeks of basic calculus, even before the mean value theorem. LHR comes later, usually around the time Taylor's theorem is discussed, and depends on the fancier generalized MVT. Also as our friend Paramanand Singh notes, all we need to use this approach is that both $f'(0),g'(0)$ exist - we do not need to know $f'(x),g'(x)$ exist for any other $x$ as in LHR.
Comment: That's the approach I would have suggested.
Comment: Is this not literally l'Hopital's rule with the added convenience that the function in the denominator happens to be $x$ rather than some $h(x)$?
Answer: The limit can be found using neither Taylor expansions, nor derivatives, but with much more basic approaches.
First, a consequence of the well-known limit
$$ \lim_{x\rightarrow0} \left(1 +\frac{1}{x}\right)^x = e$$
is
$$ \lim_{x\rightarrow0} \frac{e^x -1}{x} = 1 $$
so the limit in OP is equal to
$$ 1 + \lim_{x\rightarrow0} \frac{(x+4)^{3/2} -8}{x} $$
so long as the second term exists. We calculate the second term as
$$ \lim_{x\rightarrow0} \frac{((x+4)^{3/2}-8)((x+4)^{3/2}+8)}{x((x+4)^{3/2}+8)} = \lim_{x\rightarrow0} \frac{(x+4)^3-64}{x((x+4)^{3/2}+8)} = \\ \lim_{x\rightarrow0} \frac{(x+4)^3-64}{x} \lim_{x\rightarrow0} \frac{1}{((x+4)^{3/2}+8)} = \frac{1}{16} \lim_{x\rightarrow0}\frac{48x+12x^2+x^3}{x}=\frac{48}{16}=3$$
where again then transition from the first line to the second is valid so long as both limits exist (which, as you see, they do).
Comment: My answer is not close to LHR, so please stop saying it is. It will do you well to understand this point.
Comment: Taylor's theorem is independent of L'Hospital's Rule. There is a proof using L'Hospital's Rule, but it does not make them equivalent. There are other proofs too.
Comment: @ParamanandSingh you're more than likely right. This problem took me back to a calculus exam with a simple limit $\lim_{x\rightarrow0}\frac{\sin 5x}{\sin 7x}$ to be done without l'Hopital. Attempts to do this using Taylor were also for some reason considered implicitly out of bounds. So we had to start from $\lim_{x\rightarrow0}\frac{\sin x}{x}$
Comment: That particular limit can be done just by using the formulas for $\sin 5x,\sin 7x$ in terms of $\sin x$. Note that if $n$ is odd then $\sin nx=n\sin x+\dots$ and $\sin x$ can be taken out as factor. Canceling it we get the limit $5/7$. Also see this answer https://math.stackexchange.com/a/2101475/72031
Comment: @ParamanandSingh sure. At that exam the correct solution for that particular question was $\frac{\sin 5x}{\sin 7x} = \frac{5}{7}\frac{\sin 5x}{5x}\frac{7x}{\sin 7x}$
Comment: @zhw what do you mean "stop saying"? Both my comment and answer were posted near simultaneously several days ago. I have long since stopped saying anything.
Comment: You said it once, then you said it again 40 minutes later (not simultaneously), and you left it up after my comments.
Comment: @zhw You're being pedantic (what are 40 minutes over several days?) to no end. I hope my edit makes you happy.
Answer: Less elegant than zhw'x answer.
For $(x+4)^{3/2}$, use the generalized binomial theorem of Taylor expansion
$$(x+4)^{3/2}=8+3 x+\frac{3 x^2}{16}+O\left(x^3\right)$$ Using the standard Taylor expnasion of $e^x$, we then have $$(x+4)^{3/2}+e^x-9=\left(8+3 x+\frac{3 x^2}{16}+O\left(x^3\right) \right)+\left( 1+x+\frac{x^2}{2}+O\left(x^3\right)\right)-9$$ $$(x+4)^{3/2}+e^x-9=4 x+\frac{11 }{16}x^2+O\left(x^3\right)$$
$$\frac{(x+4)^{3/2}+e^x-9}{x}=4 +\frac{11 }{16}x+O\left(x^2\right)$$ which shows the limit and how it is approached.


Biggest differences between 4 mallet grips

Question: I am aware that there are 2 popular ways to hold 4 mallets while playing the marimba. There is Burton's and there is Steven's. I am not really even sure which grip I currently use, as I just started playing with 4 mallets. All I know is that one of them causes more pain on your fingers, which I believe is Steven's. Also, as I was talking to my private teacher, I found out that there is a separate grip for 4 mallet jazz vibes. Does anyone know the name for this and the pros/cons?
Answer: My answer will largely contain excerpts from Robert Breithaupt's book "The Complete Percussionist."
The Cross Grip is derived by crossing a second mallet over a single mallet, held in a traditional style.  This grip creates stability within the grip, but does not provide for the independent control of the mallets needed for much advanced marimba literature.
The Burton Grip was developed by Gary Burton, and provides greater control of the inside mallets and a less cumbersome wrist motion for the outside mallets.  Small and large intervals are created in the same manner as the cross grip.  Single line melodies are often played with the inside mallet of the left hand and the outside mallet of the right hand.  This grip is used by most vibraphonists.
The Musser Grip allows movement from one movement without corresponding movement from the other.  This grip employs a hand positi8on similar to the matched grip snare drum grip.
The Stevens Grip positions the hand such that it is most similar to that of the American timpani grip / drum set ride cymbal grip (also known as the French grip.)
I included these explanations to help you determine which grip you currently employ.  Grip preference is in part determined by what style of music you play and what performance practices you prefer individually.  This is in part decided by not only your aesthetic / comfort preferences but also things you cannot change - like hand size for example.
I know that the Musser / Stevens grips are popular because of the increased flexibility.  It allows for some very unique chord voicings (such as reaching a M10 in each hand!) but again, pros and cons are really contingent upon individual players.
The four grips presented above are the grips I am most familiar with and have learned myself, and if there is a fifth, it is either not well-known or well-accepted.  If you have small hands, the Stevens or Musser grip might be causing you problems since they demand more independence.  However, the pain you're experiencing could also be from poor practice technique.
At any rate, since you are taking private lessons, I would highly, highly suggest that you speak with your teacher about the concerns and grip types.
Hope that helps!
Answer: Neither grip should be painful, although Stevens requires a little more muscle development on the weak side of the hand which could cause some overuse strain when just starting out.  The Burton grip is the 'jazz' grip.  It was developed by jazz vibist Gary Burton.
I've found that the Stevens grip is better if you need to play lines that jump around a lot because you have substantially more control over individual mallets.  An example of this might be playing fast arpeggios.  If you are doing a lot of blocked chords and lines without a lot of jumping, the Burton grip is the way to go.  It's more stable and allows you put a lot of power into your strokes.  In general Burton grip forces you to use more macro movements(arms instead of fingers) to accomplish the strokes.
All that being said, in the long run the Stevens grip is the more flexible of the two, and you'd rarely catch an orchestral percussionist using Burton grip.
Comment: What are blocked chords? And can you upload pictures of them?
Comment: @CodyGuldner: [Block chords](http://en.m.wikipedia.org/wiki/Block_chord) refers to a way of homophonically playing a musical line with four part harmony. This is often employed by jazz pianists and jazz vibraphonists in melody and solo playing, as well as being a standard tool in jazz arranging for wind instruments.
Answer: I started off using the Stevens Technique, because that was the grip of choice by the person teaching me at the time. It seemed easy enough, so I used it for a few years. That being said, there's one that most call "traditional grip." That's the one to use, in my opinion. It's much easier for playing fast passages with the inner two, easier to open and close quickly, AND I personally find it more comfortable.


Making a client sticky without initial session identifier with HAProxy

Question: We have HAProxy infront of a pair of API servers. Currently using appsession because a lot of API clients won't be maintaining a cookie - that's a burden we don't want to pass on to our users.
The problem we're facing is that once a client logs in, they have to stay on that particular API server, due to connections the API servers make to other services on behalf of the client. Unfortunately, there is no session identifier until after the first login request is made, so the next request made with the session identifier usually roundrobins to the opposite server and remains sticky there.
Here is our backend config:
backend api
      mode http
      option httplog
      option httpclose
      option httpchk HEAD /index.html
      cookie apibalance insert indirect nocache
      appsession sessionId len 36 timeout 360s request-learn mode query-string
      server api01 api01.hostname:8080 cookie api1 check weight 30 inter 10000 downinter 20000
      server api02 api01.hostname:8080 cookie api2 check weight 30 inter 10000 downinter 20000

The cookie apibalance is left over from how we were doing things, but I figure we can probably remove it now.
Is there a way to tell HAProxy, probably via the response, that future requests made with sessionId within the query-string should stick to the current server? Session Id is generated server side (the API server), and returned within a JSON response. Successive requests will be sent with the session id within the query string.
Answer: The answer, for me at least, was to do IP based stickiness.
balance source

And remove the cookie and appsession based configuration.


Using Matlab's fmincon to find optimal parameter of SDOF system having discrete white noise input

Question: I am trying to use Matlab's fmincon function to find the optimal value of $k$ for the following ODE, which represents a mass-spring system,
$$m\ddot{x}(t)+kx(t)=f(t),$$
where $f(t)$ is taken to be constant amplitude white noise. The cost function is taken to be absolute maximum displacement of the mass, that is, $\max_\limits{t}(|x(t)|)$.
The issue I am having is that fmincon takes a very long time to find the optimal value when using a white noise input. When using a sinusoidal input, fmincon finds the optimal value relatively quickly. Note that this is just an illustrative example of a problem I'm experiencing with a more complicated ODE, that is, even with the complicated ODE, having a sinusoidal input the optimal value is found relatively quickly.
First let's generate the white noise input and save it into an .mat file,
stepsize = 0.01;
tgm = 0:stepsize:10;
fgm = randn(numel(tgm),1);
save('gm.mat','tgm','fgm')

The code is broken into three parts:
The objective function and loading the discrete input:
function cost = objfunc(para)
tstart = 0;
tfinal = 10;    % sec

load('gm.mat','tgm','fgm')
options = odeset('RelTol',1e-8 ,'AbsTol',1e-8 );

z0 = [0 ; 0];

[t,z] = ode45(@(t,z) sdof(t,z,para,tgm,fgm), [tstart,tfinal], z0,options);

cost = max(abs(z(:,1)));
end

The ODE:
function dz = sdof(t,z,para,tgm,fgm)
dz = zeros(2,1);
k = para;
m = 1
f = interp1(tgm, fgm, t, 'linear');

dz(1) = z(2);
dz(2) = -(k/m)*z(1) + f/m;
end

Calling fmincon:
para0 = 0.1;
lb = 0;
ub = 1;
para = fmincon(@objfunc, para0, [], [], [], [],lb, ub);

I'm pretty new to using Matlab's Optimization Toolbox so I'm not entirely sure if I'm approaching this problem correctly, or if I should code the white noise differently or input it in a different place.
Thanks for any help or feedback!
Comment: In my opinion, the problem is that you load your mat file each time you are computing the cost function. Consider using persistent parameters or anonymous functions. Note also that for your problem the ```fminbnd``` seems to be more pertinent.
Comment: Thank you for your comment. I will experiment with either keeping the inputs as persistent variables or using anonymous functions. I did see ```fminbnd```, but the more complicated ODE will optimize over 3 parameters and so I'll need to use ```fmincon``` eventually.
Comment: As a follow up question, would using an anonymous function created using the ```fit``` function on the generated white noise then importing the object through fmincon possibly lead to faster convergence?
Answer: Surprisingly, but the problem is not in load. When I run your code with a profiler, it takes 460 seconds, where 396 seconds are spent for interp1, 2808319 calls, that is 141 ms per 1000 calls.
If you open the code of this function, you will find that it makes a lot of things to parse your inputs, then it creates a griddedInterpolant, and then it interpolates. Since we know that we always call it with the same   tgm and fgm, let us create the griddedInterpolant on our side, and then pass it to the function as an argument. Ok, now the code with the profiler takes 178 seconds (125 seconds without profiling), where interpolation takes 71 seconds for the same 2808319 calls, that is 25 ms per 1000 calls, more than 5 times faster.
Creating anonymous functions does not change a lot in this case, but I have also updated the code to show how it works.
The function that creates a handle for the cost function:
function obj_fh = get_objfun(tgm, fgm)

    data_set = griddedInterpolant(tgm,fgm);

    tstart = 0;
    tfinal = 10;    % sec
    z0 = [0 ; 0];

    options = odeset('RelTol',1e-8 ,'AbsTol',1e-8 );

    obj_fh = @(para) objfun(para);

        function cost = objfun(para)
            [~,z] = ode45(@(t,z) sdof(t,z,para,data_set), [tstart,tfinal], z0,options);

            cost = max(abs(z(:,1)));
        end
end

The function that implements the ode
function dz = sdof(t,z,para,data_set)
    dz = zeros(2,1);

    k = para;
    m = 1;
    f = data_set(t);

    dz(1) = z(2);
    dz(2) = -(k/m)*z(1) + f/m;
end

The main script
para0 = 0.1;
lb = 0;
ub = 1;

load('gm.mat','tgm','fgm');
objfunc = get_objfun(tgm, fgm);

para = fmincon(objfunc, para0, [], [], [], [],lb, ub);

Comment: The object ```obj_fh``` if a function handle. It is a pointer (handle) to a function that takes one input ```para``` and returns ```cost```. The function ```get_objfun``` creates a local workspace with local variables, e.g., ```data_set```, and then defines the function ```objfun```, which operates on this workspace. The pointer to the function can be then used to compute the cost using the previously defined workspace.
Comment: Thank you very much for your answer, it was very helpful, and definitely sped up the computation time. I have one follow up question though, in the ```get_objfun``` function, you set ```obj_fh=@(para) objfun(para)```, where ```objfun``` is defined just below. My question is, where does ```obj_fh``` get ```para``` from? Is it provided by ```fmincon``` some how?


Yum dependency available but not marked for install

Question: I'm trying to install a specific version of MySQL: mysql-community-server-5.6.29-2.el6 on RedHat 6.6.
When I run yum install, I get dependency errors, but the dependencies are clearly available. I'm not sure how to proceed.
It looks like something is requesting MySQL-community-libs-5.7.11-1.el6, but I don't know how to force it not to.
Useful output:
[root@cl-mgr01 ~]# yum install mysql-community-server-5.6.29-2.el6
     ## truncated for brevity ##
Resolving Dependencies
--> Running transaction check
---> Package mysql-community-server.x86_64 0:5.6.29-2.el6 will be installed
--> Processing Dependency: mysql-community-common(x86-64) = 5.6.29-2.el6 for package: mysql-community-server-5.6.29-2.el6.x86_64
--> Processing Dependency: mysql-community-client(x86-64) = 5.6.29-2.el6 for package: mysql-community-server-5.6.29-2.el6.x86_64
--> Processing Dependency: libnuma.so.1(libnuma_1.2)(64bit) for package: mysql-community-server-5.6.29-2.el6.x86_64
--> Processing Dependency: libnuma.so.1(libnuma_1.1)(64bit) for package: mysql-community-server-5.6.29-2.el6.x86_64
--> Processing Dependency: libnuma.so.1()(64bit) for package: mysql-community-server-5.6.29-2.el6.x86_64
--> Running transaction check
---> Package mysql-community-client.x86_64 0:5.6.29-2.el6 will be installed
--> Processing Dependency: mysql-community-libs(x86-64) = 5.6.29-2.el6 for package: mysql-community-client-5.6.29-2.el6.x86_64
---> Package mysql-community-common.x86_64 0:5.6.29-2.el6 will be installed
---> Package numactl.x86_64 0:2.0.9-2.el6 will be installed
--> Running transaction check
---> Package mysql-community-libs.x86_64 0:5.6.29-2.el6 will be obsoleting
---> Package mysql-libs.x86_64 0:5.1.73-3.el6_5 will be obsoleted
--> Processing Dependency: libmysqlclient.so.16()(64bit) for package: 2:postfix-2.6.6-6.el6_5.x86_64
--> Processing Dependency: libmysqlclient.so.16()(64bit) for package: perl-DBD-MySQL-4.013-3.el6.x86_64
--> Processing Dependency: libmysqlclient.so.16(libmysqlclient_16)(64bit) for package: 2:postfix-2.6.6-6.el6_5.x86_64
--> Processing Dependency: libmysqlclient.so.16(libmysqlclient_16)(64bit) for package: perl-DBD-MySQL-4.013-3.el6.x86_64
--> Running transaction check
---> Package mysql-community-libs.x86_64 0:5.7.11-1.el6 will be obsoleting
--> Processing Dependency: mysql-community-common(x86-64) = 5.7.11-1.el6 for package: mysql-community-libs-5.7.11-1.el6.x86_64
---> Package mysql-community-libs-compat.x86_64 0:5.7.11-1.el6 will be obsoleting
--> Running transaction check
---> Package mysql-community-common.x86_64 0:5.6.29-2.el6 will be installed
--> Processing Dependency: mysql-community-common(x86-64) = 5.6.29-2.el6 for package: mysql-community-server-5.6.29-2.el6.x86_64
--> Processing Dependency: mysql-community-common(x86-64) = 5.6.29-2.el6 for package: mysql-community-libs-5.6.29-2.el6.x86_64
---> Package mysql-community-common.x86_64 0:5.7.11-1.el6 will be installed
--> Finished Dependency Resolution
Error: Package: mysql-community-server-5.6.29-2.el6.x86_64 (mysql)
           Requires: mysql-community-common(x86-64) = 5.6.29-2.el6
              ...
           Available: mysql-community-common-5.6.29-2.el6.x86_64 (mysql)
               mysql-community-common(x86-64) = 5.6.29-2.el6
              ...
           Installing: mysql-community-common-5.7.11-1.el6.x86_64 (mysql)
               mysql-community-common(x86-64) = 5.7.11-1.el6
Error: Package: mysql-community-libs-5.6.29-2.el6.x86_64 (mysql)
           Requires: mysql-community-common(x86-64) = 5.6.29-2.el6
             ...
           Available: mysql-community-common-5.6.29-2.el6.x86_64 (mysql)
               mysql-community-common(x86-64) = 5.6.29-2.el6
             ...
           Installing: mysql-community-common-5.7.11-1.el6.x86_64 (mysql)
               mysql-community-common(x86-64) = 5.7.11-1.el6
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

Other useful output:
[root@cl-mgr01 ~]# rpm -qa | grep mysql
mysql-connector-java-5.1.17-6.el6.noarch
mysql-libs-5.1.73-3.el6_5.x86_64

Answer: Try following:
# yum install --enablerepo=mysql56-community install mysql-community-server
Loaded plugins: fastestmirror, langpacks, nvidia
Loading mirror speeds from cached hostfile
 * base: mirror.metrocast.net
 * elrepo: mirror.symnds.com
 * epel: mirror.metrocast.net
 * extras: mirror.metrocast.net
 * nux-dextop: mirror.li.nux.ro
 * updates: mirror.solarvps.com
No package install available.
Package mysql-community-server-5.6.30-2.el7.x86_64 already installed and latest version
Nothing to do
#

... better yet, using yum-config-manager, disable mysql57-community and enable mysql56-community, then install mysql-community-server.
# yum repolist | grep mysql
mysql-connectors-community/x86_64 MySQL Connectors Community                 21
mysql-tools-community/x86_64      MySQL Tools Community                      33
mysql56-community/x86_64          MySQL 5.6 Community Server                229
# egrep '^(name|\[|enabled)' /etc/yum.repos.d/mysql-community.repo
[mysql-connectors-community]
name=MySQL Connectors Community
enabled=1
[mysql-tools-community]
name=MySQL Tools Community
enabled=1
[mysql55-community]
name=MySQL 5.5 Community Server
enabled=0
[mysql56-community]
name=MySQL 5.6 Community Server
enabled=1
[mysql57-community-dmr]
name=MySQL 5.7 Community Server Development Milestone Release
enabled=0
#

Comment: Ah, I forgot to add: this is not on an internet-connected network, and the reposerver is outside my control...
Answer: What I had to do in the end is the following:

Upgrade MySQL-libs using yum update mysql-libs, which installed mysql-community-libs
Downgrade them using yum downgrade mysql-libs so that they were on 5.6.29
Install mysql-community-server


What to do if recurve arrows are far to the right?

Question: I am shooting a recurve bow, and my arrow group is to the right.
My problem is that my sight pin is already over as far right as it goes, and if I move it any further I won't be able to see it anymore.
Is there anything else I can adjust to bring my group over to the left?
Comment: I don't know anything about archery, but judging just from the title, this seems related: [What to do if the arrows are too far to the left?](http://sports.stackexchange.com/questions/2875/what-to-do-if-the-arrows-are-too-far-to-the-left). (BTW this question was shown also in related links on the right.)
Comment: It seems to me that you would have different things to do in order to bring your arrows more to the left, than the main answer at least says for that question.  Some adjustments in archery (in fact, most, other than simply aiming intentionally off center) are unidirectional.  This should not be closed as duplicate, at least without some feedback from someone expert in the field.
Comment: This is definitely a dupe of https://sports.stackexchange.com/questions/2875/what-to-do-if-the-arrows-are-too-far-to-the-left - it's the same problem with the same cause (usually a form issue)
Answer: Alright, I finally figured it out. The problem was that my sight picture was about three inches off.


Visualising OLS estimator sampling distribution

Question: I am trying to understand the idea of the sampling distribution of an OLS estimator. To do so I am trying to visualise this distribution obtained with simulations (I use R for this).
So I generate the universe of observations with 100,000 randomly distributed observations of my independent variable univ.x. Then I also generate the universe of observations for the dependent variable (univ.y) according to the following (exact) linear relationship: univ.y=1.5+3*univ.x.
> univ.x <- rnorm(100000,0,1)
> univ.y <- 1.5 + 3*univ.x
> summary(lm(univ.y~univ.x))

Call:
lm(formula = univ.y ~ univ.x)

Residuals:
       Min         1Q     Median         3Q        Max
-2.900e-15 -3.000e-16 -2.000e-16  0.000e+00  8.498e-12

Coefficients:
            Estimate Std. Error   t value Pr(>|t|)
(Intercept) 1.50e+00   9.75e-17 1.538e+16   <2e-16 ***
univ.x      3.00e+00   9.73e-17 3.083e+16   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.083e-14 on 99998 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 9.507e+32 on 1 and 99998 DF,  p-value: < 2.2e-16

So far so good.
At this point, I want to sample 1,000 observations from the universe and I would expect to find the same linear relationship with some random error. But I don't, in fact I find only the intercept but the slope is 0 and not 3. I have also repeated this 100 times with the same result.
What am I missing here?
Here is the code:
> x <- sample(univ.x, 1000)
> y <- sample(univ.y, 1000)
> summary(lm(y ~ x))

Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max
-9.9094 -2.0161 -0.0021  1.9563  8.9696

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.505428   0.096626  15.580   <2e-16 ***
x           0.009807   0.094319   0.104    0.917
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.055 on 998 degrees of freedom
Multiple R-squared:  1.083e-05, Adjusted R-squared:  -0.0009912
F-statistic: 0.01081 on 1 and 998 DF,  p-value: 0.9172

Visualising the sampling distribution of OLS estimates [solved]
Thanks to the comments I solved my problem. I leave the code here for interested users and learners.
univ.x <- rnorm(100000,0,1)
univ.y <- 1.5 + 3*univ.x + rnorm(100000,0,3)
summary(lm(univ.y~univ.x))
plot(univ.x,univ.y)

b <- vector(mode = "numeric", 1000)
for (i in 1:1000){
        samp <- sample(1:100000, 100)
        x <- univ.x[samp]
        y <- univ.y[samp]
        model <- lm(y~x)
        b[i] <- coef(model)[2]
}
hist(b)

Answer: You are sampling 1000 of the $x_i$ at random and 1000 of the $y_i$ at random, so you are not necessarily sampling 1000 pairs $(x_i,y_i)$ that fulfill the linear relationship, or that are connected in any way.
Moreover, the data you generated has no randomness in the $y_i$ respect to the $x_i$. Once you knew one observation of $x_i$ you would know the corresponding $y_i$ for sure, right? This is not the real-life setting that OLS or regression is designed for.
The true regression equation you would get from real life data is $$y_i=\beta x_i+\varepsilon_i,$$
where $\varepsilon_i\sim N(0,\sigma2)$. So to obtain randomness you also need to generate the random errors $\varepsilon_i$, all of them drawn from the same distribution $N(0,\sigma2)$.


How to join three entities in a view?

Question: I have a Drupal schema where I want a view to display node 'item' results based on fields from an associated 'catalogue' node. Each associated 'catalogue' has a 'catalogue_ranking' node which is used to order 'item' results.  So the join I am looking for is:
items <== LEFT JOIN catalogue <== LEFT JOIN catalogue_ranking
I can manually construct the SQL I need to produce the results as follows:
SELECT node.nid, substring(node.title, 1, 20) AS title, field_data_field_catalogue.field_catalogue_nid,
       node_catalogue.nid AS cat_nid, substring(node_catalogue.title, 1, 20) AS cat_title,
       field_data_field_ref_catalogue.field_ref_catalogue_nid, node_cat_ranking.nid AS rank_nid, field_data_field_priority.field_priority_value
  FROM node node LEFT JOIN field_data_field_catalogue field_data_field_catalogue ON node.nid = field_data_field_catalogue.entity_id
                 LEFT JOIN node node_catalogue ON node_catalogue.nid = field_data_field_catalogue.field_catalogue_nid
                 LEFT JOIN field_data_field_ref_catalogue field_data_field_ref_catalogue ON node_catalogue.nid = field_data_field_ref_catalogue.field_ref_catalogue_nid
                 LEFT JOIN node node_cat_ranking ON node_cat_ranking.nid=field_data_field_ref_catalogue.entity_id
                 LEFT JOIN field_data_field_priority field_data_field_priority ON node_cat_ranking.nid = field_data_field_priority.entity_id
  WHERE LENGTH(node.title) > 1 ORDER BY IFNULL(field_data_field_priority.field_priority_value, 0) DESC LIMIT 5;

However, I've been going bananas trying to figure out the exact forward or reverse relationships needed to produce the same results using the Drupal view UI. The "Priority" field remains stubbornly blank no matter what combinations I try! What am I doing wrong?
Comment: How do you join the entities? I guess with `entity-reference`. If views you have `Relationship` settings where you can add reference by fields
Comment: Yes, I know about the Relationship settings. The problem is that the join attempts to relate catalogue_ranking nodes to the _item_ nodes, not to the _catalogue_ nodes. If I use a relationship inside a relationship, it gets closer but still matches on the wrong fields.
Comment: filter on item. Add relationship a bridge to the Content entity that is referencing Content via the entity reference field from catalogue to item. Add relationship a bridge to the Content entity that is referencing Content via the entity reference field from ranking to catalogue, and set previous relationship as relationship. Add sort on rank field and set relationship to last relationship added. That is if I read your relationships correctly.
Comment: Hi J, yes, that is exactly what I would have thought should work, but it doesn't :(

Although I should caveat that by saying that I am using a Node Reference field instead of an Entity Reference field because ER is way too slow when doing lookups. Could that make a difference?
Answer: You can implement custom relationship using hook_views_data_alter() and define exactly in this hook which fields to use for JOIN - https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7
Example:

/**
 * Implements hook_views_data_alter().
 */
function custom_log_views_data_alter(&$data) {
  // Expose uid as a relationship to users.
  $data['custom_log']['uid'] = array(
    'title' => t('User information.'),
    'help' => t('Information related to user who triggered the event.'),
    'relationship' => array(
      'base' => 'users',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('User information.'),
    ),
  );
}

How to join three entities in a view?


8 - Form Validate Entity Reference

Question: I would like to add a form validation to an entity edit form. The entity has an entity_reference field on which I would like to perform a manual validation. I have successfully implemented a hook function to access the data entered into the widget, perform the required checks, and raise an error if necessary. The problem is that I do not want to make my function dependent on the widget that is used to alter the entity_reference field.
An entity_reference field with cardinality bigger than 1 (i.e. the ability to store a list of entries) can be edited using, e.g., an Autocomplete, an Autocomplete (Tag Style) or a Select List. The problem is that the data accessible in the validation function will differ depending on what widget is used.
The function $form_state->getValue('field_name') returns either
Array ( [0] => Array ( [target_id] => 2 ) [1] => Array ( [target_id] => 3 ) )

or
Array ( [target_id] => Array ( [0] => Array ( [target_id] => 2 ) [1] => Array ( [target_id] => 3 ) ) )

For a select_list or an autocomplete_tag, respectively.
I could obviously check what the structure of the array is to determine how to handle it, but I'm sure there must be a better way to obtain the data from this array.
My custom validation involves a check to be performed on a relation between the referenced entities and the user, so I do not need to perform any checks on the entered raw data. Basically, I just want to obtain a list of target_id's that I can interact with.
Answer: The solution was to implement entity-level constraints. This allows Drupal to manage the data that gets typed into the widgets, and no additional (widget-dependent) validation is necessary.
Apparently, the idea in Drupal 8 is that most entity-related validations are not done via the form validations. Instead, so-called constraints can be added, either on the field level to affect only one field, or on the entity level to affect multiple fields.
This GitHub repo contains example files for creating entity-level constraints, which were very helpful. You will need to create files for the Constraint and for its Validator. Furthermore, you will need to attach the Constraint to the Entity, which can be done either using hooks (as demonstrated in the .module file, see link above) or by adding this to the annotations of your entity:
 *   constraints = {
 *     "ExampleConstraint" = {}
 *   }

8 - Form Validate Entity Reference


Solve $\frac{dy}{dx} + \frac{y}{x} = \frac{1}{(1+\log x+\log y)^2}$

Question:
Solve $\frac{dy}{dx} + \frac{y}{x} = \frac{1}{(1+\log x+\log y)^2}$

I tried solving this differential equation, I got stuck after a few steps
I got
$(a+\log(xy))^2d(xy) = xdx$
I don't know what to do after this
Answer: If you write $$\frac{dy}{dx}+\frac{y}{x} = \frac{1}{(1+\log(xy))^2}$$ and substitute $v=xy$, then wonderful things happen.  Then $$\frac{dv}{dx} = x\frac{dy}{dx} +y$$ Plug stuff in and the equation becomes $$\frac{1}{x}\frac{dv}{dx}=\frac{1}{(1+\log v)^2},$$ separable.
Answer: Taking L.C.M on the left side you'll get
$$ (xdy + ydx )(1+logxy)^2 = xdx $$
And as we know that $$xdy + ydx = d(xy)$$ so by substituting $$xy=t$$ you'll get
$$(1+logt)^2 dt = xdx $$
Integrating both sides
$$ \int (1+logt)^2 \mathrm{d}t =  (x^2 )/2 + c$$
To solve the L.H.S use your own integration skills (Hint :- Integration by parts )
Answer: With $u = xy$, the differential equation becomes
separable.
Comment: Why the downvote?


MongoDB - Erro ao executar find geoespacial $near

Question: Tenho uma coleção com os seguintes documentos.
<code>{
    "_id" : ObjectId("5c6bb6b492647b15f80038a1"),
    "loc" : {
        "type" : "Point",
        "coordenadas" : [
            -41.104658,
            -20.963387
        ]
    }
}
</code>
Estou executando o find:
<code>db.tblfrota.find(
   { loc : {
        $near :  {
           $geometry :  {
              type  :  "Point" ,
              coordenadas  :  [  parseFloat(-41.81064615) ,  parseFloat(-22.39813884)  ]
           },
           $maxDistance :  5000
        }
   }
   }
)
</code>
Tenho os índices:
<code>[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_"
    },
    {
        "v" : 2,
        "key" : {
            "loc.coordenadas" : "2dsphere"
        },
        "name" : "coord_3d",
        "2dsphereIndexVersion" : 3
    },
    {
        "v" : 2,
        "key" : {
            "coordenadas" : "2d"
        },
        "name" : "coordenadas_2d"

    }
]
</code>
Está retornando o erro :

Error: error: {   "ok" : 0,   "errmsg" : "invalid point in geo near
  query $geometry argument: { type: \"Point\", coordenadas: [
  -41.81064615, -22.39813884 ] }  Point must be an array or object",    "code" : 2,     "codeName" : "BadValue" }
Answer: Resolvido: o erro era na sintaxe.
db.tblfrota.find(
   { loc.coordenadas: {
        $near :  {
           $geometry :  {
              type  :  "Point" ,
              coordinates:  [  parseFloat(-41.81064615) ,  parseFloat(-22.39813884)  ]
           },
           $maxDistance :  5000
        }
   }
   }
)