Apache SVN module do not list permissioned subfolders in web view

Question: I've builded up a SVN server in a Ubuntu 16 LTS instance connected with a AD via LDAP. My problem is: I can't setup the Apache or the SVN module to list the subfolders of a repository when a user does not have R permission on the root level of the repository.
Example:
[RepositoryABC]
user1=rw
user2=r

[RepositoryABC:/folder]
user3=rw

When the user1 and user2 access the SVN via the web view provided by the SVN Apache module both can see the RepositoryABC. But if the user3 try the same he/she will get a empty page although he/she has permission in the subfolder.
Answer: I think that you might try to add user3 to root directory with r, and then hide undesired folders from him, like:
[RepositoryABC]
user1=rw
user2=r
user3=r

[RepositoryABC:/OTHER_FOLDER_1_YOU_WANT_TO_HIDE_FROM_USER3]
user3=(syntax that hides)
[RepositoryABC:/OTHER_FOLDER_2_YOU_WANT_TO_HIDE_FROM_USER3]
user3=(syntax that hides)

[RepositoryABC:/folder]
user3=rw

just an idea, untested.
Comment: `syntax that hides` would be?
Comment: @MarceloFilho it's you who should write that, I exactly dont know the specifics of AD/LDAP and there should exist a value (instead of `r/rw`) which will forbid any access to those folders.


Losing a bit when converting in JavaScript?

Question: So let's say I have a var testIP = '188.8.131.52';
And I'm performing following methods:
function ipToBin(ip) {
    var block = ip.split('.');
    var res = 0;

    res += block[0] << 24;
    res += block[1] << 16;
    res += block[2] << 8;
    res += block[3] << 0;

    bin = res.toString(2);
    console.log('\n to bin: ', bin);
    console.log(bin.length);
    return bin;
}

function binToIP(bin) {
    var block1 = (bin.split(0, 8));
    block1 = parseInt(block1, 2);
    block1 = (block1 >> 0) & 255;

    var block2 = bin.split(9, 8);
    block2 = parseInt(block2, 2);
    block2 = (block2 >> 8) & 255;

    var block3 = bin.split(17, 8);
    block3 = parseInt(block3, 2);
    block3 = (block3 >> 16) & 255;

    var block4 = bin.split(25, 8);
    block4 = parseInt(block4, 2);
    block4 = (block4 >> 24) & 255;

    console.log((block4 + '.' + block3 + '.' + block2 + '.' + block1).toString());
}

Now the thing is that the binary string's length is only 31 and when converted back to IP, it returns 184.108.40.206. Is this similar to this post? Or where exactly lies the problem I'm facing?
Answer: The primary problem is that toString(2) will only output as many digits as it needs, and it only needs 31. So when you're doing your string manipulation in binToIP, which relies on 32 digits, you're ending up with the wrong value.
I wouldn't do string manipulation in binToIP at all, I'd just do the converse of what you do in iptoBin: Parse it to a number, then do bit manipulation to get the individual bits, then form them into a string:
function binToIP(bin) {
  var value = parseInt(bin, 2);
  var block1 = (value & 0xFF000000) >> 24;
  var block2 = (value & 0x00FF0000) >> 16;
  var block3 = (value & 0x0000FF00) >> 8;
  var block4 = value & 0x000000FF;
  var ip = block1 + "." + block2 + "." + block3 + "." + block4;

  return ip;
}

Live example:

var testIP = '18.104.22.168';
snippet.log("Original IP: " + testIP);
var bin = ipToBin(testIP);
snippet.log("bin: " + bin);
var rebuiltIP = binToIP(bin);
snippet.log("Rebuilt IP : " + rebuiltIP);

function ipToBin(ip) {
  var block = ip.split('.');
  var res = 0;

  res += block[0] << 24;
  res += block[1] << 16;
  res += block[2] << 8;
  res += block[3] << 0;

  bin = res.toString(2);
  return bin;
}

function binToIP(bin) {
  var value = parseInt(bin, 2);
  var block1 = (value & 0xFF000000) >> 24;
  var block2 = (value & 0x00FF0000) >> 16;
  var block3 = (value & 0x0000FF00) >> 8;
  var block4 = value & 0x000000FF;
  var ip = block1 + "." + block2 + "." + block3 + "." + block4;

  return ip;
}


Composition of Endomorphism and its matrix (Proof)

Question: I need to show that if we have an endomorphism $\varphi$ defined in a vector space $V$ with a basis $B$, the statement $M_B(\varphi))^k = M_B(\varphi^k)$.
I tried to proof it by using induction over $k$ but I feel like I missed something. My working is below:

Let $V$ be a vector space with a basis $B =: b_1, \ldots, b_n$ and $\varphi$ an endomorphism in $V$ with the matrix $M_B(\varphi)$.
Show that $(M_B(\varphi))^k = M_B(\varphi^k)$ for $k = 1, \ldots, n$.
For $k = 1$: $(M_B(\varphi))^1 = M_B(\varphi^1) \iff (M_B(\varphi)) = M_B(\varphi)$, which is obviously true.
Now we assume that $(M_B(\varphi))^{k+1} = M_B(\varphi^{k+1})$
We see that $(M_B(\varphi))^{k+1} = M_B(\varphi)^k \cdot M_B(\varphi)$. From induction hypothesis, we know that $(M_B(\varphi))^k = M_B(\varphi^k)$, so we substitute and get:
$$(M_B(\varphi))^{k+1} = M_B(\varphi)^k \cdot M_B(\varphi) = M_B(\varphi^k) \cdot M_B(\varphi) = M_B(\varphi^{k+1})$$

I'm thankful for any help ;)
Comment: Which definition of the matrix $M$ of an endomorphism $f$ are you familiar with? What other properties of such matrices have you proven?
Comment: I know that there is a matrix for every endomoprhism in terms of a Basis. So we can just use the matrix as a representation of the given endomorphism.
Comment: i edited the post now with a screenshot of my work. I tried to proof the statement by induction but I feel like I'm missing something. maybe you can help me ;)
Answer: I think where it's lacking is the last equality:
$$M_B(\varphi^k) \cdot M_B(\varphi) = M_B(\varphi^{k+1}).$$
Every other step follows from associativity of matrix multiplication and composition of endomorphisms. At no other point do you use/claim any specific properties of the $M_B$ map. This is the step that tests your understanding of the $M_B$ map: what it means, how it's used, and what properties you've proven about it.
Now, how do you justify this step? It may be as simple as referring to a result proven previously in your course. It may look something like this:

Suppose $V_1, V_2, V_3$ are vector spaces over the same field, $B_1, B_2, B_3$ are respective bases for these spaces, and $T : V_1 \to V_2$ and $S : V_2 \to V_3$ are linear. Then,
  $$M_{B_1}^{B_3}(ST) = M_{B_2}^{B_3}(S)M_{B_1}^{B_2}(T).$$

(Here $M_{B_1}^{B_2}(T)$ refers to the matrix for the linear transformation $T$, from basis $B_1$, to basis $B_2$. I find that there's a lot of variety in how these matrices are notated, so the notation might not be the same for you.)
Applying this result is easy enough. Just take $V_1 = V_2 = V_3 = V$, $B_1 = B_2 = B_3 = B$, $S = \varphi^k$, and $T = \varphi$. Recall that $M_B$ is shorthand for $M_B^B$.
If you don't have access to the above result, then you'll have to prove the step manually, using the definition of $M_B$. Recall that, by definition,
$$M_B(\psi) = \left(\begin{array}{c|c}
& & & \\
[\psi(b_1)]_B & [\psi(b_2)]_B & \cdots & [\psi(b_n)]_B \\
& & &
\end{array}\right),$$
i.e. the matrix whose columns are the coordinate column vectors of $\psi(b_1), \psi(b_2), \ldots, \psi(b_n)$ with respect to $B$. Now, here's a result you probably do have access to:

If $\psi : V_1 \to V_2$ is linear, and $B_1, B_2$ are bases for $V_1, V_2$ respectively, then for all $v \in V_1$,
  $$[\psi(v)]_{B_2} = M_{B_1}^{B_2}(\psi) \cdot [v]_{B_1}. \tag{$\star$}$$

In fact, $(\star)$ characterises the matrix $M_{B_1}^{B_2}(\psi)$, and the unqique matrix satisfying $(\star)$ for all $v \in V_1$ is, in my mind, the most natural definition of $M_{B_1}^{B_2}(\psi)$.
So, we can use this to show $M_B(\varphi^k) \cdot M_B(\varphi) = M_B(\varphi^{k+1})$. To compute $M(\varphi^{k+1})$, we must first compute $[\varphi^{k+1} b_i]_B$ for $i = 1, \ldots, n$. Using the above result, we get
\begin{align*}
[\varphi^{k+1} b_i]_B &= [\varphi^k(\varphi(b_i))]_B \\
&= M_B(\varphi^k)[\varphi(b_i)]_B \\
&= M_B(\varphi^k) M_B(\varphi)[b_i]_B \\
&= M_B(\varphi^k) M_B(\varphi)e_i,
\end{align*}
where $e_i$ is the $i$th standard vector, since
$$b_i = 0b_1 + 0b_2 + \ldots + 0b_{i-1} + 1b_i + 0 b_{i+1} + \ldots + 0b_n.$$
But, multiplying a matrix (such as $M_B(\varphi^k) M_B(\varphi)$) by $e_i$ simply returns the $i$th column of such a matrix. By definition, the above vector is also the $i$th column of $M_B(\varphi^{k+1})$, hence
$$M_B(\varphi^k) M_B(\varphi) = M_B(\varphi^{k+1})$$
as all their columns are equal in this way.


how to count total number of divs inside another div using javascript

Question: How to count the total number of div elements that are contained in another div using javascript?
Comment: @alex: So what? This has nothing to do with jQuery, and the OP may not be in a situation where he can use jQuery, or indeed he/she may not want to use jQuery. Frankly, for a non-jQuery question I'd rather not have the help of people who only look at questions tagged with jQuery and not with JavaScript.
Comment: You weed out a lot of JavaScript developers (sort of me too) when you don't include the jQuery tag!
Answer: The getElementsByTagName() is not only a document method, but one that can run on any DOM element.

element.getElementsByTagName is
similar to
document.getElementsByTagName, except
that its search is restricted to those
elements which are descendants of the
specified element

see more at https://developer.mozilla.org/en/DOM/element.getElementsByTagName

So the actual code that does what you ask is
var container_div = document.getElementById('id_of_container_div');
var count = container_div.getElementsByTagName('div').length;

Comment: Haha, random moment where IE6 doesn't fall over.
Comment: @amphetamachine Then I wonder why this page: http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx says "this feature needs Microsoft Internet Explorer 5 or later" ;) `getElementsByTagName` **is** available in IE6
Comment: getElementsByTagName isn't available in browsers other than ones that use the Gecko engine. Try it in IE6.
Comment: I was pretty sure `getElementsByTagName` was in IE6?
Answer: You can use @davidcmoulton's handy Gist:
https://gist.github.com/davidcmoulton/a76949a5f35375cfbc24
I find it quite useful that it doesn't only count DIVs but also lists the count of all element types of your page.
Here is a copy of the Gist for further reference:
(function (window, undefined) {
//  Counts all DOM elements by name & logs resulting object to console.
var forEach = Array.prototype.forEach,
counter = {},

incrementElementCount = function (elementName) {
  if (counter.hasOwnProperty(elementName)) {
    counter[elementName] += 1;
  } else {
    counter[elementName] = 1;
  }
},

processNode = function (node) {
  var currentNode = node;
  if (currentNode.nodeType === currentNode.ELEMENT_NODE) {
    incrementElementCount(currentNode.nodeName);
    if (currentNode.hasChildNodes) {
      forEach.call(currentNode.childNodes, function (childNode) {
        if (childNode.nodeType === currentNode.ELEMENT_NODE) {
          processNode(childNode);
        }
      });
    }
  }
};

processNode(window.document.firstElementChild);

console.log(counter);

}(this));

Answer: There are many way to count divs element using jquery.
But most popular and simple way are:
$(document).ready(function(){
  var divCount = $("div").size();
  alert(divCount);
});

AND
$(document).ready(function(){
  var divCount = $("div").length;
  alert(divCount);
});

Its helpful for you


ionic loop lendo sensor e enviando para api

Question: Olá, preciso realizar leituras consecutivas de alguns sensores no ionic 3.x porém não posso deixar que isso trave completamente a aplicação. tentei fazer assim:

  async disparaLeituras(path_id) {
    while (true) {
      console.log('laço');
      try {
        var gyscope_data = await this.deviceMotion.getCurrentAcceleration();
        console.log(gyscope_data)
      } catch (e) {
        console.log(e); // 30
      }

    }
  }

porém isso fez com que aplicação travasse completamente, além do sensor de aceleração eu verifico o giroscopio e o gps tambem, todos eles retornam promisses, alguém sabe a forma correta de proceder?
Comment: O jeito mais fácil é usar como uma promise padrão em vez de usar `await`, mas talvez isso não ajude no seu caso de uso. O que você vai fazer com esses dados depois?
Comment: eu envio pra uma api dps, se eu tirar o wait vou diparar varias promisses e vai acabar travando tbm
Comment: talze usar recurção seja uma soluçao, dps q a promisse realiza uma leitura ela dispara a proxima
Answer: De fato, fazer diversas requisições por segundos pode prejudicar o desempenho do app e do backend.
Você pode usar o watchAcceleration e os operadores do rxjs para limitar e / ou agrupar os dados do acelerômetro.
Algunas opções de solução são

Juntar leituras por n segundos e enviar em batch (com bufferTime e mergeMap):

import { bufferTime, mergeMap } from 'rxjs/operators';

(...)

this.deviceMotion.watchAcceleration().pipe(
    bufferTime(2000),
    mergeMap(groupedData => this.apiService.sendBatchData(groupedData)),
).subscribe(response => {
    // Response da api
});

Coletar a última leitura a cada n segundos, descartando leituras intermediárias (com debounceTime):

import { debounceTime, mergeMap } from 'rxjs/operators';

(...)

this.deviceMotion.watchAcceleration().pipe(
    debounceTime(2000),
    mergeMap(singleData => this.apiService.sendData(singleData)),
).subscribe(response => {
    // Response da api
});

Entre outras. A solução ideal vai depender do seu caso de uso.
Comment: o debouncetime seria o equivalente a rodar uma funçao de litura e envio a cada n segundos?
Comment: Não diria que é equivalente. Pode até ser parecido. Mas usando o `watchAcceleration` você muda o fluxo do programa e, ao invés de **pedir** e esperar a resposta do acelerômetro a cada _n_ millisegundos, **você será notificado sempre que houver uma atualização**. Então, você pode fazer o que quiser com os dados que chegaram: descartar, agrupar, etc,.de forma muito mais declarativa.


How to preserve external IPs through gateway to keep using Fail2Ban

Question: I have a CentOS 7 box with 2 NICs acting as a gateway; one NIC is connected to the internet while the other NIC is connected to our LAN.
The first NIC belongs to the 'external' zone of firewalld, it has masquerading on and is set to forward port 22, 80 and 443 to those boxes inside the internal network that manage SSH and the web servers; let's say that, from the internet, the box appears as "example.com" at address "126.96.36.199" while its name in the LAN is "gateway.lan" with address "192.168.1.1".
Everything works, with a significant caveat; since we want to be able to connect via SSH using the internet name of the box (ssh example.com) also from within the LAN (where the SSH box is named "server.lan" and has address 192.168.1.10), the only way to make this work seems to be setting a rule in firewalld's 'internal' zone forwarding all accesses to port 22 of "18.104.22.168" back to port 22 of the SSH box:
internal (active)
target: default
icmp-block-inversion: no
interfaces: XXXXXX
sources:
services: dns
ports:
protocols:
masquerade: yes
forward-ports:
source-ports:
icmp-blocks:
rich rules:
      rule family="ipv4" destination address="126.96.36.199" forward-port port="22" protocol="tcp" to-port="22" to-addr="192.168.1.10"

The rule alone does not work unless masquerading is on for the 'internal' zone; unfortunately, this also obviously causes the external IPs that hammer that box trying to brute-force a root password to appear as coming from "192.168.1.1" (the "gateway.lan" address) in the logs of "server.lan", which makes it impossible to use Fail2Ban on the "server.lan" box to hamper the thousands of daily attempted accesses.
What am I doing wrong? I think enabling masquerading on the "internal" zone is conceptually wrong but I could find no other way the make the firewalld rule work. I have no qualms in keeping the masquerading on but I'd like to know how Fail2Ban may be then made to work when behind a gateway...
Any advice to any other way to make a configuration like this work as I'm expecting?
Comment: Why aren't you using IPv6?
Comment: That is out of my reach; I have to accommodate a situation within a pre-existing network which is IPv4 only.
Answer: Ah, we did it! And it was relatively easy (well, once you know how)...
We had correctly surmised that masquerading on the "internal" zone was not to be globally enabled but it was to be limited to packets originating from the LAN that are routed towards the public IP.
This implies not indiscriminately enabling it with --add-masquerade for the whole zone but using masquerade INSIDE a specific rich rule, in the following form:
firewall-cmd --zone=internal --permanent --add-rich-rule='rule family=ipv4 source address=192.168.1.0/24 destination address=192.168.1.10 masquerade'

For a while we were fooled by the fact that we insisted on using the public IP "18.104.22.168" as "destination address" instead of the internal one "192.168.1.10" in the rule; we didn't get that, once traveling through the "internal" zone, packets targeting port 22 of "184.108.40.206" are already converted by the rich rule into the LAN address of the SSH box. Moreover, this syntax does NOT allow specifying a port.
The final status for the "internal" zone is as follows:
internal (active)
target: default
icmp-block-inversion: no
interfaces: XXXXXX
sources:
services: dns
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
      rule family="ipv4" destination address="126.96.36.199" forward-port port="22" protocol="tcp" to-port="22" to-addr="192.168.1.10"
      rule family="ipv4" source address="192.168.1.0/24" destination address="192.168.1.10" masquerade

which:

correctly reroutes SSH access from the internet to the SSH box - of course this also requires in the "external" zone a forward rule for port 22 towards the same port on the "internal" one;
lets LAN machines indifferently SSH into the box with its public or LAN name;
does not mask the addresses of malicious SSH attempts from the internet to the box  so that Fail2Ban can perform its job.

Cheers!


Dividing polynomials with two unknowns and finding the unknowns

Question: The question I'm trying to solve is: when the function $f(x)= mx^3+(k-4)x^2+k^2x-7$ is divided by $(x+2)$ the remainder is $-111$. And when it is divided by $(x-4)$ the remainder is $489$. Determine all the possible values of $m$ and $k$.
So, I tried using the remainder theorem with both remainders like $P(-2)= -111$ and I plugged in $-2$ for $x$ and put $-111$ on the right side of the equal sign. I got the equation $k^2-2k+4m-44$. I got the same format for the second equation for $P(4)$. My question is: What do I do with two unknowns? I tried keeping the $k^2$ on the left side and moving everything to the right, to square root it but it got me nowhere.
Comment: That's a system of two equations to solve for two unknonws. Try for example to eliminate one of variables between the equations, then you have one equation in one unknown to solve.
Comment: Use latex for formulas please.
Comment: (1) what was the second equation you got ? (2) why you want to solve this ? (3) where was this taken from ? [[ this will enable giving Answers suitable to your Case ]]
Answer: As you've suggested, we can apply the Remainder Theorem in each case. For the remainder upon division by $(x+2)$, we have
\begin{align}
-111 = f(-2) &= m(-2)^3 + (k-4)(-2)^2 + k^2(-2) - 7 \\
&= -8m + 4(k-4) - 2k^2 - 7
\end{align}
or
$$
4m + k^2 - 2k - 44 = 0.
\tag{1}
$$
Analogously, for the remainder upon division by $(x-4)$, we have
\begin{align}
489 = f(4) &= m(4)^3 + (k-4)(4)^2 + k^2(4) - 7 \\
&= 64m + 16(k-4) + 4k^2 - 7
\end{align}
or
$$
16m + k^2 + 4k - 140 = 0.
\tag{2}
$$
Subtracting Equation $(1)$ from $(2)$ yields $12m + 6k = 96$ or, with an eye towards substituting back into Equation $(1)$,
$$
4m = 32 - 2k.
\tag{3}
$$
Now, Equation $(1)$ looks like
$$
(32 - 2k) + k^2 - 2k - 44 = 0
$$
or
$$
k^2 - 4k - 12 = 0.
$$
This quadratic equation has two solutions, namely
$$
k = -2
\quad\text{or}\quad
k = 6.
$$
Substituting back into Equation $(3)$, these correspond to
$$
m = 9
\quad\text{or}\quad
m = 5,
$$
respectively.
Putting this all together, the only solutions are
$$
(m, k) = (9, -2)
\quad\text{or}\quad
(m, k) = (5, 6),
$$
yielding the cubic polynomials
$$
f(x) = 9x^3 - 6x^2 + 4x - 7
$$
or
$$
f(x) = 5x^3 + 2x^2 + 36x - 7.
$$
Answer: For an alternative approach, based on $P(-2) = -111$, $P(4) = 489$, and also $P(0) = -7$, the unique quadratic interpolation polynomial through the $3$ points is $Q(x) = 12 x^2 + 76 x - 7$.
$P(x)-Q(x)$ is a cubic with leading coefficient $m$ which must vanish at $x=-2,0,4$, so:
$$
\begin{align}
P(x) &= Q(x) + m\,x(x+2)(x-4)
\\ &= m x^3 - 2 (m - 6) x^2 + 4 (19 - 2 m) x - 7
\end{align}
$$
Identifying coefficients against $P(x) = mx^3+(k-4)x^2+k^2x-7$:
$$
\begin{cases}
\begin{align}
-2(m-6) &= k - 4
\\ 4 (19 - 2 m) &= k^2
\end{align}
\end{cases}
$$
Eliminating $k$ between the two equations:
$$
4 (19 - 2 m) = \big(4-2(m-6)\big)^2 \;\;\iff\;\; m^2 - 14 m + 45 = 0 \;\;\iff\;\; m \in \{5, 9\}
$$


Solve equations by using Matrix Inverse Method.

Question: Answer in the book and my answer is different.Can any one help me which one is correct.
<code>           Solve the following system of equations by using Matrix Inverse Method.
           3x+ 4y+ 7z= 14
           2x-y+ 3z= 4
           2x + 2y - 3z = 0
</code>
Answer form the book
My Answer
Comment: You've confused minor with cofactor.
Comment: can you tell me which one is correct answer from the book or my answer ? thank you so much
Comment: Use [Octave Online](https://octave-online.net/) with MATLAB's syntax to verify.
Comment: Just multiply out both "solutions" by hand.  The wrong answer will quickly reveal itself by plugging in $x,y,z$.
Answer: The best method to check is to plug in the solution in the original system and verify whether or not it work. If not check that $AA^{-1}=I$.
Answer: The answer from the book is not consistent with the proble. The lower left entry of the matrix should be $2$, not $1$. So, it is normal that whoever wrote it got a different answer.
Comment: I think  left entry matrix should be 2  not 1  ,
Comment: @BishalThapa That's what I meant. Sorry. I've edited my answer.
Comment: That's okay no problem, Can you tell me my answer is correct ?
Comment: @BishalThapa Almost. You computed $A^{-1}$ correctly, but the solution is $\frac{62}{81}$, $\frac{76}{81}$, and $\frac{92}{81}$.
Comment: Thank you so so much @Jose Carlos Santos    You saved me


Polynomial with rational roots

Question: Let $f:\mathbb{R} \to \mathbb{R}$ be a polynomial function with rational coefficients  and degree $3$. If the  graphic of $f$  is tangent to the  $x$ axis. Show that all zeros of $f$ are rational numbers.
If $\alpha$ is a zero of $f$, i.e., if $f(\alpha)=0$ and the graph of $f$ is tangent to the $x$ axis in this point, then $\alpha$ has even multiplicity, but I don't know how I can conclude this question. Someone can help-me?
Thanks a lot.
Answer: If $\alpha$ is a root where the graph of $f$ is tangent to the $x$ axis, then $\alpha$ is a root of multiplicity $\ge 2$ (not necessarily even).
Case 1: $\alpha$ has multiplicity $3$.  Then $\alpha$ is a root of the polynomial $f''(x)$ which has degree $1$ and rational coefficients, and therefore $\alpha$ is rational.
Case 2: $\alpha$ has multiplicity $2$.  Then the gcd of $f(x)$ and $f'(x)$ is $x-\alpha$.  But the gcd of two polynomials with rational coefficients has rational coefficients, so $\alpha$ must be rational.
Answer: Hint Since $$f(x) = A x^3 + B x^2 + C x + D$$ is rational and scaling a polynomial doesn't change its roots, we can replace $f$ with $A^{-1} f$ and hence assume it is monic:
$$f(x) = x^3 + b x^2 + c x + d .$$
Similarly, $f(x)$ has rational roots iff $f(x - \frac{b}{3})$ does, so we may as well prove the claim for $f(x - \frac{b}{3})$, but expanding gives that $f(x - \frac{b}{3})$ is rational and has zero quadratic coefficient, so we may as well assume $f(x)$ has the form
$$f(x) = x^3 + p x + q$$ for rational $p, q$ (we call such a cubic depressed).
Now, since the root $\alpha$ has multiplicity $\geq 2$, $f$ must have the form $$f(x) = (x - \alpha)^2 (x - \beta) .$$
Expand and compare like terms in $x$.

Doing so gives $\beta = -2 \alpha$ (so that $\beta$ is rational iff $\alpha$ is) and thus $$p = -3 \alpha^2, q = 2 \alpha^3.$$ Thus, either $\alpha = 0$ or (if $p \neq 0$) $$\alpha = -\frac{3 q}{2 p}$$ and either way $\alpha$ is rational. (If we like, we can back-substitute to find explicit rational expressions for $\alpha, \beta$ in terms of $A, B, C, D$.)

Polynomial with rational roots


Zero-truncated Sichel distribution in R

Question: I'm trying to fit the GAMLSS library's Sichel distribution to some zero-truncated data, but the only way to get the function to work is to include the zero-class anyway but give it a frequency of 0, which doesn't take into account the zero-truncated nature of my data. Can anyone suggest a way to properly "redistribute" the zero-class's probability to the remaining probabilities (or some other, better, course of action using Sichel)?
If you run the following example, you'll see that sum(pdf2) equals 1, but that the zero class that has a probability in my case of 0 is still allocated around 27% of the cum probability:
Counts = data.frame(n = c(0,1,2,3,4,5,6,7,8,9,10),
                    freq = c(0,182479,76986,44859,24315,49,100,490,106,0,2))

gamlss(n~1,family=SICHEL, control=gamlss.control(n.cyc=50),data=Counts )

pdf2 = dSICHEL(x=with(Counts, n), mu = 1.610, sigma = 98.43, nu = 3.315)

print( with(Counts, cbind(n, freq, fitted=pdf2*sum(freq))), dig=9)

sum(pdf2)

Answer: In R, load the package gamlss.tr (for fitting truncated distributions), then:
y<-rSICHELtr(1000,2,0.5,-1)
hist(y)
gen.trun(par=0,family="SICHEL", type="left",delta=0.0001)
m1<-gamlss(y~1,family=SICHELtr)
summary(m1)

The above code generates a sample of 1000 from the truncated SICHEL distribution,
then fits it.  Note in the simulation mu=2, sigma=0.5 and nu=-1.
In the summary fitted model gives fitted log(mu), log(sigma) and nu.
Comment: Welcome to the site, @Robert. We prefer if you don't sign your posts; note that your avatar & username (w/ a link to your userpage) are added automatically to your posts. Since you're new here, you'll want to read our [about page](http://stats.stackexchange.com/about) & our [FAQ](http://stats.stackexchange.com/faq), which contain info like this about CV.
Answer: By zero-truncated, do you mean that any data that would have had a 0 as a response is just missing? In that case, can't you just put the 0s in?
Or do you mean that some proportion of the time, instead of getting a sensical answer, you get a 0 instead? That sounds like zero-inflation to me. In that case, there are zero-inflated poisson and similar in GAMLSS.
I don't know of a zero-inflated Sichel, and there's nothing in GAMLSS for it, but is there a particularly good reason for using the Sichel distribution for your data? Does it reflect the underlying process particularly well? (I believe that the Sichel represents a mixture model of Poissons, where the meta-distribution is distributed as Inverse Gaussian...)
Comment: By zero-truncated, I mean that the probability of a zero-count is zero. My data are the count of items purchased _per transaction_ at a convenience store over a five-day period--obviously there's at least one item being bought per purchase (but usually fewer than, say, 20). The schema looks something like: DATE, TRANSACTION_ID, COUNT_OF_PURCHASES As to Sichel, I do have reason to believe that that distribution might provide a good fit, but I'm trying several others as well (e.g., ZTNB). Thanks for your reply. --Jeff
Comment: Oh, I see. ZTNB seems viable. Or you could model visits *including* unobserved non-purchases, as you originally noted. That would basically be a free parameter, but if Sichel is describing some other aspect of the underlying behavior, it might be worth it.
Comment: Incidentally, you should have responded to my answer, not in a separate answer. And if you like the answer, please up-vote it, and if it actually answers the question to your satisfaction, accept it. (Likewise, your follow-up should have been a comment on your question, not an answer.) Welcome to Stack Exchange! :)
Comment: Follow-up: 1. The SICHEL() function is in the gamlss.dist package. 2. Would a simple (and correct!) method to adjust the > 0 probabilities be to divide them by (1-.27)? --Jeff
Answer: The distribution of the zero truncated law is
$$ \mathbb P(X = k | X > 0) = { \mathbb P(X = k) \over 1 - \mathbb P(X=0) },$$
for $k>0$.
So in R it is given by dSICHEL( x, mu, sigma, nu)/(1-dSICHEL(0, mu, sigma, nu)) and its log by dSICHEL( x, mu, sigma, nu, log=TRUE)-log(1-dSICHEL(0, mu, sigma,nu))... it is then easy to compute the log-likelihood for given parameters $\mu, \sigma, \nu$. You could try to maximize it using nlm or optim.

Zero-truncated Sichel distribution in R


Is there a name for positive random variables that add up to 1? Is "Convex random variables" phrase appropriate for that?

Question: Is there a name for positive random variables that add up to 1? Is "Convex random variables" phrase appropriate for that? Extending it a bit further, if a weighted Harmonic mean has positive weights chosen randomly such that sum of weights =1, can we say it is a "Harmonic mean with convex weights?"
Comment: Why do you need to specify it explicitly? Weighted means *always* have positive weights that sum to 1 (possibly after a rescaling implicit in their definition), in my experience. I would rather specify "harmonic mean with *random* weights".
Comment: https://en.wikipedia.org/wiki/Compositional_data
Answer: The random variables are on a simplex, in this case a probability simplex:
https://en.wikipedia.org/wiki/Simplex
With respect to the weighted Harmonic mean, I would say:  "a harmonic mean with weights on a probability simplex"... or, more likely in real life, "a harmonic mean with positive weights that sum to one." :)


Solve differential equation. Not able to apply any standard formula

Question: $(D^2-6D+13)y=3^x.$ How to approach this problem? All of the formulas i have learnt till now do not fit in this problem
Comment: Hint: $3^x=e^{\ln(3) x}.$
Comment: It would be useful to clarify exactly what's confusing you in the original post, so you can receive the best responses.
Comment: What have you learnt so far? Does this look similar to problems you've seen before? Have you seen $D$ previously, and what does it mean?
Comment: ofcourse i know that stuff. I am confused about the rhs part. All the questions i have solved till now didn't have a similar rhs
Comment: is $D=\frac{dy}{dx}$?
Comment: I suppose $D$ is $\frac{d}{dx},$ so that $D^2 y=\frac{d^2y}{dx^2}$. Is that correct?
Answer: $$y'' - 6y' + 13y = 3^x$$
First of all solve the homogeneous equation
$$y'' - 6y' + 13y = 0$$
Whose characteristic equation is
$$z^2 - 6z + 13 = 0$$
$$\mathbf{z} = \frac{6\pm\sqrt{36 - 52}}{2} = \frac{6\pm 2i}{2}$$
$$z_0 = 3+2i$$
$$z_1 = 3-2i$$
By the theoryuld know how to arrange them to create the homogeneous solution $Y_o$.
After this you need the particular solution.
Write $3^X$ as $e^{x\ln(3)}$ and then use the function $Y_p = A e^{Bx}$, differentiate and solve for $A$ and $B$ et voilà.
$$Y = Y_o + Y_p$$


Haskell--Recursive calls on Lists

Question: I have a function onemove that I am recursively calling upon a list moves.  The function onemove returns a 3-tuple (Int,[Char],[[Char]]), namely time, captures, and board .  I would like to call the function onemove on the input tuple for each move in the moves list.  Below I have provided my code thus far:
    makemoves :: (Int,[Char],[[Char]],[(Int,Int)]) -> (Int,[Char],[[Char]])

    makemoves (time, captures, board, [] ) = (time, captures, board)
    makemoves (time, captures, board, (moveFrom, moveTo):moves )
        | checkerAlive board = makemoves (onemove (time, captures, board, move:moves))
        | otherwise          = resetGame (time, captures, board)
        where    copyTime = time
                 copyCaptures = captures
                 copyBoard = board
                 move = (moveFrom,moveTo)
                 tempTuple = onemoving (time, captures, board, move)

How might I call the function makemoves recursively?  onemovereturns a 3-tuple, while makemoves is expecting a 4-tuple, which is the returned 3-tuple plus the next move.  Thanks!
Comment: If this typechecks, why is the type signature of `onemove` the same as `makemoves`?
Comment: I don't get a few things from your code. For example why do you have a `copyBoard = board`? Also instead of defining `move` in the `where` clause you can use `@` patterns: `move@(moveFrom, moveTo):moves`. Regarding your problem, there are some circumstances where it's easier to write a helper function that returns redundant information and write the actual function by calling it and dropping the not-needed information. Lazyness will also avoid to actually compute information that isn't really required.
Answer:
onemovereturns a 3-tuple, while makemoves is expecting a 4-tuple,
  which is the returned 3-tuple plus the next move. Thanks!

No, it's expecting a list of the remaining moves, which you already have in moves.
Remember the other day, when I told you to have your functions take multiple arguments instead of all its arguments in a single tuple? This is exactly why. You should do that now:
makemoves :: [(Int,Int)] -> (Int,[Char],[[Char]]) -> (Int,[Char],[[Char]])

makemoves [] (time, captures, board) = (time, captures, board)
makemoves (move:moves) (time, captures, board)
    | checkerAlive board = makemoves moves (onemove (time, captures, board, move:moves))
    | otherwise          = resetGame (time, captures, board)

I'm not sure what all those where clauses are for; none of them are used.
EDIT: Ignore the below, actually, since you need early-exit logic based on the checkerAlive function. It can still be written as a fold, but is probably more work than it's worth at this point.
Also, what you've written here is a very common recursion pattern in functional programming called a "fold". This whole thing can be rewritten as:
makemoves :: [(Int,Int)] -> (Int,[Char],[[Char]]) -> (Int,[Char],[[Char]])
makemoves moves env = foldr onemoveOrReset env moves
onemoveOrReset :: (Int,Int) -> (Int,[Char],[[Char]]) -> (Int,[Char],[[Char]])

Comment: @Dev: that requirement is rather obnoxious. _Sometimes_ it is reasonable to have tuples instead of curried functions, but Haskell programmers generally very much prefer the former. If your professor knows anything about proper Haskell programming, they'll happily accept a curried solution as well.
Comment: @Dev I agree with leftaroundabout, as a Haskeller I would much prefer those tuples split up, given names, possibly even full blown record types as it makes the code far more readable, understandable, and clean.  Using giant tuples is usually a code smell in Haskell.  There are exceptions to this rule, but in general a 2-tuple is about as high as you want to go.  I would say that the primary reason for this is because the standard Haskell libraries do not have many tools for working with larger tuples, and that after that point it really helps to give fields explicit names.
Comment: Unfortuantely, my professor sets the requirements on the input/output tuple that is declared so I must work around the idea in some way
Comment: @Dev you might want to look at [Data.Tuple.Curry](https://hackage.haskell.org/package/tuple-0.2.0.1/docs/Data-Tuple-Curry.html)
Answer: Lines like
          copyTime = time

are completely superfluent in Haskell: it's never meaningful to copy anything. There's just values, no "objects" which might change at some point, and a value can be used from anywhere. So your entire where block is useless.
To get to your problem, let's consider a simpler example: not moves, but simple numbers you're trying to add. Written with tuples (though, as said by Mark Whitfield, curried functions are better!)
addOne :: (Int,Int) -> Int
addOne (num,inc) = num + inc

makeAdds :: (Int, [Int]) -> Int
makeAdds (num, []) = num

Ok, now the recursive case. At the moment, in your code you have basically
makeAdds (num, inc:incs) = makeAdds (addOne (num, inc:incs))

This is wrong for two reasons:

addOne can't use a list, yet you're handing it inc:incs – the very list you've just got from input. Obviously, you want to use just the head element, i.e. inc alone.
makeAdds needs two arguments, the second being a list. Well, obviously that's the remaining list!
makeAdds (num, inc:incs) = makeAdds (addOne (num, inc), incs)

easy enough.
That said, the "correct" version of all this would of course be
addOne :: Int -> Int -> Int
addOne = (+)                   -- Yeah, you can do that.

makeAdds :: [Int] -> Int -> Int  -- Observe I've switched the order:
                                 -- "state" arguments best come last, useful with partial application

makeAdds [] = id
makeAdds (inc:incs) = makeAdds incs . addOne inc

Answer: So I figured it out, here is the solution
     makemoves (time, captures, board, (moveFrom, moveTo):moves )
        | checkerAlive board = makemoves (newTime,newCaptures,newBoard,moves)
        | otherwise          = resetGame (time, captures, board)
       where move = (moveFrom,moveTo)
             (newTime,newCaptures,newBoard) = onemoving (time, captures, board, move)

You must first create a temp holder for the first move, thus (newTime,newCaptures,newBoard) then pass that temp holder onto the next move in the moves list with the call to makemoves
Comment: Note that you can omit the `(moveFrom, moveTo)` tuple and just match `move:moves` immediately, since you don't use either `moveFrom` or `moveTo` on its own. Apart from that, this is pretty much as good as it gets with those ugly un-curried functions.

Haskell--Recursive calls on Lists


OBIEE how to modify analysis table

Question: I have an analyis pivot table

and here is the result

Is there any way to modidify this analysis pivot table to be like this:
Answer:
Please see the above image.

Create the sum in criteria itself.
In column labels click on that summation and select none.
Create a dummy column having string 'Total', and arrange everything like below image.
Comment: Also u can edit the column headings in criteria only as per your requirement.
Comment: very nice answer :)

OBIEE how to modify analysis table


Centering a form in Delphi for PHP

Question: I have created a Delphi for PHP page in RadPHP. How can I make it center in the browser's window?
Is it possible to achieve it using only PHP code?
Comment: English it's not my native language, so that probably that's why I didn't understood... afaik DelphiForPhp it's and IDE/RAD that provide a graphical interface for the developer. At the far end, the final output should be php+html+css+js, it's that correct ? can you post also some code ? or a screenshot at least....
Comment: i just want the php code to make the page center
Answer: Form cannot be centered by only using php, because php is server scripting language and it cannot determine the size of client area (available space) in the browser. This can only be done by using CSS and JavaScript. Try that approach.
Answer: You can center an RPCL webpage with the following settings in your Page subclass:

Alignment: agCenter.
Layout.Type: REL_XY_LAYOUT.

Centering a form in Delphi for PHP


Find the max and min value of $f(x,y)=3x-4y$ over $x^2+4y^2 \leq 13$

Question: I am required to find the maximum and minimum values of $f(x,y)=3x-4y$
on the region $x^2+4y^2 \leq 13$?
Can anyone guide me how to do this kind of question?
Appreciate your help!
Comment: Try the method of Lagrange Multipliers (e.g. Example 4): http://tutorial.math.lamar.edu/Classes/CalcIII/LagrangeMultipliers.aspx
Answer: We do it in a calculus-free way. Consider the line $3x-4y=w$, as $w$ varies.  As $w$ changes, the line moves parallel to itself. When $w$ is large negative, the line will be far from our elliptical region.As $w$ increases, it will get closer, until it finally touches the boundary of the region. Then, as $w$ increases further, the line keeps passing through the region, until for suitable $w$ it again just touches the region.
So for the min/max values of $w$, we want the line $3x-4y=w$ to ne tangent to the ellipse. So the line and ellipse should meet in a double point. Thus
$$\left(\frac{4y+w}{3}\right)^2 +4y^2=13$$
has a double root. Equivalently, $52y^2+8wy+w^2-117=0$ has a double root.
The condition for this is that the discriminant is $0$. We obtain the equation
$$64w^2=(4)(52)(w^2-117)$$
This simplifies to $9w^2=9(13^2)$, giving $w=\pm 13$.
Remark: If we are in a calculus mood, we can note that the line $3x-4y=w$ has slope $\frac{3}{4}$. The slope $\frac{dy}{dx}$ of the tangent line to $x^2+4y^2=13$ at  $(x,y)$ is given by $2x+8y\frac{dy}{dx}=0$. So at the point of tangency we have $x=-3y$. Now we can solve for $x$ and $y$.
Answer: Note that the constraint set is compact, hence a minimiser and a maximiser exist.
Also note that $f$ has non zero gradient everywhere, hence it has no local minimiser or maximiser. Consequently, the constraint must be active at
a minimiser or maximiser.
It follows that you need only look for a minimiser or maximiser on the set
$x^2+4 y^2 = 13$. You can use Lagrange multipliers for this.
Alternative approach:
Let $z=2y$, then the problem becomes
$\min \{ 3x-2z | x^2+z^2 \le 13 \}$
(and $\max$).
It should be clear from a picture that the solution must lie on the line through the origin in the direction $(3,-2)$, that is, the solution must have
the form $(x,z)=(3t,-2t)$ for some $t$. It is not too hard to check that
the minimising and maximising values of $t$ are $-1$ and $1$ respectively
and these correspond to costs of $\pm 13$.
Hence the extremisers in the original coordinates are
$(-3,1)$ and $(3,-1)$ respectively.
Answer: Hint-1: Use Lagrange multipliers to solve it.
Hint-2: Try to find out the general equation of the ellipse $x^2+4y^2=13$. Now, compare that tangent equation with the given equation of the line, and try to find out the point where tangent touches the ellipse. There will be a quadratic equation in terms of $x$. After solving it you will find four points. Two of them give you the max and other two will be the min.


Golang ReverseProxy HTTP Timeout

Question: I have a go based single host reverse proxy being used in my application. The request to the downstream service that the proxy makes gets timedout and cancelled automatically after 30 seconds.
After looking at the http package github, I found a similar issue: https://github.com/golang/go/issues/28876.
The suggested response is that the HTTP timeout needs to be set, not the TCP dialing part, but I'm not able to find the configuration to do that.
Need some help on that.
timeout := service.httpConfig.ProxyTimeout / 1000
proxy := httputil.NewSingleHostReverseProxy(clusterURL)
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.ResponseHeaderTimeout = time.Duration(timeout) * time.Second

proxy.ServeHTTP(c.Writer, c.Request)

Doing this didn't help. The request always throws a 504 after 30 seconds even if my ProxyTimeout is 180,000.
Answer: try to replace Transport, like this
proxy := httputil.NewSingleHostReverseProxy(clusterURL)

proxy.Transport = &http.Transport{
    Proxy: http.ProxyFromEnvironment,
    Dial: (&net.Dialer{
        Timeout:   180 * time.Second,
        KeepAlive: 180 * time.Second,
    }).DialContext,
    TLSHandshakeTimeout: 180 * time.Second,
}

proxy.ServeHTTP(c.Writer, c.Request)

and check timeout on *http.Server
httpServer := &http.Server{
  ReadTimeout:  180 * time.Second,
  WriteTimeout: 180 * time.Second,
}

Golang ReverseProxy HTTP Timeout


A/B Test from two distributions with unknown means

Question: I will run a experiment to check if a given change, represent some significance in user interactions. I have two sets, sampled from two groups, one called control which counts the number of interactions from 30 sampled users in control group, and I have treatment which counts the number of interactions from 30 sampled users with a test feature. They are given in the Python code below
import numpy as np

control   = np.array([1, 0, 1, 3, 2, 1, 0, 1, 3, 2, 1, 0, 1, 3, 2, 1, 0, 1, 3, 2, 1, 0, 1, 3, 2, 1, 0, 1, 3, 2])
treatment = np.array([0, 1, 3, 2, 1, 2, 1, 3, 2, 1, 0, 2, 3, 2, 1, 0, 2, 3, 2, 1, 0, 2, 3, 2, 1, 0, 2, 3, 2, 4])

For this test i will use the following parameters
Practical Significant Boundary: $d_{min} = 0.05$
Significance level $\alpha = 0.05$
d_min = 0.05
alpha = 0.05

I want to check if in average there is no usage difference between the two groups. Then I state the  null hypothesis as
$H_0: \mu_t == \mu_c \implies d = 0$
where $\mu$ is the average of control group (c) or treatment group (t) and $d$ the difference $d = \mu_t - \mu_c$.
mu_c = control.mean()
mu_t = treatment.mean()
d = mu_t - mu_c

By the characteristics of the data, I will use the t-test for evaluation. I will assume the variance is the same between both groups, that will give me the following computation to test statistics.
n_c = len(control) # Number of samples in control
n_t = len(treatment) # Number of samples in treatment

df = n_c - 1 + n_t - 1 # Degree of freedom

# squared sum of errors from control group
SS_c = np.sum((control - mu_c)**2)

# squared sum of errors from treatment group
SS_t = np.sum((treatment - mu_t)**2)

# Pooled standard error
S_pool = np.sqrt((SS_c + SS_t)/df)

# Test statistics for t-distribution
TS = d / (S_pool * np.sqrt(1/n_c + 1/n_t))

Now I will verify if the test confirms or rejects the null hypothesis. For that I compute the t_alpha with 58 degrees of freedom,
import scipy.stats as stats

t_alpha = stats.t.ppf(1-alpha/2, df)

TS > t_alpha or TS < -t_alpha
# Returns true

Since TS is out of the boundaries of t_alpha we can reject the null hypothesis.
Now I will verify if the result is practically significant, that is if my confidence interval including the standard error intersects somehow the significance region. For that I need to estimate the margin error ($m$), then compute the confidence interval from $d \pm m$
m = t_alpha * S_pool
ci = np.array([d - m, d + m])

Just for reminder d is the difference between the averages from two groups (control and treatment).
To visualize we can build the given plot.
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 3))
ax = fig.add_subplot(111)
ax.vlines(0, -1, 1)
ax.vlines([-d_min, d_min], -1, 1, linestyles='dashed', label="Significant boundary");
ax.plot(d, 0,'b.', label="Center Confidence Interval");
ax.hlines(0, *ci, 'b', label="Confidence Interval");
ax.set_title("Significance");
plt.legend();

Since the confidence interval overlaps with the significant boundary (totally), even cross the $0$, I cannot assume that this test has practical significance, hence I would reject it.
The problem is: I was not expecting an interval SO large. Probably I just have used a wrong formula for margin error, but it seems correct. Any help to go forward in this is welcome.
Comment: Why do you think it is wrong? It seems reasonable. You have very few observations. Try just using an online calculator to verify.
Answer: It's always a good idea to use existing implementations to check, especially for something as common as a t-test.
import statsmodels.stats.weightstats as sm
test = sm.CompareMeans(sm.DescrStatsW(treatment), sm.DescrStatsW(control))
test.ttest_ind()
>>> TtestResult(statistic=1.0934, pvalue=0.2788, df=58.0)

test.tconfint_diff()
>>> (-0.2492, 0.8492)

Note that both contradict the results you have obtained. A statistical language like R will confirm this and give you everything you want to know in a single line of code:
t.test(treatment, control, var.equal = TRUE)
>   Two Sample t-test
> t = 1.0934, df = 58, p-value = 0.2788
> 95 percent confidence interval:
>  -0.2492  0.8492

Clearly you have at least one mistake in your formulae. I'm not sure why you end up with TS outside of the critical values because for me this is not the case when re-running your code:
TS = d / (S_pool * np.sqrt(1/n_c + 1/n_t))  # 1.0934
t_alpha = stats.t.ppf(1-alpha/2, df)        # 2.0017
TS > t_alpha or TS < -t_alpha
>>> False

The problem in your confidence interval calculation is that what you've called "pooled standard error" is actually the pooled standard deviation. The standard error is this quantity scaled by the square root of $n$ and also the denominator of your t statistic: S_pool * np.sqrt(1/n_c + 1/n_t). Using that you'll end up with the correct CI:
SE_pool = S_pool * np.sqrt(1/n_c + 1/n_t)
m = t_alpha * SE_pool
ci = np.array([d - m, d + m])
>>> array([-0.2492,  0.8492])

Finally, it's not clear what you mean by 'practical significance boundary'. The most liberal interpretation (and how you started your implementation) is that you want to test $H_0: \mu_t-\mu_c = 0$ and if you observe d > d_min you conclude that the effect might be practically relevant - if it were statistically significant. A more stringent interpretation, where you seem to want to go with your confidence interval, is that you actually want to test $H_0: \mu_t-\mu_c\le d_{min}$ which is the same as a $1-\alpha$ interval excluding d_min. I don't know which of these two you actually want, just highlighting that they are not the same. Neither of the null hypotheses can be rejected at the specified $\alpha$ in your case.
Comment: Indeed. I made a small mistake while transcribing the data from my local file to the SO. And here, at StackOverflow, with the "wrong" data, the **test statistics** confirms the null hypothesis. Good point is that using both Python Libs and R the test statistics values (the TS variable), are the same. it means that equation is correct. And indeed, my misnaming took me to a conceptual error, thank you for catching this up. With that fix (as you shown) the results are now equal than R and Python Stats. BTW, is there a name for this $np.sqrt(1/n_c + 1/n_t)$? It looks like a kind of harmonic mean.
Comment: If you keep the variances (which you already pooled in `S_pool`) in the denominators they are a weighted [pooled variance](https://en.wikipedia.org/wiki/Pooled_variance#Definition_and_computation). It's usually this variance that you divide by $n$ (or $n-1$) and the standard error by the degrees of freedom and not the other way around - the end result is the same regardless of order though.


How hierarchical taxonomy comparison works

Question: I'm bit confused about how hierarchical taxonomy comparison will work when using Views.
For an example (using Taxonomy and Menu block modules) I've 2 level deep taxonomy:
1 Animal(10)
     1a Tiger(2)
     1b Deer(5)
What should normally be is whenever I want to search for Animal type then the View search should return total of 10+2+5 = 17 nodes.
I've just now checked that it will instead return 10.
How to get this correct functionality?
Answer: try structure -> taxonomy -> (edit your vocabulary) and at the bottom there is a checkbox
<code>"Select to rebuild the menu on submit."
</code>
Please note:
<code>"Rebuild the menu on submit. Warning: This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies."
</code>
Hit save and it should help


What are the rules regarding player movement in a lineout

Question: What are the rules regarding movement of players in the lineout?
I understand that there needs to be minimum distance between the 2 lines and that there needs to be a minimum distance between the lines and the side line.
I'm interested about movement of players for deception reasons.
Moving back and forth, switching places, leaving the lineout etc
Are there any specific rules that suggest what is and is not allowed at this time?
Comment: Furthermore, anyone can go and research any question themselves, but that's not the point of Stack Exchange sites. Rory has contributed more than enough effort by formulating an answerable question, with a clearly-defined scope (which is far more effort than some questions asked here). If someone googles "movement of players in a lineout" and hits this question as the top result, they've saved ten to fifteen minutes reading a lawbook. That's part of the purpose of this site.
Comment: I'm voting to close this question as off-topic because  the asker gives no indication of performing basic checks on whether any rules apply, and adequate official resources are easily available that do so, to far greater depth than is possible on SE. Follow-up questions after reading the laws are preferable.
Comment: 1.> You could have just posted a link to the laws as an answer and that would have been helpful. As it happens the reference to the IRB made finding the "laws" much easier and especially the reference to "Law 19". I don't see why you didn't just post this as an answer.
Comment: In the past, [closing a question due to lack of research](https://sports.stackexchange.com/questions/12860/if-the-pitcher-throws-to-1st-base-to-try-to-get-the-base-runner-out-is-the-runn#comment19667_12860) wasn't a reason to close or be used as a "[super downvote](https://sports.stackexchange.com/questions/12722/ball-goes-through-the-strike-zone-but-the-catcher-doesnt-catch-the-ball#comment19370_12722)." I'm not sure what merits a different perspective here.
Comment: 2.> I think you need to check the definition of 'off-topic'. My question is about the rules of a sport (Rugby) and this is a site specifically for asking questions about sport. It's not like I asked about Kids Toys or Politics or Fishing or something else..
Comment: @ Rory Becker "teach me the rules" isn't on-topic in the sense defined by the site itself. "I don't get this technicality in the rule/I don't understand this rule after reading it because it's verbose" would not be.
Comment: @mastermind_ed see my earlier responding comment. Trying to clear up a nuance or confusion that results from the law's explanation being tertible, okay. Asking for an explanation without looking at the laws, let alone laws with fantastic explanations already? Not to me.
Comment: Indeed, consistency based on reasonability should be the goal.
Comment: Have you tried looking for the laws? They're very clearly explained by the IRB, diagrams and images and examples included for clarity. Law 19 is what you want.
Comment: This seems answerable in a paragraph or two quoted from the Laws, and could probably be then summed up in a few sentences to form a good answer. We have association football questions like this all the time that are equally vague and broad (see [here](http://sports.stackexchange.com/questions/3/how-is-offside-determined-in-soccer) and [here](http://sports.stackexchange.com/questions/2525/what-is-the-rule-for-awarding-indirect-free-kicks-inside-a-penalty-box-rather-th) in particular), so I don't see why asking such a question about rugby union football should result in closure of the question.
Comment: @studro The question is answered far better by the official source than anything Sports.SE could hope to achieve. Seriously, go and look: the diagrams and annotation make it crystal-clear as to what is and isn't okay in a lineout. It's not doable in "a paragraph or two" for the same reason.
Comment: @Nij Then let's enforce that across the board. I don't have an issue with your perspective, because you have a valid point. I have an issue when this perspective is applied to one question and not applied to other, similarly-flawed questions.
Answer: According to rugby law 19.8, here are a few things we need prior to taking the lineout:

Both teams have same number of players contesting the lineout, who must be in a single straight line
Both team contestants must be between the 5m and 15m line from the touch line
Team lines must be 1m apart and the throw must be made straight in that 1m channel

According to rugby law 19.10:

The jumpers can only jump once the ball is thrown

Now, they move back and forth because they have combinations. Playing at my club, the last number of a lineout call gives a combination. For example "Tequila 6 6 8" means it's combination 8 and players have rehearsed that in training.
They would know for example that number 8 means short lineout, therefore a jumper will jump close to the 5m line.
If the number was 5 from the call "2 Echo 5" for instance, the throw would be to the jumper close to the 15 meter line, etc...
You can have as many combinations as you want. When you have a lineout, you need the opposition not to know what you are about to do, hence trying to lure the opposition into believing you are going to throw at the 15m etc when you are going to end up throwing at the 5m line, by moving back and forth, and having weird calls.
As an external note though, everything that you are allowed to do in rugby, or not allowed to do in rugby is described in the rugby laws available online at http://laws.worldrugby.org/.


nginx URL rewrites, applying wildcard

Question: I am using nginx to rewrite some urls. how would I take the wildcard part of the initial url and apply it to the destination url?
ex. ^/il-it/news /news where news is its the wildcard and its auto applied to the destination.
rewrite  ^/il-it(/.*)?$ / permanent;

Answer: Try this -
rewrite  ^/il-it/(.+)/?$ /$1 permanent;

Comment: `(.+)` - one or more, `(.*)` - Zero or more times
Comment: thank you... that worked. Can I ask why (.+) and not (.*) ?

nginx URL rewrites, applying wildcard


Absolute and Conditional Convergence of Series Involving Double Log

Question: Test the following series for absolute and conditional convergence:
$$\sum_{k=3}^\infty \frac {(-1)^k \log k}{k\log (\log k)}. \tag{1} $$
What test do I have to use to test for convergence of this series?
Use of the double log always confuses me.
I have two more series:
$$\sum_{k=2}^\infty \frac{(-1)^k}{k^\alpha+(-1)^k}, \alpha \gt 0 \tag{2} $$
$$\sum_{k=1}^\infty (-1)^kk^{-\alpha}, \quad \alpha \in \mathbb{R} \tag{3}$$

$(3)$ is easy.
Convergence:
By alternating series, so $\lim_{k\rightarrow \infty} k^{-\alpha}$ if $\alpha \gt 0 $.
In this case, this series converges conditionally.
However the series does not converge absolutely unless $\alpha \gt 1$ by p-series.
Divergence:
If $\alpha \le 0$ this series does not converge absolutely or conditionally.
This is because $\lim_{k\rightarrow \infty} k^{-\alpha}$ is not equal to zero.

(Reference: Elementary Classical Anaylsis, Marsden, pg. 323)
Comment: For the first, you are probably expected to use the alternating series test to prove convergence. That absolute convergence fails could come via comparison with $\sum \frac{1}{k\log(\log k)}$, which your course may already have shown is divergent.
Comment: @Dr.MV Your answer until now seems so clear to me. Maybe third one also converge conditionally, but not absolutely. I will set up my idea for third one via your answer. Wait for a moment.
Comment: @Dr.MV How about my third one solution? Is that OK to you?
Comment: @André Nicolas Thank you for your comment.
Comment: You are welcome. Indeed the third is the easiest. You probably should have said why non-convergence if $\alpha\le 0$: the terms do not have limit $0$.
Comment: I revised my question. Is that alright now?
Comment: @Dr.MV Can you please see my another question? It is harder than this one in my perspective. The link is as follows. http://math.stackexchange.com/questions/1315828/finding-functions-extension-and-its-existence-may-be-only-one-extension
Comment: @MathforyourLife I'll  have a look
Answer: We have
$$\int_3^{L}\frac{\log x}{x\log (\log x)}dx=\int_{\log (\log 3)}^{\log (\log L)}\frac{e^{2u}}{u}du$$
which clearly diverges as $L \to \infty$.  Thus there series does not absolutely converge by the integral test.  Inasmuch as $\lim_{k\to \infty}\frac{\log k}{k\log(\log k)}=0$, the series conditionally coverges.

For the second  series
$$\sum_{k=2}^{\infty}\frac{(-1)^k}{k^{\alpha}+(-1)^k} \tag 1$$
we have
$$\lim_{k\to \infty }\frac{1}{k^{\alpha}+(-1)^k}= 0$$
for $\alpha >0$ only.  Thus, the series $(1)$ converges for $\alpha >0$.  Now, to test for absolute convergence, we have
$$\left|\frac{(-1)^k}{k^{\alpha}+(-1)^k}\right|<\frac{1}{k^{\alpha}-1}$$
and thus, the series converges absolutely for $\alpha >1$.
NOTE:  The third series is effectively the same as the second one.
Comment: You mean this series converges absolutely, but not conditionally?
Comment: You used substitution method for integration. How about just setting logx=u?
Comment: @MathforyourLife The first series converges, but does not converge absolutely.  The substitution used was $u=\log (\log x)$.  If one uses instead, $u=\log x$, then  the transformed integral is $\int_{\log 3}^{\infty}\frac{udu}{\log u}$ which diverges also.
Comment: The reason is that $u$ is larger than $\log u$. So you mean $\log x=u$ is alright to show the absolute convergence of this problem by integral test.
Comment: @MathforyourLife That substitution in the integral test shows that the convergence is NOT absolute since the integral, and hence the series, diverges.  The original series with the alternative sign converges, but the series of absolute value of the terms diverges.  That implies conditional convergence only.
Comment: Oh I am sorry. I meant "alright to disprove the absolute convergence"!
Answer: The series is conditionally convergent by Dirichlet's test, since the partial sums of $(-1)^k$ are bounded and $\frac{\log k}{k \log(\log k)}$ is eventually decreasing to zero. It is not absolutely convergent by comparison with the harmonic series, since for any $k$ big enough:
$$\frac{\log k}{k\,\log\log k} > \frac{\log k}{k\,\log k} = \frac{1}{k}.$$
You may use similar arguments for dealing with the series in the second part, too.


How do I decouple a parallel pings processing system

Question: I have a system which recieves 1000s of GPS pings every second which are stored in a RDBMS table, lets call it the pingsTable. These pings are then read from the database and are processed individually in multiple processors to extract valuable information for the end user.
As of now, our system maintains a column in the pingsTable itself namely processed_state which basically specifies if a ping has been processed through a particular processor or not. For example, processed state 3 means that the pings is processed by the first 3 processors. Every processor is configured to read pings having processed state lesser than its own state and update the processed_state to its own state once the ping is processed.
The problem is that even though these processors do not depend on each other, I am still forced to process pings in a defined order.
My intention is to decouple these processors from each other so that I can run these processors parallely. Also, I need to maintain the processed_state of each ping because I may need to query already processed pings while analysing these pings.
I can think of maintaining a separate table for each processor and do a join to check if a ping is processed or not. I am looking for a more efficient and extendable design for the same.
Answer: As I understand you need to process pings in parallel. Processing has to go via all independent processors ( services). While maintaining in DB the processors which have done processing
The easiest way to do is
Assign ID to your processor. ID should based on bitwise operator ( i.e. 1,2,4,8,16 .etc.).

Feed ping to all processor
When server is done processing update DB with (processor ID + any existing value)
Use bitwise operation in your SQL queries

For example 1 ping needs to be processed by 5 processors

Processor 5 process ping update DB value 16
processor 2 process ping update DB value 16 + 2 = 18
processor 3 process ping update DB value 18 + 4 = 22

Now you want to query that processor 4 processed the ping. In your SQL's where clause use "bitwise and" for operator 8
This way you don't need separate table etc.. And things without join make it faster. On negative side you have to take care of DB update, row locking if two processors are trying to update same value.


How to do efficient inserts?

Question: When I insert a new object to the DB I tie it with a relationship to another, by doing another db lookup, I'd like to remove this extra step for efficiency, I.E How can I set a relationship to another using just the ID, rather than having to fetch the whole object from the DB? e.g.:
Car C = new Car();
C.Person = db.person.find(PersonID); //unnecessary lookup
//I'd like to do: C.setPersonID(personID);
db.cars.add(C);
db.saveChanges();

where model:
class Car
{
   public virtual Person Person { get; set; }
}

Answer: Assuming that its a one-to-one relationship, you could do this:
public class Car
{
    public int Id { get; set; }
    public int PersonId { get; set; }
    public Person Person { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class CarConfiguration : EntityTypeConfiguration<Car>
{
    public CarConfiguration()
    {
        HasKey(i => i.Id);
        HasRequired(i => i.Person).WithMany().HasForeignKey(i => i.PersonId).WillCascadeOnDelete(false);
    }
}

Then to add a new car with a person using only the person's Id and also assuming that the person with that Id is existing:
using (var ctx = new CarContext())
{
    var car = new Car();
    car.PersonId = 5;
    ctx.Cars.Add(car);
    ctx.SaveChanges();
}

You may find this link useful.
Comment: Thanks, I'd rather not change to using custom contexts, I'm just using a BaseDBContext. So I like the idea of a set Accessor for the ID property. I'm wondering if I can create a method setPersonID(myID) { Person p = new Person; p.id = myId; this.Person = p; }
Comment: Not sure if that's possible since without explicitly declaring the foreign key you won't be able to set the relationship using the Id.
Comment: You could add the SetPersonId(int personId) method on the Car class which you use to set the Id. Not sure though if that is what you mean.
Comment: yes thats what I mean, of course there's no personId property so I'm guessing you have to instantiant the Person object and set its id
Comment: It just seems like EF would have catered for this more elegantly
Comment: Well as far as I know other ORMs I've used (OpenAccess, XPO) doesn't have a way to do it without explicitly specifying the foreign key similar to above.
Answer: Use foreign keys and set the foreign key property accordingly.
Answer: I haven't run this to confirm, but I believe there is a Convention based ID system used by Entity Framework. This may well automatically do what you don't want to happen.
class Car
{
   public virtual Person Person { get; set; }
   public virtual Int32   PersonID { get; set; }
}

I was going to post code from the NerdDinner project where I have seen this before (http://nerddinner.codeplex.com/) but you can look it up as it is fairly attribute-laden code.

How to do efficient inserts?


Finding the limiting distribution of $\sqrt{n} (\hat{\tau} - \tau)$ as $n \rightarrow \infty$ for $N(\mu, \mu^2 \tau)$

Question: Let $X_i$ for $i = 1, ..., n$ be a random sample from the distribution $N(\mu, \mu^2 \tau)$ with unknown parameters $\mu \in (\infty, 0) \cup (0 ,\infty), \tau > 0$.
Find and justify the mle $\hat{\tau}$ and the limiting distribution of $\sqrt{n}(\hat{\tau} - \tau)$ as $n \rightarrow \infty$.
My Solution:
So from exponential theory the MLE's are moment-of-moments estimators, so $\hat{\mu} = \bar{X}$ and $\hat{\tau} = (1-1/n)S_X^2/(\bar{X})^2$. (Obviously after showing that this is a natural exponential family)
Now since the MLE contains the sample mean and sample standard deviation I could use LLN + CLT + Delta Method to find the limiting distribution but I know that the asymptotic property of the MLE is $\sqrt n(\hat{\tau} - \tau) \rightarrow N(0, \frac{1}{I(\tau)})$, so
$$l = \ln( f(x)) \propto -\frac12\log(\mu^2 \tau) - \frac{x^2}{2\mu^2 \tau} + \frac{x}{\mu \tau} - \frac{1}{2 \tau}$$
$$\frac{\partial l}{\partial \tau} = \frac{x^2}{2 \mu^2 \tau^2} - \frac{x}{\mu \tau^2} + \frac{1}{2 \tau^2} - \frac{1}{2 \tau}$$
$$\frac{\partial^2 l}{\partial \tau^2} = -\frac{x^2}{ \mu^2 \tau^3} + \frac{2x}{\mu \tau^3} - \frac{1}{ \tau^3} + \frac{1}{2 \tau^2}$$
$$-\frac{\partial^2 l}{\partial \tau^2} = +\frac{x^2}{ \mu^2 \tau^3} -\frac{2x}{\mu \tau^3} + \frac{1}{ \tau^3} - \frac{1}{2 \tau^2}$$
$$E\left(-\frac{\partial^2 l}{\partial \tau^2}\right) = \frac{\mu^2\tau + \mu^2}{ \mu^2 \tau^3} -\frac{2 \mu}{\mu \tau^3} + \frac{1}{ \tau^3} - \frac{1}{2 \tau^2}$$
$$E\left(-\frac{\partial^2 l}{\partial \tau^2}\right) = \frac{\tau}{2\tau^3}$$
$$\frac{1}{I(\tau)} = 2\tau^2.$$
However the solution given to us using the delta method is:
$\sqrt{n} (\hat{\tau} - \tau) \approx N(0, 2\tau^2 + 4\tau^3)$
Am I going wrong somewhere conceptually or algebraically?
Comment: Why don't you compute the full information matrix?  Your calculation appears to assume $\mu$ is known but you state it is not.
Comment: I was under the impression that since $\frac{1}{I(\tau)}$ does not depend on $\mu$ and $\mu \ne 0$ we can follow through despite whether $\mu$ is known or not. Perhaps it is a conceptual error on my part but would the "full information matrix" be pertaining to finding $\frac{\partial^2 l}{\partial \tau \partial \mu}$, $\frac{\partial^2 l}{\partial \mu \partial \tau}$, and $\frac{\partial^2 l}{\partial \mu^2}$? And if so, wouldn't that be $\sqrt{n} (\hat{\tau} - \tau) \rightarrow N(0, \frac{1}{I(\mu, \tau)})$ ? (Unless this is the actual formula for the asymptotic distribution of the MLE)
Answer: Whuber's comment is to the point, since it matters whether you estimate two parameters or one.
Algebraically, you are correct up to and including the computation of the expected value of the negative 2nd derivative. But if $\mu$ is also estimated, than the variance of $\tau$ is not the inverse (here just the reciprocal) of this expected value.
If $\mu$ is also estimated, then your MLE is a $2 \times 1$ vector, and in order to obtain the variance of $\tau$, you need to compute the full $2 \times 2$ (negative of the) Hessian of the log-likelihood and invert it properly. You will find that the answer given to you is correct. There is no need to use the Delta method.
Intuitively, the variance is higher due to the uncertainty in co-estimating also $\mu$.


Prove that $\int_{\mathbb{R}}|x+iy|^{-\alpha}dx=c_\alpha y^{-\alpha+1}$.

Question: Prove that $\int_{\mathbb{R}}|x+iy|^{-\alpha}dx=c_\alpha y^{-\alpha+1}$, where $c_\alpha$ is a constant to be determined.
I tried to prove the problem using mathematical induction and it is okay for the starting point $\alpha=2$, which I obtained $\int_{\mathbb{R}}|x+iy|^{-\alpha}dx=(4n+1) \pi y^{-1}$. But I face difficulty for the inductive step'
Comment: Your "mathematical induction" line assumes $\;\alpha\in\Bbb N\;$ and not merely a real parameter. Is this accurate? Because if it is then you should write it down explicitly, and if it is not then induction won't help you here.
Answer: Here are some ideas. The integral can be rewritten as
$$
\int_{\mathbb R}\left(x^2+y^2\right)^{-\alpha/2}\mathrm dx.
$$
Use the substitution $x=ty$ (it is implicitely assumed that $y\neq 0$).
Comment: I tried the substitution $x=ty$  yes it give the result when it is improper integral but I did not get the result due to integration over $\mathbb{R}$ .
Comment: Thanks it works using the substitution and using Beta and Gamma Function.


Recursive bubble sort in X-Y coordinate in C

Question: I would like to sort the elements associated with X
The method tried not in a recursive way, any idea how to do it
The expected output is:
{5,73} , {11,19}, {11,34}, {11,68}, {13,5}
I have tried this so far, but only X is sorted while Y remain in original position
void sort(struct Points a[], int n)
        {

            if (n == 1) return;

            for (int i=0; i<n-1; i++)
                if (a[i].X > a[i+1].X)
                    swap(&a[i].X, &a[i+1].X);

            //sort(&a[0], n);

        }
    struct Points {
        int X, Y;
    };

    void swap(int *a, int *b)
    {
        int t;

        t  = *b;
        *b = *a;
        *a = t;
    }

        void sort(struct Points a[], int n);

        int main()
        {
            int i;
            struct Points ptArray[5] = { {11, 34}, {5, 73}, {11, 19}, {13, 5}, {11,
                68}};

            sort(ptArray, 5);

            for (i = 0; i < 5; i++){
                printf("(%d, %d)\n", ptArray[i].X, ptArray[i].Y);
            }

            return 0;
        }

Comment: `swap(&a[i].X, &a[i+1].X)` -> `swap(&a[i], &a[i+1])` if the rest is correct
Comment: As @Federico wrote, your `swap` function should likely have a different signature, i.e. `void swap(struct Points *a, struct Points *b)`. Also, struct name should be `Point`, not `Points`.
Answer: full working code -
struct point{
    int x; int y;
};

bool isGreater(point p1, point p2){
    if(p1.x>p2.x) return true;
        else if(p1.x==p2.x){
            return p1.y>p2.y;
        }
    return false;
}

void recBubble(point *arr, int n){
    if (n == 1) return;

    for (int i=0; i<n-1; i++)
        if (isGreater(arr[i],arr[i+1]))
            swap(arr[i], arr[i+1]);
    recBubble(arr, n-1);
}

Answer: There are a few issues in your code:
[1] you want to swap Points object so modified swap function looks
void swap(Points *a, Points *b)
{
    Points t;

    t  = *b;
    *b = *a;
    *a = t;
}

[2] now you are sorting elements only by checking X coordinates, you don't have condition to check Y - values
[3] when you want to call sort function recursively, n parameter must be decremented before calling function
sort function should be
void sort(struct Points a[], int n)
{
  if (n > 1)
  {
    for (int i=0; i<n-1; i++)
        if (a[i].X > a[i+1].X || (a[i].X == a[i+1].X && a[i].Y > a[i+1].Y))
            swap(&a[i], &a[i+1]);
    sort (a,--n);
  }
}


Z-score for normal and reversed variables

Question: I'm comparing multiple countries across many indicators (with different scales and units). I want to develop a score for each country and I'll do that by taking the mean of the z-scores for each indicator. But some of my indicators are reversed. So, for example, for -Life Expectancy- less is worse, while for -Obesity- less is better. How can I statistically account for that? Can I just multiply the z-scores for those reversed variables by -1 so when I take the mean of the z-scores it actually means something?
Comment: See also points 2-7 [here](https://stats.stackexchange.com/a/9361/17230).
Answer: It's perfectly acceptable to do this, so that a negative z-score implies a negative result, just as long as you state that this is what you have done somewhere. This way they all mean the same thing.
Have you thought about doing J-charts for this too?


Recuperar todos os eventos usando FullCalendar

Question: Eu preciso recuperar todos os eventos do meu calendário e depois recuperar todos os dias que têm um evento.
Eu já tentei
<code>$("#calendar").fullcalendar("getSource");
</code>
mas iss não funciona
Answer: Para capturar todos os eventos, utilize:
<code>// Obter array de eventos
var eventos = $('#calendar').fullCalendar('clientEvents');
</code>
Esse comando retornará um array com todos os eventos, e consequentemente dentro de cada evento tem uma data inicio e uma data fim. Você pode percorrer esse array e obter todas as datas inicio de cada evento:
<code>// Criar um array para armazenar os dias que tem evento
var dias = [];

// Percorrer array de eventos armazenando os dias que ainda não estão no array
eventos.forEach(function(evento){
    var data = evento.start._d;
    var dataString = data.getFullYear() + '-' + data.getMonth() + '-' + data.getDate();
    if(dias.indexOf(dataString) < 0){
        dias.push(dataString);
    }
});
</code>


Simplify water salinity equations

Question: I recently became interested in calculating water salinity from conductivity and temperature. I failed to find any theoretical model to how this is done, only empirical models derived from fitting to experimental data.
One such model (first Google hit) I found was this, of which if you look in the page source you find:
$r = \frac{C/42914}{c_0+T*(c_1+T*(c_2+T*(c_3+T*c_4)))}$
$ds_1 = b_0+r^2*(b_1+r^2*(b_2+r^2*(b_3+r^2*(b_4+r^2*b_5))))$
$ds_2 = ((T-15.0)/(1.0+0.0162*(T-15.0)))$
$d_s = ds_1 ds_2$
And finally:
$salinity=a_0+r^2*(a_1+r^2*(a_2+r^2*(a_3+r^2*(a_4+r^2*a_5))))+d_s$
where $a_i, b_i, c_i$ are fitted coefficients.
Without going into depth about the fysics of salinity, doesn't this model seem overly complicated? I mean whats the highest order of T? Alot.
Comment: You'd think they'd have tried simpler models first, no? In any event, I'm not sure what the *mathematical* question here is...
Comment: @J.M. - My point is that does it really add that much to have that many degrees of freedom?
Comment: Hard to tell. Were any physical justifications given for the polynomials in the expression?
Comment: No, I might try plotting salinity as a function of conductivity and temperature and see weather the function looks overfitted.
Answer: In 1978, the United Nations Educational, Scientific and Cultural Organization (UNESCO), International Council for the Exploration of the Sea (ICES), Scientific Committee on Oceanic Research (SCOR) and International Association for the Physical Sciences of the Oceans (IAPSO) adopted a practical method for calculating salinity of seawater based on electrical conductivity measurements compensated for temperature.
The Practical Salinity Scale of 1978 (PSS-78) defines a scale for 'Practical Salinity', $S$ (a dimensionless quantity) which is calculated from electrical conductivity and temperature measurements, in the range $2 \leq S \leq 42$, by the following formula:
$S = 0.0080 - 0.1692K_{15}^{1/2} + 25.3851K_{15} + 14.0941K_{15}^{3/2} - 7.0261K_{15}^{2} + 2.7081K_{15} ^{5/2}$
Where $K_{15}$ is the ratio of conductivity of the sea water sample to that of potassium chloride (KCl) solution of mass fraction 32.4356x10$^{-3}$, at 15$^{o}C$ and atmospheric pressure.
This formula is extended to compensate for the variation in conductivity with temperature in the range $-2^{o}C \leq t \leq 35^{o}C$ (at atmospheric pressure) by incorporating temperature coefficient (see http://unesdoc.unesco.org/images/0004/000479/047932eb.pdf).

Simplify water salinity equations


Using Kolmogorov's 0-1 law in proof of shift map being ergodic

Question:
Why should ${\cal E}_\theta$ be trivial?. I dont see how Kolmogorov's 0-1 law says that in this case we should take the 0 option.
This is only mention of ${\cal E}_\theta$ in my notes I can find.
Comment: You are writing $\xi_\theta$ where the book writes ${\cal E}_\theta$. This completely different notation is what's confusing us....
Comment: What is $\xi_\theta$? I don't see a definition for it in the theorem, or even mentioned.
Comment: @AdamHughes Only mention I can find is in the edit
Comment: "A set $A\in{\cal E}$ is called invariant if $A=\theta^{-1}(A)$. The class of all invariant sets forms a $\sigma$-algebra, which we denote by ${\cal E}_\theta$."
Answer: A sigma-algebra is trivial when it contains only sets of measure $0$ or $1$. There is no "0 option" here, that "we should take".


Can you set the directory from which the Media module populates its Library tab?

Question: I would like to know if it is possible to set the directory from which the Media module populates its Library tab in the Media Browser.
For instance, when the newest version of the Media module is installed, the directory its Library tab is populated from seems to be /sites/default/files/field/image/. If another directory is already created on a server which contains a set of images I would like to choose from, is it possible to modify the Media module to look in that directory?
I've spent a fair amount of time digging through the module code and haven't found where the directory default is being set. Has anyone ever attempted this?
Comment: I'm not sure whether this helps you, but I found this answer in an older Drupal Answers question about the Media module: http://drupal.stackexchange.com/a/23207/9379 where it says that Media comes with a standard view (that defines which files are taken into account)
Comment: I don't think it works like that. For instance, if you have a file field attached to an entity and you specify the folder in which it must store the file then that is taken into account as well. I would think that Media just uses the file's internal path as set by file_entity to load media. Drupal file system will convert it to the correct physical path. I also think that you might have access to the internal and physical paths in the view that the media browser runs on.
Answer: The Media Browser does not work with a physical path, but with the file managed table, and Drupal file system uses the uri of the file to get to the actual file.
Go to the views settings page admin/structure/views/settings and turn on 'Show the SQL query'.
Then open up the media browser and look at the SQL query. It starts of with
SELECT file_managed.timestamp AS file_managed_timestamp, file_managed.fid AS fid, SUM(file_usage.count) AS file_usage_count
FROM
{file_managed} file_managed

which means it is using the file_managed table as its base. That comes from the file module in Core. Looking at that table definition in PHPMyAdmin for instance will reveal a fid as the primary identifier, a filename, a uri, filemime and some other fields. The uri is the important part as it tells Drupal how to get to files. The uri is prefixed by the stream wrapper (PHP classes that provide a common interface for getting to resources) and the two common Drupal ones are public:// and private://.
The media module already provides a remote internet sources wrapper, and Remote stream wrapper module provides a Remote Url plugin for the media module.
You can also write your own. Writing stream wrappers
Comment: This comment is a thank you @J.Reynolds, but also a quick explanation of how your answer helped me.

After inspecting the file_managed table I decided to try and insert another row and use the uri field to link to an image I placed in a folder on my local server. I then added a file path filter to the Media Browser block that started with the directory (public://images) and the image appeared. So the record in the file_managed table was the missing link.


net core api newtonsoft.json Self referencing loop detected for property 'Client' with type 'Microsoft.Graph.GraphServiceClient'. Path 'Invitations'

Question: I am storing GraphServiceClient in the session (because I need to use it in other Requests):
HttpContext.Session.SetObject("graphClient", _graphServiceClient);

GraphServiceClient is an Object, so I extended Session:
public static class SessionExtensions
    {
        public static void SetObject(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObject<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }

When trying Post request I get the following Error with 401 Status

"Self referencing loop detected for property 'Client' with type
'Microsoft.Graph.GraphServiceClient'. Path 'Invitations'."
Comment: Why are you attempting to store the client instead of just the token(s)? You should only need to store the token and then create a client when needed.
Comment: To be able to reproduce your issue, we'll need to see the code and payload that is causing the issue. BR
Answer: As Marc LaFleur suggested, I solved this issue by storing the token


Multiple Relationships in CiviCRM Views Integration

Question: I have been trying to set up a Drupal View of a a 3-way relationship in CiviCRM.
The view I wanted was that showed a list of contacts that are provided services from the current user's employer, as below
(current user) contact a => (is employed by) => organisation => (is a provider of) => contact c
I created a view of CiviCRM Contacts, and could not see a way of getting this relationship to display what I wanted without building a custom module, which is explained below.
Answer: You can do this with a custom module and using the preprocess views hook to pass in the contextual filter. The filters are passed into the $args[] variable.
You also may need to enable multiple values in a contextual filter, if you have more than one relationship from Contact A to Contact B, in this case this is multiple employers. This is under Contextual Filters > Advanced > Allow multiple values.
You do not add % to the path as you would normally do with a contextual filter as we are programmatically inserting it.
Create a custom Drupal module with the following code
<code>/**
* @implements hook_views_pre_view().
*/
function HOOK_views_pre_view(&$view, &$display_id, &$args){

if($view->name == "my_view") {
      // Check that we are altering the correct view based on and $view->name
      civicrm_initialize();
      require_once 'api/api.php';
      //get the matching civi id for the current user
      //This is using Civicrm version 4.4.6

      global $user;
      //first get the current user's Civicrm record
      $params = array(
         'version' => 3,
         'sequential' => 1,
         'uf_id' => $user->uid,
      );
      /*The contact ID is in $result['values'][0]['contact_id']*/
      $result = civicrm_api('UFMatch', 'get', $params);

      $params = array(
          'version' => 3,
          'sequential' => 1,
          'relationship_type_id' => 5, /*get your relationship ID from /civicrm/admin*/
          'contact_id_a' => $result['values'][0]['contact_id'],
      );
      $result = civicrm_api('Relationship', 'get', $params);

      //temp stores the string which will be passed to the $args[] array
      $temp = "";

      //loop through the a => b relationships, and append all the ids of contact b
      foreach ($result[values] as $key => $value ) {
         if ($key > 0)
            $temp .= "+";
         $temp .= $value['contact_id_b'];
      }
      // populate the $args contextual filters array with the ids.
      $args[] = $temp;
   }
}
</code>
Answer: You can do this without a custom module. In Views Relationships your first add a Views Relationship for the CiviCRM Relationship, and then add the Contact at 'the other end' of the Relationship. So for each Civi Relationship you will create 2 Views Relationship. Hence to daisy chain A to B to C, you will have 4 Views Relationships
Not easy to explain especially when both Views and CiviCRM are using the term Relationship.
Add Views Relationship 1 (VR1) of type "Connects a contact (as contact A) to a relationship." (eg employer of)
Add Views Relationship 2 (VR2) of type "The contact B" use select VR1 as the 'Relationship'
So you have now connected person X to Org Y
Add Views Relationship 3 (VR3) of type "Connects a contact (as contact B) to a relationship." (eg Provider of) - select VR2 as the 'Relationship'
Add Views Relationship 4 (RV4) of type "The contact A" select VR3 as the 'Relationship'
So now you should have connected person X to Org Y and then Org Y to person Z.
For creating RV3, you need to work out whether to use "starting from A" or B as it will depend on how you created your "is a provider of" Relationship. Clear? Not that easy to explain ;-)


Passar argumentos para o getter da propriedade

Question: O VB.NET permite que você declare parâmetros no getter da propriedade
Public ReadOnly Property Propriedade(param As String) As String
  Get
     Return param & "!"
  End Get
End Property

É uma característica estranha e no C# não funciona. Qual é a utilidade prática?
E por que utilizar propriedades com parâmetros ao invés de funções, como:
Public Function GetFoo(param As String) As String
    Return param & "!"
End Function

Answer: Existe em C# sim. Elas são propriedades indexadoras. E portanto servem justamente para ter um indicador de qual o índice de uma coleção de dados está querendo pegar. É possível ter mais de um parâmetro, mas todos deveriam ser índices de uma matriz.
Em VB.NET é um pouco mais flexível porque pode nomear a propriedade e C# não, então é possível ter mais de um indexador. Mas não devem ser usados como propriedades normais. Se tem que passar argumento para o getter, ele não é um getter. VB.NET tem decisões questionáveis.
Pode ser usado com o setter também que acabaria tendo pelo menos dois parâmetros.
Obviamente que isto pode ser abusado e usar da forma mostrada na pergunta, mas não é recomendado, é fora da semântica para o que foi criado. Só deveria ter uma propriedade assim se o tipo sendo criado for uma coleção de dados.
Note que em VB.NET o acesso a coleções é feito com parênteses igual a funções e dá uma impressão errada de que está chamando um método. Em C# não há esta confusão:
propriedade[indice]
propriedade[indice] = 1;

Então assim como em VB.NET é possível abusar em C#:
public int this[int index] {
    get => 42 + index;
    set => WriteLine($"abusei {index}");
}

Em C# é possível dar nome para o indexador para outras linguagens que trabalham com nomes verem este nome:
[System.Runtime.CompilerServices.IndexerName("NomeDoIndexador")]

Coloquei no GitHub para referência futura.
Mas ainda não pode ter mais que um. O nome padrão é Item.
Já respondi porque propriedades costumam ser melhores que métodos em certos cenários.


Oracle Apex Signature Plugin issue

Question: I am trying to create digital signature feature in apex application and was able to do via the plugin created exactly following steps mentioned here:
https://github.com/Dani3lSun/apex-plugin-apexsignature
I used this plugin directly and am able to sign .
However in the interactive grid query below, if i use the query below directly, it throws pl sql numeric conversion error:
I wish to get the report similar to the way its shown in demo application, but am unable to.
Also in interactive grid i cannot find option to set datatype for blob001 column. i want it to be downloadable link.
<code>SELECT c001    AS filename,
       c002    AS mime_type,
       d001    AS date_created,
       blob001 AS img_content
  FROM apex_collections
 WHERE collection_name = 'APEX_SIGNATURE';
</code>
Apex 20.2
Answer: The Demo application utilizes an Interactive Report, not Interactive Grid.

Probably that's the source of the error.

Oracle Apex Signature Plugin issue


Evaluate $\int_0^1dx\int_0^{\sqrt{1-x^2}}dy\int_{\sqrt{x^2+y^2}}^{\sqrt{2-x^2-y^2}}z^2dz$

Question: I need to evaluate this integral $$\int_0^1dx\int_0^{\sqrt{1-x^2}}dy\int_{\sqrt{x^2+y^2}}^{\sqrt{2-x^2-y^2}}z^2dz$$I know it's not hard, but somewhere I struggle. As I see it would be really helpful to use spherical coordinates. This is what I already did: $$\int_0^1dx\int_0^{\sqrt{1-x^2}}dy\int_{\sqrt{x^2+y^2}}^{\sqrt{2-x^2-y^2}}z^2dz=\int_0^{\frac{\pi}{2}}d\phi\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}d\theta\int_?^?r^4 \sin^2\theta
 \cos^2\phi \space dr$$ where $x=r \cos\phi \cos\theta \space \space$, $y=r \sin\phi \cos\theta \space \space$ and $z=r \sin \theta$.
Can anyone help me?
Answer:
Instead of going through the effort of working out the bounds for spherical coordinates, it may be less work to use cylindrical coordinates instead:
$$\begin{align}
\mathcal{I}
&=\int_{0}^{1}\mathrm{d}x\int_{0}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{\sqrt{x^{2}+y^{2}}}^{\sqrt{2-x^{2}-y^{2}}}\mathrm{d}z\,z^{2}\\
&=\int_{0}^{\frac{\pi}{2}}\mathrm{d}\theta\int_{0}^{1}\mathrm{d}r\,r\int_{\sqrt{r^{2}}}^{\sqrt{2-r^{2}}}\mathrm{d}z\,z^{2};~~~\small{\left[\left(x,y\right)=\left(r\cos{\theta},r\sin{\theta}\right)\right]}\\
&=\frac{\pi}{2}\int_{0}^{1}\mathrm{d}r\,r\int_{\sqrt{r^{2}}}^{\sqrt{2-r^{2}}}\mathrm{d}z\,z^{2}\\
&=\frac{\pi}{4}\int_{0}^{1}\mathrm{d}t\int_{\sqrt{t}}^{\sqrt{2-t}}\mathrm{d}z\,z^{2};~~~\small{\left[r^{2}=t\right]}\\
&=\frac{\pi}{4}\int_{0}^{1}\mathrm{d}t\int_{t}^{2-t}\mathrm{d}u\,\frac{u}{2\sqrt{u}};~~~\small{\left[z^{2}=u\right]}\\
&=\frac{\pi}{8}\int_{0}^{1}\mathrm{d}t\int_{t}^{2-t}\mathrm{d}u\,\sqrt{u}.\\
\end{align}$$
There rest of the calculation should be straightforward from this point.


How to comment out code in a .tpl.php template

Question: If I want to remove parts of .tpl.php file what are my options other than removing them permanently?
HTML comments < !-- --> work but print the part in the HTML source.
PHP // comments or /* */ don't work.
For example, how could I comment out a block like:
    <?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
      <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

    <?php endif; ?>

Comment: How long are these removals left in your code?  Only during active development or indefinitely?  IMHO, comments are fine for a few quick tests, but to avoid bloat and debugging headaches I would look into version control as @tim.plunkett suggested.
Comment: good point. I'm using git for development, I'm just not too familiar with it yet where I can quickly see the history of changes on a file.
Comment: Maybe not the greatest solution, but if your GUI has a local history, that could work for your local comparisons.  You can still use git as well and when you're ready to dive into it, your info will all be there. :)
Comment: Anything within PHP tags can be commented with // or /* */ Are you missing any opening or closing PHP tags?
Comment: I added an example to my question
Comment: Use version control, and then you can just delete the lines.
Answer: I actually prefer to use this way
<?php if (FALSE): ?>

  <?php if ($submitted): ?>
    <?php print $submitted ?>
  <?php endif; ?>

  <?php if ($terms): ?>
    <?php print $terms ?>
  <?php endif;?>

<?php endif; ?>

This make it easier to put the block back in (change FALSE to TRUE), or attach a variable to the conditional.
EDIT:
To address your example, I would do it one of two ways
<?php if (FALSE): ?>
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
  <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>
<?php endif; ?>

or
<?php if (FALSE && $logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
  <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

I would normally lean towards using the second in my daily work.


Teste de conexão com internet eficaz

Question: Tenho uma aplicação no qual faço um teste de conexão antes de consultar um webservice, justamente para exibir uma mensagem para usuário que não possui conexão com internet. Uso um método desta forma:
public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        return true;
    } else {
        return false;
    }
}

Percebi nesta pergunta sobre Testar conexao com a internet de uma aplicação que é usado o Context.CONNECTIVITY_SERVICE, como na minha função. Baseado em alguns testes que fiz, desta forma como é feita, se estiver apenas conectado ao WIFI ou 4G, é detectado que possui uma conexão, porém nem sempre funciona, pois em alguns casos acaba caindo numa INTRANET. Pode ser uma forma eficiente, mas não necessariamente tão eficaz.
Vi essa resposta sobre Texte de Contexão que é possível dar um ping no HOST, porém de acordo com a resposta validada, nem sempre os hosts aceitam pings.
Tento toda esse questionamento, qual seria a forma mais eficaz de testar se existe uma conexão com internet?
Answer: Uma coisa é ter uma conexão activa à rede(network) outra é conseguir aceder a um recurso na internet.
A verificação da existência de uma conexão activa pode ser feita com o código colocado na pergunta.
Eu apenas alterava
if (null != activeNetwork)

para
if (null != activeNetwork && activeNetwork.isConnected())

ficará assim:
public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork && activeNetwork.isConnected()) {
        return true;
    } else {
        return false;
    }
}

Caso essa verificação falhe deve informar o utilizador da necessidade da conexão e, eventualmente, pedir-lhe que ligue o wifi, direccionando-o para as Settings, usando
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));

Verificar se um recurso na internet é acessível ou não depende do recurso em si. Por isso não é possível escrever um método que garanta a 100% que um qualquer recurso está acessível.
Usar ping ou verificar se o endereço da google está acessível apenas garante isso mesmo: que o servidor "pingado" ou o servidor da Google estão acessíveis, não garante que o seu serviço ou qualquer outro esteja.
Assim, nos termos que refere, não há um método único e eficaz de verificar a conexão à internet.
A abordagem a seguir é verificar se há uma conexão activa e, em cada caso, o código que acede ao recurso, lidar com o facto de ele poder não estar acessível.
Comment: Tinha me esquecido desta pergunta! Obrigado. =D

Teste de conexão com internet eficaz