Is there a way to use the compareTo() method for a data set, without iterating through each element of the set?

Question: I am wondering if there is a way to use compareTo() without having to iterate through each string element in the data set, I'm pretty sure this is not possible using arrays, but is there a data structure that is capable of working in that way?
See example below for clearer explanation:
public static int PronounDetector(String [] pronouns)
{
    String [] you = {"you", "You"};
    for (int i = 0; i < pronouns.length; i++)
    {
        if (pronouns[i].compareTo(you) == 0)
        //Is there a way for compareTo to run through
        //the entire String data set without having to make
        //it iterate through each element using a for loop?
        {
            return 2;
        }
    }
}

EDIT: I understand that no matter what the program will iterate through the data set, (how else will it find a match?), I am just looking to see if there is a way to do it without me actually having the physically type in the for loop.
Comment: Worst-case scenario will *always* lead to search of entire data-structure. So, No. its not possible.
Comment: Pretty sure if you want to compare something to every element, you're gonna have to iterate through every element _somehow_. Also, I don't think your code would even compile...
Answer: The must be meet two conditions if you want to skip some data during search processing.

The data must be related.
The data must be organized.

You can improve your search, by sorting the array and then compare from the middle.
Then in each step you will reduce element that must be compare by half.
Instead of array you can used TreeMap, that will store the data in tree structure to have same result.
Code example:
public static boolean contains(String[] array, String key) {

        Objects.requireNonNull(array,"The array must not be null");
        Objects.requireNonNull(array,"The key must not be null");

        String[] copy = array.clone();
        Arrays.sort(copy);

        return Arrays.binarySearch(copy, key) != -1;
    }

Answer: Yes, you don't have to "double iterate" (even though that's exactly what happens under the hood) you can convert the array you to a string and search it using contains():
    String youStr = Arrays.deepToString(you);
    System.out.println(youStr.contains(pronouns[0])); // prints 'true'


Number of distinct $n$ cycles of $n$ objects.

Question: Find number of $n$ element cycles of $n$ elements.
The first position can be filled in $n$ ways.
Then, the second position can be filled in $n-1$ ways.
Then, the third position can be filled in $n-2$ ways.
$\vdots$
This gives a total of $n!$ ways.
Let, the four elements, for $n=4$ be: $a,b,c,d.$
Taking a particular cycle to be $abcd,$ have the equivalent cycles:

$bcda,$
$cdab,$
$dabc.$

I.e, for each cycle of length $n,$ there are $n-1$ equivalent cycles.
But, this means there are $n!/(n-1)$ distinct cycles.
However, for $n=4$ have $6$ non-equivalent (distinct) cycles of length $4,$ as for say the cycle $(abcd)$:

$abcd,$
$abdc,$
$acbd,$
$acdb,$
$adbc,$
$adcb.$

But, this contradicts with earlier analysis of having $4!/(3)= 8$ cycles.
Comment: Simpler: since every cycle is equivalent to a cycle with first element $a$ (or $1$), and two cycles with the same first element are equal if and only if they are identical, you just need to order the remaining $n-1$ elements.
Comment: "... Taking a particular cycle to be $\mathsf{abcd}$, have the equivalent cycles be: $\mathsf{bcda}$, $\mathsf{cdab}$, $\mathsf{dabc}$, i.e., for each cycle of length $n$, there are $n-1$ equivalent cycles." You forgot to take $\mathsf{abcd}$ itself into your enumeration.
Answer: For each cycle $a_1a_2\dots a_n$, there are actually $n$ equivalent cycles, not $n-1$ --- each corresponds to a unique choice of starting element $a_i$. In the case of $n=4$ where the original cycle is $abcd$, the equivalent cycles are
$$\{abcd,bcda,cdab,dabc\};$$
I believe you only counted the last three.
Comment: So, for $n=4,$ have the number of distinct $4$-cycles, given by: $n!/(n)= (n-1)!= 3!= 6.$
Comment: @jiten Yes, that's exactly right.


Install SSL certificate on AWS

Question: I bought a SSL cert from Go Daddy and I'm hosting my website on a linux instance running nginx on AWS.
I am trying to install a SSL certificate on to an instance I have on AWS
This is my understanding of how the process works.
In order to get an SSL certificate I must create a CSR, when making a CSR a private key is also created.
I submit my CSR to my CA (Go Daddy) and they use that create my cert and my cert chain. Then I put the cert, cert chain and private key into my server and thats it.
Theres two ways to do this, either directly on the server or through AWS. I'm trying to do it on AWS.
https://sg.godaddy.com/help/manually-install-an-ssl-certificate-on-my-aws-server-32075
This tutorial assumes I already have a CSR and Private key, which I don't.
So I tried the following to get a CSR
https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaGetCsr.html
https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaCreateCa.html

Go to Amazon Certificate manager

Create a subordinate CA (I don't know why)
2.1. Put your details, not Go Daddy's details.
2.2. Accept default settings for all the following pages and create

Install subordinate CA certificate
3.1 Choose External private CA
3.2 This page gives you as CSR for this CA, copy and paste the CSR into Go Daddy to key the certificate from Go Daddy to my server
3.3 Download the newly keyed SSL cert from go daddy, put the bundle file in the certificate chain field, put the other file in the certificate body field

Now i get

MalformedCertificateException:
The basic constraints extension must
specify that the certificate is for a CA."

I've clearly done something wrong here. The error message seems as if I have misintreprted the purpose of this amazon feature.
and I've only got a CSR I don't have a Private Key.
when following this guide
https://sg.godaddy.com/help/manually-install-an-ssl-certificate-on-my-aws-server-32075
I get to step 8 and I dont have a private key file.
After doing some research I found these
https://superuser.com/a/1428640
https://serverfault.com/a/919007/596551
Which says I'll never be issued the private key from this method which puts me back to square one, no CSR and no private key, therefore no cert can be generated.
However as per the first link I am using an Amazon Load Balancer
My questions are.

Is my understanding of the process of applying an SSL certificate right?
What is the correct way of applying a SSL cert to AWS from scratch?

When
Comment: You are looking at the instructions for ["ACM Private CA"](https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaWelcome.html) which is a CA hierarchy run **on and by Amazon _for_ you** and completely incompatible with any _other_ CA like GoDaddy. The next section on that page says for "certificates you import" (from another CA) to go to https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html instead. In particular see https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html .
Answer: I haven't read your aws doc links but I have done the certificate apply on AWS ELB, EC2 VM, apache httpd many times. You don't have to follow the aws guide if that does not sound simple to you. You can do it the old fashioned way. That's how I do it. You create a CSR with openssl command in a Linux server and private key and then get the Signed SSL from go daddy for that CSR . Later you can import the certs and private key in AWS ACM. Which you can later use it to apply to ELB or directly apply this certs and keys in web server. Simple isn't it. There are plenty of tutorials on the internet about how to generate CSR with openssl and private key, which you can get through your favorite web search engine like google. So I am not going to reiterate the steps. I leave to you to find out if you didn't know already.
Comment: Thanks man, that ended uo being much easier.

Install SSL certificate on AWS


Return the same Div when clicking + button in React JS

Question: i build this div element here , which at the end has a "+" button and a "x" button . The plus button adds the same div just below it and the x or clear button removes it . Now how can i render the same div when clicking plus button or when clicking x , i tried multiple ways but i couldn't do it , this is my code. One way that i think of is doing recursion but it doesn't work.

function IpRangeInput() {
  const [ipRange, setIpRange] = useState<string>('');
  const [inputValue, setInputValue] = useState<string>('');
  const [fromValue, setFromValue] = useState<string>('');
  const [toValue, setToValue] = useState<string>('');

  const handleInputValue = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(event?.target.value);
  };

  const handleAdd = () => <IpRangeInput />;

  return (
    <Box className={styles.inputContainer}>
      <ThemeProvider theme={theme}>
        <FormControl className={styles.inputContainer__select}>
          <Select
            defaultValue="Select"
            id="select-label"
            value={ipRange}
            onChange={(e) => setIpRange(e.target.value)}
          >
            <MenuItem value="IP/CIDR">IP / CIDR</MenuItem>
            <MenuItem value="Range">Range</MenuItem>
          </Select>
        </FormControl>

        {ipRange === 'Range' ? (
          <>
            From
            <Box
              className={[
                styles.inputContainer__input,
                styles.inputContainer__newInput,
              ].join(' ')}
            >
              <TextField
                value={fromValue}
                onChange={(e) => setFromValue(e.target.value)}
              />
            </Box>

            To
            <Box
              className={[
                styles.inputContainer__input,
                styles.inputContainer__newInput,
              ].join(' ')}
            >
              <TextField
                value={toValue}
                onChange={(e) => setToValue(e.target.value)}
              />
            </Box>
          </>
        ) : (
          <Box className={styles.inputContainer__input}>
            <TextField value={inputValue} onChange={handleInputValue} />
          </Box>
        )}

        <IconButton
          className={styles.inputContainer__addButton}
          onClick={handleAdd}
        >
          <AddIcon />
        </IconButton>

        <IconButton
          className={styles.inputContainer__clearButton}
          onClick={handleAdd}
        >
          <Clear />
        </IconButton>
      </ThemeProvider>
    </Box>
  );
}

Answer: Вам нужно хранить список блоков в родительском компоненте в стейте, например, как массив айди. Каждому блоку присваивается свой айди. И в итоге нажатие кнопок будет триггерить удаление или добавление айди в массив или из него
Ваш итоговый код:

function Parent () {
  const [list, setList] = useState([0])

  const handleAdd = (id) => setList(prevList => prevList.push(id + 1))

  const handleClear = (id) => setList(prevList => {
    prevList.splice(id, 1)
    return prevList
  })

  return (
    list.map((item) => {
      <IpRangeInput
        key={item}
        id={item}
        handleAdd={handleAdd}
        handleClear={handleClear}
      />
    })
  )
}

function IpRangeInput({ handleAdd, handleClear, id }) {
  const [ipRange, setIpRange] = useState<string>('');
  const [inputValue, setInputValue] = useState<string>('');
  const [fromValue, setFromValue] = useState<string>('');
  const [toValue, setToValue] = useState<string>('');

  const handleInputValue = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(event?.target.value);
  };

  const handleAdd = () => handleAdd(id)
  const handleClear = () => handleAdd(id)

  return (
    <Box className={styles.inputContainer}>
      <ThemeProvider theme={theme}>
        <FormControl className={styles.inputContainer__select}>
          <Select
            defaultValue="Select"
            id="select-label"
            value={ipRange}
            onChange={(e) => setIpRange(e.target.value)}
          >
            <MenuItem value="IP/CIDR">IP / CIDR</MenuItem>
            <MenuItem value="Range">Range</MenuItem>
          </Select>
        </FormControl>

        {ipRange === 'Range' ? (
          <>
            From
            <Box
              className={[
                styles.inputContainer__input,
                styles.inputContainer__newInput,
              ].join(' ')}
            >
              <TextField
                value={fromValue}
                onChange={(e) => setFromValue(e.target.value)}
              />
            </Box>

            To
            <Box
              className={[
                styles.inputContainer__input,
                styles.inputContainer__newInput,
              ].join(' ')}
            >
              <TextField
                value={toValue}
                onChange={(e) => setToValue(e.target.value)}
              />
            </Box>
          </>
        ) : (
          <Box className={styles.inputContainer__input}>
            <TextField value={inputValue} onChange={handleInputValue} />
          </Box>
        )}

        <IconButton
          className={styles.inputContainer__addButton}
          onClick={handleAdd}
        >
          <AddIcon />
        </IconButton>

        <IconButton
          className={styles.inputContainer__clearButton}
          onClick={handleClear}
        >
          <Clear />
        </IconButton>
      </ThemeProvider>
    </Box>
  );
}
Comment: Thanks i translated your solution , modified it a little bit , but it still worked thanks !


scikit-learn linear regressor digests perfectly collinear features?

Question: I am currently running this little piece of code:
import numpy as np
import sklearn.linear_model as skl_lm

X = np.random.normal(size = 1000)**2
y = X + np.random.normal(size = 1000)

Y = np.array([ [ X[i], X[i] ] for i in range(1000) ])

model = skl_lm.LinearRegression().fit(Y,y)
print(model.coef_)
print(np.dot(Y.transpose(),Y)/999)

It just creates 1000 squares of a normal random variable $X$, and uses it to create another linearly correlated variable $y$, accounting for some noise. Then creates a matrix of features $Y$, where the two features are actually both $X$. Then it tries to fit $y$ over $Y$. The model actually generates something, while the second print shows that the correlation matrix between columns of $Y$ is singular. How is sklearn.linear_model digesting this singular matrix? I believe it should not be able to determine the coefficients, as it should invert the covariance matrix.
Answer: Internally sklearn uses scipy.linalg.lstsq function for finding solutions to linear equation, which is the same as numpy.linalg.lstsq, and its innerworkings are described in this post: How does NumPy solve least squares for underdetermined systems?


n-th roots of unity

Question: Let $q$ be a prime power and $n$ a positive integer s.t. $\gcd(n, q) = 1$.
Let $E(n)$ be the set of the complex $n$-th roots of unity. For every positive integer $d$ such that $d | n$ , let
$$Q_d(x) := \prod_{\alpha \in E(n):\mathrm{ord}(\alpha)=d} (x- \alpha)$$
Why does follow from this that
$$x^n-1 = \prod_{d |n} Q_d(x)$$
Comment: where exactly does q appear in your question?
Does it have any relevance?
Comment: Is that over $\mathbb C$ ?
Comment: If two polynomials have leading coefficient $1$ and have the same roots, they have to be equal.
Answer: I don't know how your $q$ needs to be in the mix there but let me elaborate the other things a little bit. We will need a little bit of group theory and some facts from complex analysis.

A complex $n$-th root of unity is a solution to the equation $z^n=1$. That is, it is a root of the complex polynomial $z^n-1$. Lets call the set of all such roots $E(n)$. This set forms a group w.r.t. to complex multiplication (note that $1$ is an $n$-th root of unity for every $n$). Now, by the Fundamental Theorem of Algebra, there are at most $n$ distinct $n$-th roots of unity as $z^n-1$ is a polynomial of  degree $n$ and you can actually show that there are exactly $n$, i.e. $|E(n)|=n$.
I don't go into the details now, but you can express them as values of the exponential function.

Every such root $\lambda\in E(n)$ can be given an order $\mathrm{ord}(\lambda)\in\mathbb N$ which is the smallest $m$ such that $\lambda^m-1=0$, i.e. the degree of the polynomial of which it was first introduced as new root of unity.
E.g. note that $-1$ is a 4th root of unity but however it was already a 2nd root of unity and will be an $n$-th root of unity for every even $n$. Thus $\mathrm{ord}(\lambda)=2$ although $\lambda\in E(4)$ as well.
Now, taking an $n$-th root of unity $\lambda$, you have that the set
$$\{\lambda,\lambda^2,\dots,\lambda^{\mathrm{ord}(\lambda)}\}$$
forms a cyclic group generated by $\lambda$ with respect to complex multiplication. You can easily verify the closure of this under multiplication as $\lambda^{\mathrm{ord}(\lambda)}=1$.
Now, as $\lambda\in E(n)$ and $E(n)$ is itself a group w.r.t. complex multiplication, we have that
$$\{\lambda,\lambda^2,\dots,\lambda^{\mathrm{ord}(\lambda)}\}\subseteq E(n)$$
i.e. it forms a subgroup of $E(n)$. We now recite Lagrange's theorem from group theory:

Let $G$ be a finite group and $U$ a subgroup of $G$ (thus necessarily finite), then $|U|$ divides $|G|$.

We thus have, that $\mathrm{ord}(\lambda)=|\{\lambda,\lambda^2,\dots,\lambda^{\mathrm{ord}(\lambda)}\}|$ divides $n$.

Thus, every $n$-th root of unity has an order and every such order divides $n$.
Again, by the Fundamental Theorem of Algebra, we have that
$$z^n-1=\prod_{\lambda\in E(n)}(z-\lambda)$$
i.e. we can split the polynomial into linear factors of its roots and the $(z-\lambda)$ are pairwise distinct. If we define the polynomials
$$Q_d(z)=\prod_{\lambda\in E(n):\mathrm{ord}(\lambda)=d}(z-\lambda)$$
for every $d$ dividing $n$, then we naturally get
$$z^n-1=\prod_{d\mid n}Q_d(z)$$
as every such $(z-\lambda)$ occurs in exactly one $Q_d(z)$ once from the considerations before, where $d=\mathrm{ord}(\lambda)$ divides $n$.

A little fact, which is of no direct relation to your question but I really like mentioning it, is that understanding this formula
$$z^n-1=\prod_{d\mid n}Q_d(z)$$
is one of three steps towards a relatively simple proof of a fascinating theorem from abstract algebra which is:

Every finite division ring is a field.

i.e. in every finite division ring the multiplication operation is necessarily commutative. This is known as Wedderburn's little theorem and see this if it spiked you interest.
Comment: WOW! Thank you very, very much for this phenomenal answer!
Comment: @JohnD I'm flattered, you're very welcome.
Answer: There are essentially $3$ relatively straightforward facts (and one complicated one) required to draw the required conclusion.
The first is that if $\alpha ^n-1=0$, $ord(\alpha)\mid n$.
This is a direct consequence of Euclid's division lemma/ the division algorithm and the definition of the order of the element- the order of an element, $\alpha$, is defined as the smallest positive integer, $m$, such that $\alpha^m=1$ (in this context). Suppose then that we are given an $n$ such that $\alpha^n-1=0$. $n$ is just an integer and $ord(\alpha)$ is just some positive integer so we may use the division algorithm to write $n=ord(\alpha)k+r$ where $k$ is an integer and $r$ is an integer such that $0\leq r<ord(\alpha)$.
But this gives us that $$\alpha^n=1\implies \alpha^{ord(\alpha)k+r}=1\implies (\alpha^{ord(\alpha)})^k\alpha^r=1\implies (1)^k\alpha^r=1\implies\alpha^r=1$$
And so, if $r$ were any non-zero number we would have a contradiction as $r$ is a positive integer that is $<ord(\alpha)$ but we still have $\alpha^r=1$ despite the fact that $ord(\alpha)$ was itself defined to be the smallest such positive integer- it follows that $r$ must be $0$ and so, if $\alpha^n-1=0$, $ord(\alpha)\mid n$.
The second important fact is that if $r$ is a root of the polynomial $p(x)$, then $(x-r)$ divides $p(x)$
This results, likewise, from the division algorithm but this time for polynomials. Suppose $p(x)$ has a root $r$. We consider the division algorithm applied to $p(x)$ with a divisor of $(x-r)$. $$p(x)=(x-r)q(x)+t(x)$$ where $t(x)$ is either the $0$ polynomial or $t(x)$ has order strictly less than that of $(x-r)$. If $t(x)$ is the $0$ polynomial, we are done. Otherwise, we note that since $(x-r)$ is of degree $1$, $t(x)$ must be of degree $0$, i.e. a constant polynomial so $t(x)=t$. $$p(x)=(x-r)q(x)+t$$ But if we plug $r$ into the above equation. we get $$p(r)=0\implies (r-r)q(r)+t=0\implies t=0$$ which contradicts the assumption that $t(x)$ was not the zero polynomial. Hence, if $r$ is a root of $p(x)$, $(x-r)$ divides $p(x)$.
The third is that any polynomial in the polynomial ring, $F[X]$ of a field, $F$, has a root in a suitable field extension, $K\supset F$ OR just The Fundamental Theorem of Algebra  .
This is the one slightly complicated bit- the main purpose of this is that it allows us to say that $x^n-1$ has roots. More technically, a field is basically a set of elements with operations of addition, multiplication, division, etc. defined so that they have all the nice properties we see in things like standard addition or multiplication on the reals (like commutativity and distributivity). The bit above in bold before the "OR" basically states that for any polynomial, $s(x)$, with coefficients in some field, $F$, there exists another field, $K$, such that $K\supset F$ and a root of $s(x)$ lies in $K$. Since each field has a multiplicative identity, the roots of $x^n-1$ have the same basic algebraic properties in all fields so one can simply refer to the FTA instead. It may also seem rather odd to bring up the statement about field extensions given that it seems to be more general than the FTA (making a claim about all fields instead of just $\mathbb C$) but the FTA's strength comes from its claim about that $\mathbb C$ is algebraically closed- the statement about fields in general doesn't tell you where the root will be, effectively- just that one exists. The FTA, on the other hand, tells you both that the roots will exist and that they will lie $\mathbb C$ but this result clearly isn't a general one. This is why, in a sense, the FTA is stronger and also why its proof necessarily involves a topological element. If you know a bit about polynomial rings, you can find a sketch of the ideas in the question and answer here
The reason this is important is that it tells us that any polynomial can be factored as $\prod_{r\in ROOTS} (x-r)^{m_r}$ where $m_r$ is the multiplicity of each root and $ROOTS$ is the set of all roots of the polynomial.
We can see this by using the third fact- $p(x)$ has a root, $r_1$, (in some suitable extension or in just $\mathbb C$ if you like). The third fact tell us we can write $p(x)$ as $(x-r_1)q_1(x)$. $q_1(x)$ is a new polynomial- it too has some root, $r_2$ so we may write $p(x)=(x-r_1)((x-r_2)q_2(x))=(x-r_1)(x-r_2)q_2(x)$. We keep repeating this process- we stop at exactly the $deg(p(x))$th step because the degree of each $q_r(x)$ is less than the degree of each $q_{r-1}(x)$ and so $q_{deg(p(x))-1}$ will be linear. It may, of course, be the case that some $r_k$ equals some $r_j$ in which case the multiplicity of the root $r_j=r_k$ is greater than one- this manifests as the power of each term in the product ($ROOTS$ is a set).
The final important fact is that $x^n-1$ never has repeated roots
The three facts above this one tell us that we can write $x^n-1$ as $\prod_{r\in ROOTS}(x-r)$ but there is something we must be careful of- the possibility of $x^n-1$ having repeated roots. The third fact assured us that any polynomial will always have some root, and, hence, that it can be factored as a product of linear polynomials in its roots but there was no assurance that those roots need be distinct (as mentioned before). For instance, the polynomial $x^3-8x^2+21x-18$ factors as $(x-3)^2(x-2)$. Can something like this happen with $x^n-1$? As it turns out, no. This is a result of a property of repeated roots and how they affect the relationship between a polynomial and its formal derivative. Simply put, the formal derivative of a polynomial $$a_nx^n+a_{n-1}x^{n-1}+...+a_1x+a_0$$ is $$na_nx^{n-1}+(n-1)a_{n-1}x^{n-2}+...+2a_2x+a_1$$ The benefit of using the formal derivative lies in the many properties it inherits from the calculus-style definition of a derivative (the sum rule, the product rule, etc.) but it is, of course, a formal operation on polynomials over rings rather than the limit of a quotient. The key fact here is that, if a polynomial has no factor of degree at least $1$ in common with its formal derivative, it has no repeated roots. The contrapositive of this is fairly simple- if $p(x)$ has a repeated root $r$, then we may write $p(x)=(x-r)^2q(x)$ for some $q(x)$. By the properties of the formal derivative, $p'(x)=(x-r)^2q'(x)+2(x-r)q(x)$ so that $x-r$ is a factor with degree $\geq 1$ of both $p(x)$ and $p'(x)$.
In the case of $x^n-1$, our formal derivative is $nx^{n-1}$ which clearly has no factor of degree $\geq 1$ in common with $x^n-1$, giving us that $x^n-1$ has distinct roots.
The problem at hand
Now, we turn our attention to the product in the question. By the first fact, each root of $x^n-1$ has an order that divides $n$. This means, for any root $r$ of $x^n-1$, the polynomial $x-r$ appears at least once among all the $Q_d(x)$'s. Then, since each root, $r$, of $x^n-1$ has a unique order (by the definition of an element's order), each $x-r$ occurs exactly once among all the $Q_d(x)$. This gives us that $Q_d(x)=\prod_{r\in ROOTS, \\distinct} (x-r)$.
By fact three, $x^n-1$ can be written as $\prod_{r\in ROOTS}(x-r)^{m_r}$ where $m_r$ is the multiplicity of each root. Finally, by fact four the multiplicity of each root is simply $1$ so that $$x^n-1=\prod_{r\in ROOTS}(x-r)^{m_r}=\prod_{r\in ROOTS} (x-r)^1=\prod_{r\in ROOTS, \\distinct} (x-r)=\prod_{d\mid n}Q_d(x)$$
(please comment or edit for any corrections)
Edit: removed some extraneous details and fixed some errors
Comment: ${WOW}^2$ Thank you very, very much for this great answer! One question and two great answers...thank you!! =)

n-th roots of unity


If não faz comparação de Char

Question: Criei no codeigniter um helper para o datatable que retornaria um html com um ícone do bootstrap.
Segue a função:
function trata_check($valor)
{
    $ci= & get_instance();

    if($valor=='S'){
                $html='';
            }
            else{
                $html='';
            }

    return $html;
}

A parte que chama a função no controller é essa:
->edit_column('diario', trata_check('$1'),'diario')

O problema é que a comparação if($valor=='S') não esta sendo feita, esta sempre retornando falso, mas quando eu mando só retornar o parâmetro passado ela retorna o valor certo, que pode ser apenas S ou N.
Comment: O problema está em como você está chamando o helper, pois o que você está passando é a string '$1', não o valor da variável $1.
Comment: Para passar o valor use aspas dupla, trata_check("$1")
Comment: Na pode ser a forma que está passando o parâmetro para dentro da função? você está usando aspas simples, consequentemente o que será passado seria o valor $1 e não o valor da variável
Comment: O valor esta sendo passado sim, tanto que se eu mandar ele apenas retornar o valor ele retorna normal, o problema esta na comparação. De qualquer forma, tentei a sugestão e não foi.
Comment: De onde vez o $1?
Comment: Ele é utilizado para passar parâmetros na função edit_colum do CI.
Answer: A chamada da função estava sendo feita errada, do modo que estava o valor era passado, mas ficava com algumas sujeiras na memória, logo ele achava que S era diferente do valor passado.
Segue a maneira correta:
>edit_column('diario', '$1','trata_check(diario)')

Obrigado a todos.
Answer: Dê um isset na váriavel soma, acho que irá resolver.
function trata_check($valor)
{
 $ci= & get_instance();

 if(isset($valor)=='S'){
  $html='';
 }
 else{
  $html='';
 }

 return $html;

Comment: Continua retornando sempre true.

If não faz comparação de Char


Functions of sequences and convergence

Question: (a) If $f$ is continuous on $[0,\infty)$ and {$x_n$} is a sequence in $(0,\infty)$ such that {$f(x_n)$} diverges to $\infty$, then $\lim_{n \to \infty} x_n = \infty$.
(b) If $f$ is continuous on $(0,\infty)$ and {$x_n$} is a sequence in $(0,\infty)$ such that {$f(x_n)$} diverges to $\infty$, then $\lim_{n \to \infty} x_n = \infty$.
Are the statements true of false? If true, prove. If false, give a counterexample.
I think the first one is false and the second one is true. Can anyone help me to come up with a counterexample for (a) and a proof for (b) please?
Answer: (b) is false, $f(x)=\frac{1}{x}$ is continuous on $(0,\infty)$.  Take $x_n=\frac{1}{n}$.
$\lim_{n\rightarrow\infty} x_n=0$ and $\lim_{n\rightarrow\infty}f(x_n)=\infty$.
I'm not sure if the proofs of (a) given are complete, since $\lim_{n\rightarrow\infty}x_n\ne\infty$ does not imply $\lim_{n\rightarrow\infty} x_n<\infty$ or even that $\{x_n\}$ is bounded.
Answer: a) A continuous image of a compact set is compact, hence if $\{f(x_n)\}$ is unbounded, $\{x_n\}$ cannot be bounded.
b) is obviously false. See $f(x)=1/x$.
Hence we cannot prove and disprove what you want to. ;-)
Comment: Oh ok, so I was completely on the wrong track here. Thanks a lot for clarifying! :)
Answer: For a) you can think a contradition argument, suppose that $\lim x_n<\infty$, since $x_n\in(0,\infty)$ ther exists $C>0$ such that $0<x_n\leq C$, since $(0,C]\subset[0,C]$ we have that $f([0,C])$ is bounded (because $f$ is continuous), contradiction.

Functions of sequences and convergence


How to convert delegate from c# to vb.net?

Question: I have this code i'm trying to convert from C# to VB.net:
public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            // Create a new, STA thread
            object[] staOutputs = null;
            object retval = null;
            Thread thread = new Thread(
                delegate(){
                    retval = _innerInvoker.Invoke(instance, inputs, out staOutputs);
                });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            outputs = staOutputs;
            return retval;
        }

The whole delegate thing is throwing me off. Can anyone help me convert this? Or is there an article that explains how to do it?
Answer: It's an anonymous function, and VB.Net does not support anonymous functions like that (assuming .Net 2.0, since in .Net 3.5 that would be written as a lambda expression).
The best you can do in VB.Net is add the anonymous function (the delegate) as a separate method in the same class and use the AddressOf operator to reference this new method.

Update:
Reading your code again, the translation is complicated because your anonymous method will be interpreted as a closure, and that means the C# compiler does a complicated transformation on the code before turning it into IL; a whole new class is created is to capture (close over) the local variables referred to in the method:
Class InnerInvokerClosure
    Public instance As Object
    Public inputs() As Object
    Public staOutputs() As Object
    Public retValue As Object

    Public _innerInvoker As SomeDelegateType

    Sub New(ByRef instance as Object, ByRef inputs() as Object, ByRef staOutputs() As Object, ByRef retValue As Object, ByRef _innerInvoker As SomeDelegateType)
        Me.instance = instance
        Me.inputs = inputs
        Me.staOoutputs = staOutputs
        Me.retValue = retValue

        Me._innerInvoker = _innerInvoker
    End Sub

    Public Function Invoke() As Object
        retValue = _innerInvoker.Invoke(instance, inputs, staOutputs);
    End Function

End Class

Public Function Invoke(ByVal instance As Object, ByVal inputs() as Object, ByRef outputs() As Object) As Object
    Dim closure As New InnerInvokerClosure(instance, inputs, Nothing, Nothing, _innerInvoker)

    Dim t As New Thread(AddressOf closure.Invoke)
    t.SetApartmentState(ApartmentState.STA)
    t.Start()
    t.Join()

    outputs = closure.staOutputs
    return closure.retValue
End Function

Note that this translation is untested and probably wrong: the exact transformation can be very complicated.
Comment: Can you give me an example in some sudo code? Still having a hard time wrapping my head around this...
Answer: My fav way to do this is to compile in C#, and then use reflector to see what it looks like in other dotNET languages.
Friend Class Program
' Methods '
Private Shared Function Foo(ByVal instance As Object, ByVal inputs As Object(), <Out> ByRef outputs As Object()) As Object
    outputs = Nothing
    Return Nothing
End Function

Public Function Invoke(ByVal instance As Object, ByVal inputs As Object(), <Out> ByRef outputs As Object()) As Object
    Dim staOutputs As Object() = Nothing
    Dim retval As Object = Nothing
    Dim thread As New Thread(Function
        retval = Me._innerInvoker.Invoke(instance, inputs, staOutputs)
    End Function)
    thread.SetApartmentState(ApartmentState.STA)
    thread.Start
    thread.Join
    outputs = staOutputs
    Return retval
End Function

' Fields '
Private _innerInvoker As MyInvoker = New MyInvoker(AddressOf Program.Foo)
End Class

<CompilerGenerated> _
Private NotInheritable Class <>c__DisplayClass1
' Methods '
Public Sub <Invoke>b__0()
    Me.retval = Me.<>4__this._innerInvoker.Invoke(Me.instance, Me.inputs, Me.staOutputs)
End Sub

' Fields '
Public <>4__this As Program
Public inputs As Object()
Public instance As Object
Public retval As Object
Public staOutputs As Object()
End Class

Answer: SOmethiong like the following ought to it: (Where _ are private fields (this is not production rdy but hope fully give you the idea)
Public Function Invoke(instance As Object, inputs As Object(), ByRef outputs As Object()) As Object
        ' Create a new, STA thread
        Dim staOutputs As Object() = Nothing
        Dim retval As Object = Nothing
        Dim thread As New Thread(AddressOf(Do))

        _instance = instance
        _inputs = inputs
        _staOutPuts = staOutputs
        thread.SetApartmentState(ApartmentState.STA)
        thread.Start()
        thread.Join()
        outputs = staOutputs
        Return retval
    End Function

    private Function Do() as Object
    Return _innerInvoker.Invoke(_instance, _inputs, _staOutputs)
    end Function

Answer: Here is the final code i used:
    Public Function Invoke(ByVal instance As Object, ByVal inputs As Object(), ByRef outputs As Object()) As Object Implements System.ServiceModel.Dispatcher.IOperationInvoker.Invoke
        Dim staOutputs As Object() = Nothing
        Dim retval As Object = Nothing
        Dim thread As New Thread(AddressOf DoWork)
        _instance = instance
        _inputs = inputs
        _staOutPuts = staOutputs
        thread.SetApartmentState(ApartmentState.STA)
        thread.Start()
        thread.Join()
        outputs = staOutputs
        Return retval
    End Function

    Private Function DoWork() As Object
        Return _innerInvoker.Invoke(_instance, _inputs, _staOutPuts)
    End Function

@Rune FS - so close, just needed a little help. Thanks!
Comment: Never having code one single VB.NET program Im reasonably satisfied with the result lol
Answer: there is an online C# to VB converter (and vice-versa) located at http://converter.telerik.com/
I pasted your code in there....I dont know if this is valid VB or if it will work or not, but you can give it a shot.
Public Function Invoke(instance As Object, inputs As Object(), ByRef outputs As Object()) As Object
    ' Create a new, STA thread
    Dim staOutputs As Object() = Nothing
    Dim retval As Object = Nothing
    Dim thread As New Thread(Function() Do
        retval = _innerInvoker.Invoke(instance, inputs, staOutputs)
    End Function)
    thread.SetApartmentState(ApartmentState.STA)
    thread.Start()
    thread.Join()
    outputs = staOutputs
    Return retval
End Function

Comment: Agreed, first place i went was a c# to vb.net converter. it basically threw me an error: VB does not support anonymous methods/lambda expressions with a statement body


How to use rendered file entity in view header as background image for view

Question: I would like to set a background image on a div in my views-view.tpl.php using the image from a rendered entity field in the View Header.
Something like:

      <?php print render($title_prefix); ?>
      <?php if ($title): ?>

<?php print t($title)?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

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

How do I print just the url of the entity from the header? It would be great if I could pull the image URL and add an inline style on the group-header div. Any ideas on how to accomplish this?
Similar to this question: Use image from view as background image of div in page.tpl.php
Comment: Are you willing to use jQuery/JS?
Comment: Could u post the template file?
Answer: Is there something the Background Images Formatter module can do for you?
The module allows you to set a background to any CSS selector(s) you can think of. Combine it with a selector built with NID-token (NID field in Views, excluded from display, and its token used in the selector you assign the background-image to), and it will probably save you some templating headaches.
Answer: The simplehtmldom parser will be helpful to render this for you.
https://www.drupal.org/project/simplehtmldom
we can supply the html to this parser and capture the output by the APIs provided.
http://simplehtmldom.sourceforge.net/manual.htm
http://simplehtmldom.sourceforge.net/manual_api.htm
      $html_obj = new simple_html_dom();

      $wrapped_header = "
{$header}";
      $html_obj->load( $wrapped_header );
     $url_forimage="";
      // use the wrapped class
      foreach ($html_obj->find('header_url') as $plain_text_obj ) {
//get class of the rendered element and use that to capture the src tag.
//check API for more info. you should list them in the DOM hierarchy.
//I have used this DOM hiearchy "div.views-field-field-banner-image > div > a > img" for the below code.

           $url_forimage= $plain_text_obj->find('div[class=views-field-field-banner-image] div a img',0)->src;
          }

      <div class="group-header" style="background-image:<?php print $url_forimage;?>">

          <?php print render($title_prefix); ?>
          <?php if ($title): ?>

<?php print t($title)?>

          <?php endif; ?>
          <?php print render($title_suffix); ?>

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

You will need work on this to get it work.


Adicionar imagem em um CollapsingToolbarLayout

Question: Gostaria de adicionar uma imagem de fundo em um CollapsingToolbarLayout conforme este exemplo:

Tentei da seguinte forma:
   <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:background="@drawable/blue_sky"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

Mas exibe a penas a cor de fundo!
Como posso adicionar a imagem?
Comment: Este exemplo é de algum site?
Comment: sim! do stackOverflow em Inglês, adicionei para ilustrar minha dúvida
Answer: Use esse:
<android.support.design.widget.CoordinatorLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="@dimen/height_CollapsingToolbarLayout"
    android:id="@+id/appBar"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="@color/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

       <ImageView
            android:id="@+id/ivPerfilCl"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/logo"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"

            />

        <android.support.v7.widget.Toolbar
            android:id="@+id/tbDetalhes"
            android:layout_width="match_parent"
            app:layout_collapseMode="pin"
            app:theme="@style/toobar"
            app:layout_scrollFlags="scroll|enterAlways"
            android:layout_height="?attr/actionBarSize"
            android:minHeight="?attr/actionBarSize"
            />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/nested"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:borderWidth="0dp"
    android:src="@drawable/ic_event_available_white_24dp"
    app:layout_anchor="@id/appBar"
    app:layout_anchorGravity="bottom|right|end"
    android:elevation="2dp"
    android:layout_marginRight="16dp"
    android:id="@+id/FABParticiparDaAtividade"
    app:fabSize="normal"
    />
</android.support.design.widget.CoordinatorLayout>

No meu funciona. Olha como ficou.
Comment: A dimensão é 504x404.
Comment: Então, aqui não rolo! não exibe a imagem !  Criei esta tela a partir do exemplo da Android Studio. Vc alterou algo no ThemeOverlay.AppCompat.Dark.ActionBar? Valeu!!!
Comment: Cara se não funcionar agora, o problema não é no layout
Comment: Poderia me dizer a dimensão da imagem de fundo? Obrigado!


How to use Selenium find_element_by_something function with no wait time if the element is not there?

Question: Sometimes you want to do an action over an object that may or may not be in a page, obviously you would only want to execute the action if the object is present on the page, but if the object is not present that is also ok, but you don't want the automation to break. Right now, I have been handling this situation in two different ways:
Using a find_elements_by_something method along with an if:
my_var = driver.find_elements_by_xpath(some_xpath)
if len(my_var) > 0:
    # the element is present so do the action

Using a find_element_by_something method along with a try:
try:
    my_var =  driver.find_element_by_id(some_id)
    # do the action
except:
    # do something else

Both methods mentioned above work, but they have a big problem, they both make the automation slow because both try to find the element(s) using the driver timeout, so it can take a while.
Is there a way to try to find an element without using any timeout? If the element is not there in that instant in time that is ok, I don't want selenium to wait for it for a while, I just want to know if the element is there or not.
Solution:
Based on the response from @grumpasaurus
driver.implicitly_wait(0)
try:
    my_var =  driver.find_element_by_id(some_id)
    # do the action
except:
    # do something else
driver.implicitly_wait(old_wait_time)

Comment: This link has a lot of good information:  http://stackoverflow.com/questions/7781792/selenium-waitforelement
Comment: It would be helpful to post your solution as an answer and accept it. It's more quickly digestible than the currently accepted answer.
Answer: I believe you're looking into an Explicit/Implicit Wait situation.
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
Selenium allows you to change the implicit wait as you go through your test to change how long you want to wait for an element to show up.  Technically you can change it to 0 have a rescue clause handy if you don't want to fail your test.
Comment: This was a good solution, following your suggestion what I did was turning off explicit waits before doing the find_element_by and then turning it back on after that and it worked like a charm.
Comment: Yay! Uh... 4 more characters were needed... Yay!
Answer: You can simply make sure it's in the page source before using any of the methods above.
For example:
str1 = 'id="'+some_id+'"'
str2 = "id='"+some_id+"'"
page_source = driver.page_source
if str1 in page_source or str2 in page_source:
    try:
        my_var = driver.find_element_by_id(some_id)
        # do the action
    except:
        # do something else

This should significantly reduce the number of times that you attempt to find an element which is not in the DOM (false-negative). Of course, if the element is dynamically added to the DOM on the client side (using Javascript), then you might revoke an attempt to find it when it's actually there (false-positive).
So you should make a careful inspection of the web-page before you choose to apply this method...
Comment: That solution could work in some cases, like when trying to find an element using its Id. But what if I want to find an element using its Xpath which is the case in a lot of the times?
Comment: @Cas: Well, then you will have to do a more sophisticated string-search in `page_source`.


How to use DaoImpl functions with DSLContext JOOQ

Question: we noticed randomly dropping database connections (postgres) in our software. Searching through the Jooq documentation, I found that every call of set() methods after initialization may remove thread-safety of the whole framework.
Therefore, my approach is to refactor every method in our BaseDAO getting rid of setConfiguration() function and changing to a DSLContext.
E.g.
public TransactionalCallable<Optional<T>> get(I id) {
        return cfg -> {
            try {
                base.setConfiguration(cfg);
                return doGet(id).map(p -> Optional.of(from(p))).orElse(Optional.empty());
            } finally {
                base.setConfiguration(null);
            }
        };
    }

protected Optional<E> doGet(I id) {
        return Optional.ofNullable(base.findById(id));
    }

base is an instance of DaoImpl.
So how would I implement base.findById(id) using a DSLContext?
Did I understand something wrong regarding thread-safety?
Edit: I started with something like this
   public TransactionalCallable<Optional<T>> get(I id) {
        return cfg -> doGet(id).run(cfg).map(p -> Optional.of(from(p))).orElse(Optional.empty());

    }

    protected TransactionalCallable<Optional<E>> doGet(I id) {
        return cfg -> {
            try (DSLContext context = using(cfg)) {
                return Optional.ofNullable(base.findById(id));
            }
        };
    }

But still not sure how to use that context correctly.
Comment: Why do you set configurations at all? Ideally you would set up your configuration and daos only once and never tamper with configuration state again... From your question, it's not clear what you did wrong *specifically*, but it does seem you're doing a few unnecessary things, including e.g. wrapping `DSLContext` in `try-with-resources`, which doesn't do anything in your case...
Comment: Mainly because each tenant has its own database with a different configuration. Also, because the system can spawn new tenants on the fly. I thought of different approaches like having a DAO instance for each tenant, holding its own configuration. Nonetheless, my hoped was to do it somehow with the DSLContext. I know that the try-with part is not necessary. That was my approach on how I thought I could use the context to execute the findbyid() function using that context. I strongly agree, the best way would be to not to temper with the state.. maybe I have to find a way to do this eventually.
Answer: The problem I suspect is leading to your observed side effects, which I can spot in your code here:
public TransactionalCallable<Optional<T>> get(I id) {
    return cfg -> {
        try {
            base.setConfiguration(cfg);
            return doGet(id).map(p -> Optional.of(from(p))).orElse(Optional.empty());
        } finally {
            base.setConfiguration(null);
        }
    };
}

... is that you're doing something once per transaction, which should be done only once per tenant: setting the configuration in some context.
It's a lifecycle problem. You seem to be sharing a resource (base) across transactions. If this is a shared resource, then it must not be modified per transaction. It should be possible for this base to have a lifecycle that corresponds to the tenant lifecycle, or even the application lifecycle, and thus never having to worry about setting this resource again.


Bolzano-Weierstrass and zeros of complex analytic function

Question: I am working on a textbook exercise. A similar question: An analytic function in a compact region has finitely many zeros, but it's not quite clear to me and I also have possibly another approach? I want to prove basically the same question, that if $f$ is analytic inside and on a simple closed contour $C$ (except possibly for poles inside $C$), and if all zeros of $f$ are inside $C$ and of finite order, then the zeros must be finitely many.
Hopefully my attempt below can be verified or corrected.
My attempt:
Suppose otherwise. Then by Bolzano-Weierstrass, the set $S$ of all zeros of $f$ (which is infinite) contains an accumulation point inside $C$. Let's say it is $z_0$. This $z_0$ is also a zero of $f$ since it is the limit a subsequence of zeros in $S$ and $f$ is analytic (hence continuous too). By assumption, it is a zero of finite order, say $m$.
I claim that in any neighborhood $N$ of $z_0$, $f$ cannot be identically zero. To see this, write $f(z)=(z-z_0)^mg(z)$ where $g$ is nonzero and analytic at $z_0$. Hence by these properties of $g$, there is a neighborhood around $z_0$ (intersected with $N$) where $g$ is nonzero. However, this neighborhood contains another (different) zero, say $z'$, of $f$ by definition of accumulation point. Hence, $0=f(z')=(z'-z_0)^mg(z')$, implying that $g$ can be zero in this neighborhood, a contradiction.
Now by a theorem in the textbook, since $f$ is analytic and zero at $z_0$, but not identically zero in any neighborhood of $z_0$, there must be a deleted neighborhood of $z_0$ where $f$ is identically nonzero. But again, in this deleted neighborhood contains a zero of $f$, say $z''$, by definition of accumulation point, contradicting $f$ being identically nonzero there. QED.
So my questions would be:

Is the above valid? If not, which part should be improved?

Are there any other approaches?

Usually Q2 is more interesting, but I highly appreciate if Q1 is answered too. Thanks a lot!
EDIT: Now that I think about it after some comment inputs:
My first paragraph should be fine.

As for my second paragraph until conclusion, I should do it like this:

As $z_0$ is of order $m$, we can write $f(z) = (z-z_0)^m g(z)$ where $g$ is analytic and nonzero at $z_0$. By continuity of $g$ and being nonzero at $z_0$, there is a neighborhood at $z_0$ where $g$ is identically nonzero. Deleting $z_0$ there, $f$ is then nonzero in that deleted neighborhood. However, this contradicts the fact that $z_0$ is an accumulation point of zeros. Done?
OR

Another method, I can also say: Either $f$ is not identically zero in any neighborhood $N$ of $z_0$ , or $f$ is identically zero in some neighborhood $N$ of $z_0$ . For the former, my original third paragraph follows to conclude. For the latter, by identity theorem $f$ must be identically zero inside $C$. By analyticity, their derivatives of all order are zero, showing infinite order. Done?
Comment: The "except " part is something I was missing.
Comment: You wrote "In any neighborhood $N$ of $z_0$, $f$ cannot be identically zero" . Why? This is almost like assuming what you want to prove, which is: an analytic non-zero function in a non-empty compact region can have only a finite number of zeros in it".
Comment: The reason is in the next sentence. I think I wrote it not in a natural way. I just edited it, adding "I claim that".
Comment: Your understanding is correct, except that in the second paragraph you proved that if the zeros have an accumulation point where $f$ is analytic then $f$ must be identically $0$ around it, thus by analytic continuation / identity theorem it must be identically $0$ in the whole connected component.
Comment: @DonAntonio I think I realize my mistake. I have put two edits, two methods but similar conclusion.
Comment: @reuns I see. I hope you guys can check out my edits. Edit no. 2 is inspired by your comment. Is that what you mean? I think edit no. 1 is OK too?
Comment: @10understanding I think you make the whole question and  "proof" messier than it needs to be, less clearer and less straightforward. You insist in saying something like "...as $\;z_0\;$ is of order $\;m\;$ ..."  who says? Where was that assumption given The very question you're tying to prove is already given in a rather confusing way. You wrote "...f $f$ is analytic inside and on a simple closed contour $C$ (except possibly for poles inside $C$)? ..." That's a contradiction: either it is analytinc (and thus no poles at all), or else it is meomorphic (some isolated singularities...) !
Comment: @DonAntonio Thanks for the response. I mentioned "$z_0$ is of order $m$" because in my "Suppose otherwise ..." paragraph, I showed that $z_0$ is a zero of $f$, so by problem assumption, it is of finite order. Hence, I am not insisting it, unless this paragraph has anything wrong (which is my question too as I am not too sure). Also, "... $f$ is analytic inside and on a simple closed contour (except ...)$ is the assumption. How is it a contradiction?
Answer: I propose the following: let us prove that  if a function $f$ is analytic in the region $R$ consisting of all points inside and on a simple closed contour $C$, except possibly for poles inside $C$, and if all the zeros of $f$ in $R$ are interior to $C$ and are of finite order, then those zeros must be finite in number.  I think we must add the condition that $\;f\;$ isn't identically equal to zero in any non-trivial open, connected subset of $\;R\;$ . This is from a book (I already found a paper about this from 1981...) which I still cannot locate and it seems to be something very close to what you actually want. Observe that the conditions above for the function $\;f\;$ actually say the function's meromorphic on the domain enclosed by $\;C\;$ .
Proof: Suppose there are infinite zeros $\;\{z_1,z_2,...\}\;$ of $\;f\;$ inside $\;C\;$ . Then by Bolzano-Weierstrass, there exists $\;z_0\;$ on $\;R\;$ s.t. $\;\lim\limits_{n\to\infty}z_n=z_0\;$ . By continuity of $\;f\;$ , we get that $\;f(z_0)=0\;$ , too.
Since we're assuming all the zeros of $\;f\;$ on $\;R\;$ are of finite order and isolated, there exists $\;m\in\Bbb N\;$ s.t. $\;f(z)=(z-z_0)^mg(z)\;$ , in some open neighborhood $\;U\;$  of $\;z_0\;$ and for some meromorphic function $\;g\;$ s.t. $\;g(z)\neq0\;\;\forall\,z\in U\;$ . Since the possible poles of $\;f\;$ inside $\;C\;$ are isolated, we can take a neighborhood $\;V\;$  of $\;z_0\;$ where there are no poles of $\;f\;$  inside $\;V\;$ , and take the above relation $\;f(z)=(z-z_0)^mg(z)\;$ in $\;U':=U\cap V\;$, and this time $\;g\;$ is non-zero and analytic in $\;U'\;$ .
Thus we are almost thru, since then by the identity theorem of analytic functions we'd get that $\;f\;$ would be identically zero in some connected neighborhood of $\;z_0\;$ , since this point is an accumulation point of a set where $\;f\;$ and the zero function coincide, and this contradicts the further condition added above.
Comment: Thanks. It kinda looks similar but more organized. I will accept it.


Is there a print function in Java that is not blocking the UI?

Question: In my Java application, there is a printing function.
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(myJobName);
pj.setPrintable(myPrintableObject);
if ( pj.printDialog() == false ) {
  return;
}
pj.print();

While the printing job hasn't finished, I am not able to click something else in the UI, because the printing-Job is blocking.
The same applies to the print function of JTextPane:
JTextPane jtp = new JTextPane();
       ...
jtp.print(null, null, show, null, null, show);

Is there any possiblity of printing in Java without blocking the UI or do I have to realize that by myself with multiple threads?
Comment: Wrap the Printing task in a `Runnable` and pass it to a `Thread`
Answer: Your problem is that you are invoking these methods from the main event dispatcher thread. That thread exists to serve your UI - it should not be used for any long term activities. Because when you occupy that thread it can't handle events any more and your ui freezes!
You should wrap them into their own threads instead. Or use something like a SwingWorker.
Comment: Thanks! I used a SwingWorker, which was pretty pretty easy. :)


Categorising types of Mathematics

Question: What area of Math do the following fall under?
1) Systems of ODEs and Phase planes
2) Laplace Transforms
3) Fourier series
4) PDEs with grad, div, curl, flux
Comment: [Analysis](http://en.wikipedia.org/wiki/Mathematical_analysis)
Answer: The links below are to the Mathematical Atlas. Most of these fall under the large area called analysis.
1) and 4) are (surprisingly?) differential equations. Maybe someone else can provide more insight than I can? As for div and curl, these can be studied in more generality in differential geometry.
2) The Laplace transform is a technique that is used both in differential equations as well as in probability theory.
3) Following the theme, Fourier series can be used in differential equations, but if you want to look deeper, Fourier analysis and harmonic analysis deal with the more theoretical questions like convergence criteria, existence/uniqueness, figuring out in which function spaces will the Fourier transform work, etc.

Categorising types of Mathematics


How to control start and stop of libvirtd and virtlockd in pacemaker cluster?

Question: Using indirect locks of virtlockd (which is used by libvirtd) requires to use a cluster-wide shared filesystem like OCFS2.
In turn this means that virtlockd must be started after the shared filesystem is mounted (otherwise the locks created would be local at best).
Naturally libvirtd must be started after virtlockd, and any VM after virtlockd.
So I want for start: pacemaker, DLM, OCFS mount, virtlockd, libvirtd, VMs...
And for stop I want the opposite direction.
I have configured all those primitives (specifically systemd:libvirtd.service and systemd:virtlockd), clones and constraints correctly (I hope), but still I'm having issue with virtlockd.
In a system like SLES15 systemd is controlling those services, and it seems systemd has its own life controlling (starting) services even if they are all disabled.
So the question: Did anybody manage to succeed with such a setup?
Update (2021-02-04)
I found this "Drop-In" in the status output for virtlockd.service:
/run/systemd/system/virtlockd.service.d/50-pacemaker.conf
It contains:
[Unit]
Description=Cluster Controlled virtlockd
Before=pacemaker.service pacemaker_remote.service

[Service]
Restart=no

A corresponding file /run/systemd/system/libvirtd.service.service.d/50-pacemaker.conf exists:
[Unit]
Description=Cluster Controlled libvirtd.service
Before=pacemaker.service pacemaker_remote.service

[Service]
Restart=no

Could these cause the problems I'm seeing (systemd starting libvirtd-ro.socket, libvirts-admin.socket and libvirtd.service, then starting virtlockd)?
Update (2021-02-05)
It seems the resources are started in the correct order when the node boots (e.g. after being fenced), but when pacemaker is restarted (e.g. via crm cluster restart), systemd interferes and starts the virtlockd before pacemaker wants to start it.
Maybe the difference is the /run directory.
Update (2021-02-08)
Another issue I found is that even though /etc/libvirt/libvirtd.conf contains listen_tls = 1, starting libvirtd through pacemaker as indicated results in a libvirtd not having opened the TLS socket, preventing VM live migration.
Comment: What is the problem you are having?
Comment: systemd ist starting libvirtd before the pacemaker wants to start it.
Comment: In general when using Pacemaker you *disable* affected local system service management from running services or otherwise interferring with Pacemaker operations. In this case, systemd must start only corosync and pacemaker, and then Pacemaker must start libvirt and its friends. Pacemaker has all options to serialize service startup cluster-wide.
Answer: There still is some locking issue during live-migration that might be a bug in libvirtd, but I think I got the solution:
Parts of this solution are found in https://bugzilla.redhat.com/show_bug.cgi?id=1750340.
The first thing is not to use systemd's "socket activation" for libvirtd.
It's not enough to disable all the socket units (libvirtd.socket, libvirtd-ro.socket, libvirtd-admin.socket, libvirtd-tcp.socket, libvirtd-tls.socket), but you'll have to mask them.
Then libvirtd does not open the TLS socket, even if listen_tls=1 is set.
To activate that you must (in SLES 15 SP2) edit /etc/sysconfig/libvirtd to activate LIBVIRTD_ARGS="--listen".
At the same time you must deactivate LIBVIRTD_ARGS="--timeout 120" to prevent automatic termination of libvirtd.
Finally you'll have to start (once being configured) and stop virtlockd and libvirtd at the right point in time.
I am using a multipath SAN device to host my VM images, while I use a clustered RAID1 (/dev/md10) to hold the locks.
OCFS2 is being used as filesystem on top of both.
Clustered-MD and OCFS2 both need the DLM.
Cluster-wide resources use clones to distribute them.
I run three test VMs once libvirt and the image path /cfs/VMI is ready.
I won't explain the steps to configure using lockd with indirect locking here, just as I won't explain how to set up a clustered MD RAID or an OCFS2 filesystem.
Here is the three-node cluster configuration in crm syntax (the fencing resource being omitted):
node 1: node1 \
    attributes standby=off
node 2: node2 \
    attributes standby=off
node 3: node3 \
    attributes standby=off
primitive prm_CFS_VMI Filesystem \
    params device="/dev/disk/by-id/dm-name-VMI-PM" directory="/cfs/VMI" fstype=ocfs2 options="acl,user_xattr" \
    op start timeout=90 interval=0 \
    op stop timeout=90 interval=0 \
    op monitor interval=120 timeout=90
primitive prm_DLM ocf:pacemaker:controld \
    op start timeout=90 interval=0 \
    op stop timeout=120 interval=0 \
    op monitor interval=60 timeout=60
primitive prm_libvirtd systemd:libvirtd.service \
    op start timeout=100 interval=0 \
    op stop timeout=100 interval=0 \
    op monitor interval=60 timeout=100
primitive prm_lockspace_ocfs2 Filesystem \
    params device="/dev/md10" directory="/var/lib/libvirt/lockd" fstype=ocfs2 options="acl,user_xattr" \
    op start timeout=90 interval=0 \
    op stop timeout=90 interval=0 \
    op monitor interval=120 timeout=90
primitive prm_lockspace_raid_md10 Raid1 \
    params raidconf="/etc/mdadm/mdadm.conf" raiddev="/dev/md10" force_clones=true \
    op start timeout=90s interval=0 \
    op stop timeout=90s interval=0 \
    op monitor interval=300 timeout=90s \
    op_params OCF_CHECK_LEVEL=10
primitive prm_virtlockd systemd:virtlockd \
    op start timeout=100 interval=0 \
    op stop timeout=100 interval=0 \
    op monitor interval=60 timeout=100
primitive prm_xen_test-jeos1 VirtualDomain \
    params param config="/etc/libvirt/libxl/test-jeos1.xml" hypervisor="xen:///system" remoteuri="xen+tls://%n.domain.org" \
    op start timeout=120 interval=0 \
    op stop timeout=180 interval=0 \
    op monitor interval=600 timeout=90 \
    op migrate_to timeout=300 interval=0 \
    op migrate_from timeout=300 interval=0 \
    meta allow-migrate=true resource-stickiness=1000
primitive prm_xen_test-jeos2 VirtualDomain \
    params param config="/etc/libvirt/libxl/test-jeos2.xml" hypervisor="xen:///system" remoteuri="xen+tls://%n.domain.org" \
    op start timeout=120 interval=0 \
    op stop timeout=180 interval=0 \
    op monitor interval=600 timeout=90 \
    op migrate_to timeout=300 interval=0 \
    op migrate_from timeout=300 interval=0 \
    meta allow-migrate=true resource-stickiness=1000
primitive prm_xen_test-jeos3 VirtualDomain \
    params param config="/etc/libvirt/libxl/test-jeos3.xml" hypervisor="xen:///system" remoteuri="xen+tls://%n.domain.org" \
    op start timeout=120 interval=0 \
    op stop timeout=180 interval=0 \
    op monitor interval=600 timeout=90 \
    op migrate_to timeout=300 interval=0 \
    op migrate_from timeout=300 interval=0 \
    meta allow-migrate=true resource-stickiness=1000
clone cln_CFS_VMI prm_CFS_VMI \
    meta interleave=true
clone cln_DLM prm_DLM \
    meta interleave=true
clone cln_libvirtd prm_libvirtd \
    meta interleave=true
clone cln_lockspace_ocfs2 prm_lockspace_ocfs2 \
    meta interleave=true
clone cln_lockspace_raid_md10 prm_lockspace_raid_md10 \
    meta interleave=true
clone cln_virtlockd prm_virtlockd \
    meta interleave=true
colocation col_CFS_VMI__DLM inf: cln_CFS_VMI cln_DLM
colocation col_clustered-MD__DLM inf: cln_lockspace_raid_md10 cln_DLM
colocation col_libvirtd__cln_virtlockd inf: cln_libvirtd cln_virtlockd
colocation col_libvirtd__virtlockd inf: cln_libvirtd cln_virtlockd
colocation col_lockspace_ocfs2__DLM inf: cln_lockspace_ocfs2 cln_DLM
colocation col_lockspace_ocfs2__raid_md10 inf: cln_lockspace_ocfs2 cln_lockspace_raid_md10
colocation col_test-jeos1__CFS_VMI inf: prm_xen_test-jeos1 cln_CFS_VMI
colocation col_test-jeos2__CFS_VMI inf: prm_xen_test-jeos2 cln_CFS_VMI
colocation col_test-jeos3__CFS_VMI inf: prm_xen_test-jeos3 cln_CFS_VMI
colocation col_virtlockd__lockspace_fs inf: cln_virtlockd cln_lockspace_ocfs2
colocation col_vm__libvirtd inf: ( prm_xen_test-jeos1 prm_xen_test-jeos2 prm_xen_test-jeos3 ) cln_libvirtd
order ord_CFS_VMI_xen_test-jeos1 Mandatory: cln_CFS_VMI prm_xen_test-jeos1
order ord_CFS_VMI_xen_test-jeos2 Mandatory: cln_CFS_VMI prm_xen_test-jeos2
order ord_CFS_VMI_xen_test-jeos3 Mandatory: cln_CFS_VMI prm_xen_test-jeos3
order ord_DLM__CFS_VMI Mandatory: cln_DLM cln_CFS_VMI
order ord_DLM__clustered-MD Mandatory: cln_DLM cln_lockspace_raid_md10
order ord_DLM__lockspace_ocfs2 Mandatory: cln_DLM cln_lockspace_ocfs2
order ord_libvirtd__vm Mandatory: cln_libvirtd ( prm_xen_test-jeos1 prm_xen_test-jeos2 prm_xen_test-jeos3  )
order ord_lockspace_fs__virtlockd Mandatory: cln_lockspace_ocfs2 cln_virtlockd
order ord_raid_md10__lockspace_ocfs2 Mandatory: cln_lockspace_raid_md10 cln_lockspace_ocfs2
order ord_virtlockd__libvirtd Mandatory: cln_virtlockd cln_libvirtd

So the essential ordering is:
order ord_lockspace_fs__virtlockd Mandatory: cln_lockspace_ocfs2 cln_virtlockd
order ord_virtlockd__libvirtd Mandatory: cln_virtlockd cln_libvirtd
order ord_libvirtd__vm Mandatory: cln_libvirtd ( prm_xen_test-jeos1 prm_xen_test-jeos2 prm_xen_test-jeos3 )
order ord_CFS_VMI_xen_test-jeos1 Mandatory: cln_CFS_VMI prm_xen_test-jeos1
order ord_CFS_VMI_xen_test-jeos2 Mandatory: cln_CFS_VMI prm_xen_test-jeos2
order ord_CFS_VMI_xen_test-jeos3 Mandatory: cln_CFS_VMI prm_xen_test-jeos3

The issue remaining is that libvird claims the VM is not locked at the original node during live-migration shortly before migration succeeds.
Answer: Windl,
In order to eliminate the gap between virtualization and HA product documents, I set up a highly available virtualization environment, the detailed steps are as below,
SLE HA hardware environment details:

Cluster node size
DELL Precision Tower 5810

Shared Disk
Iscsi (50G)

SLE HA version
SLE15 HA SP2

# of the cluster nodes
2

SBD partition
Iscsi (50MB)

Filesystem partition
Iscsi (20GB)

VM image partition
Iscsi (30GB)

Installation and setup process:
1. Attach iscsi disk to two cluster node, divide the iscsi disk into 3 partitions (e.g. 50MB for sbd, 20GB for ocfs2, the remain for VM image).
    Add network bridge br0 on each cluster node (will be used when install/run virtual machine).
    Set up password-free ssh login for the root user between cluster nodes.
2. Install HA and virtualization related packages on each cluster node.
    # zypper in -t pattern ha_sles
    # zypper in -t pattern kvm_server kvm_tools
3. Setup HA cluster and add SBD device.
    refer to HA guide at http://docserv.suse.de/documents/en-us/sle-ha/15-SP2/single-html/SLE-HA-guide/#book-sleha-guide
4. Setup DLM and OCFS2 resources in crm.
    e.g.
    primitive dlm ocf:pacemaker:controld \
    op monitor interval=60 timeout=60
    primitive ocfs2-2 Filesystem \
    params device="/dev/disk/by-id/scsi-149455400000000004100c3befec3dc9a81f9ce28f7a8b8de-part1" directory="/mnt/shared" fstype=ocfs2 \
    op monitor interval=20 timeout=40
    group base-group dlm ocfs2-2
    clone base-clone base-group \
    meta interleave=true

5. Setup virtlockd and libvirtd service on each cluster node.
    edit /etc/libvirt/qemu.conf, set lock_manager = "lockd"
    edit /etc/libvirt/qemu-lockd.conf, set file_lockspace_dir = "/mnt/shared/lockd"  (note: /mnt/shared is ocfs2 file system mount point)
    restart/enable libvirtd service (note: virtlockd service will be started by libvirtd service according to the configuration)
6. Install a virtual machine (e.g. sle15-nd) on the shared partition from one cluster node, dump the domain configuration to a XML file.
    Move the virtual machine configuration file to the ocfs2 file system (e.g. /mnt/shared).
    note: please make sure the XML configuration file does not include any references to unshared local paths.
7. Setup VirtualDomain resource and order in crm.
    e.g.
    primitive vm_nd1 VirtualDomain \
    params config="/mnt/shared/sle15-nd.xml" remoteuri="qemu+ssh://%n/system" \
    meta allow-migrate=true \
    op monitor timeout=30s interval=10s \
    utilization cpu=2 hv_memory=1024
    order ord_fs_virt Mandatory: base-clone vm_nd1
8. Check all your changes with the show command in crm, then commit:
    e.g.
    crm(live/sle15sp2-test1)configure# show
    node 172167755: sle15sp2-test2
    node 172168091: sle15sp2-test1
    primitive dlm ocf:pacemaker:controld \
    op monitor interval=60 timeout=60
    primitive ocfs2-2 Filesystem \
    params device="/dev/disk/by-id/scsi-149455400000000004100c3befec3dc9a81f9ce28f7a8b8de-part1" directory="/mnt/shared" fstype=ocfs2 \
    op monitor interval=20 timeout=40
    primitive stonith-sbd stonith:external/sbd \
    params pcmk_delay_max=30s
    primitive vm_nd1 VirtualDomain \
    params config="/mnt/shared/sle15-nd.xml" remoteuri="qemu+ssh://%n/system" \
    meta allow-migrate=true \
    op monitor timeout=30s interval=10s \
    utilization cpu=2 hv_memory=1024
    group base-group dlm ocfs2-2
    clone base-clone base-group \
    meta interleave=true
    order ord_fs_virt Mandatory: base-clone vm_nd1
    property cib-bootstrap-options: \
    have-watchdog=true \
    dc-version="2.0.3+20200511.2b248d828-1.10-2.0.3+20200511.2b248d828" \
    cluster-infrastructure=corosync \
    cluster-name=hacluster \
    stonith-enabled=true
    rsc_defaults rsc-options: \
    resource-stickiness=1 \
    migration-threshold=3
    op_defaults op-options: \
    timeout=600 \
    record-pending=true
Verify if VM resource can work on HA cluster:
1. Verify VM resource is protected across cluster nodes.
    Test result: cannot start the VM manually via virsh command when this VM is running on another cluster node.
2. Verify VM resource can be taken by another cluster node when the current cluster node crashes
    Test result: after a few seconds (cluster fence time), the VM is started on another cluster node.
3. Verify VM resource can be taken by another cluster node when the current cluster node reboots
    Test result: the VM is migrated to another cluster node.
4. Check if we can migrate VM resource between cluster nodes
   Test result: Yes, the remote SSH connection to the VM is not broken during the whole migration.
Remarks:
1. In the actual production environment, cluster communication/management should use a separate network.
2. In the actual production environment, cluster sbd device should use a separate shared disk to avoid IO starvation.
3. Do not start VM instance manually until ocfs2 file system is mounted, since the file lockspace directory is under ocfs2 file system. In other words, you should let cluster(pacemaker) manage the start and stop of all virtual machines.
Comment: Suggestions for improvement: In installation between step 1 and step 4: If you'd explain the meaning of the partitions (maybe `fdisk -l ...`) from step 1, step 4 would be a bit easier to understand. Step 5: `/mnt/shared` most likely is a bad choice for a permanent mount.
Comment: I wonder what happens during boot: `libvirtd` will start before the cluster, so also before OCFS2 is mounted. Probably "probes" for the VMs will be started also before virtlockd will have a shared filesystem. Will virtlockd handle the situation correctly when its lock filesystem is mounted after start? (If it does a chdir into it, it probably won't work). Also I think as a proof of concept you should define at least two VMs so that each node can run one.
Comment: virlockd will access the lock file when virsh starts VM image, that means we need to make sure all VirtualDomain  resources startup after ocfs2 share file system.


rails best practices where to place unobtrusive javascript

Question: my rails applications (all 2.3.5) use a total mix of inline javascript, rjs, prototype and jquery. Let's call it learning or growing pains. Lately i have been more and more infatuated with unobtrusive javascript. It makes your html clean, in the same way css cleaned it up.
But most examples i have seen are small examples, and they put all javascript(jquery) inside application.js
Now i have a pretty big application, and i am thinking up ways to structure my js. I like somehow that my script is still close to the view, so i am thinking something like
orders.html.erb
orders.js

where orders.js contains the unobtrusive javascript specific to that view. But maybe that's just me being too conservative :)
I have read some posts by Yehuda Katz about this very problem here and here, where he tackles this problem. It will go through your js-files and only load those relevant to your view. But alas i can't find a current implementation.
So my questions:

how do you best structure your unobtrusive javascript; manage your code, how do you make sure that it is obvious from the html what something is supposed to do. I guess good class names go a long way :)
how do you arrange your files, load them all in? just a few? do you use content_for :script or javascript_include_tag in your view to load the relevant scripts. Or ... ?
do you write very generic functions (like a delete), with parameters (add extra attributes?), or do you write very specific functions (DRY?). I know in Rails 3 there is a standard set, and everything is unobtrusive there. But how to start in Rails 2.3.5?

In short: what are the best practices for doing unobtrusive javascript in rails? :)
Answer: I do not think there is one best practice, but I'll let you know what I do.

I have a series of js files each for with their own purpose in the public/javascripts/ directory. Some examples could be utility.js chat.js shopping_basket.js and so on.
I use asset packager and define one big fat collection for all my general use functionality and another for admin only functionality. Round trips to the server cost way too much. I basically include all the js in on first page load minified into one blob (in general)
I allow basic $(document).ready hooks inline in the pages, and keep them really short.
Data that my js files needs to access is rendered inline with the page. (Usually in the DOM, sometimes as vars - Eg. var xyz = 100)
I will usually develop my controllers with javascript off (and make sure it all works), then I turn it on and sprinkle a few if request.xhr? where needed.

Keep in mind, Rail 3.1 introduces a built-in best practice, see: http://guides.rubyonrails.org/asset_pipeline.html - on a personal note I have had performance and configuration issues with the new pipeline, however many others have had great success with it.
Comment: This is very interesting.
Complete. I am still interested what others have to say.
Answer: I recently documented how I have been managing javascript in Ruby on Rails. I basically break things down into many small, granular files, each with an appropriate namespace and then merge them all into a single file for production using asset_packager.
Comment: I like how you can automatically load a .js file with the same name as your controller for your views. That seems a good start at least :)
Answer: I found this post while trying to solve the same problem, but none of the existing solutions struck me as the right one. I wrote up my approach here. I love Rails' convention over configuration, so I wanted the same approach to including Javascripts that are applicable only to a particular action page. If nothing else, it's at least another approach to add to your options.
Comment: I really like your suggestion, and it is very close to what i would really like. What i now do is seperate the js in files per controller anyway, but then chuck in one big combined js because that loads quicker (1 big js instead of ton of seperate files).


How to replicate this P-value given $r$ and $n$?

Question: I am using http://www.socscistatistics.com/pvalues/pearsondistribution.aspx as my reference here.
$r = 0.0789$
$n = 15$
The $P$-value is $0.779858$. I have tried to replicate it without success. Is this something where I need $t = r\frac{\sqrt{n-2}}{\sqrt{1-r^2}} = 0.285367618996$ somehow? How do I compute $P$?
Answer: From the formula you provided, we know that
$$
r\frac{\sqrt{n-2}}{\sqrt{1-r^2}}
$$
is T distributed with $n-2$ degrees of freedom. So then if we use R we have:
> pt(0.285367618996, 13, lower.tail=F) # one tailed
[1] 0.3899292
> 2*pt(0.285367618996, 13, lower.tail=F) # two tailed
[1] 0.7798585

which is the answer provided on the website.
Comment: Is there a way to compute the value without R?
Comment: You can use the CDF that is described on [wikipedia for the t-distribution](http://en.wikipedia.org/wiki/Student%27s_t-distribution) to calculate the appropriate p-values. Though I would highly recommend using a programming language or a table.
Comment: I am very comfortable with programming but don't know what to analyze. You're saying I need to use http://en.wikipedia.org/wiki/Student%27s_t-distribution#Cumulative_distribution_function somehow?
Comment: There isn't a closed form for the solution of a t-distribution, so there isn't really an easy formula which you can just program away, so I would recommend you use something that is already written and tested or use a table of values. Otherwise implementing this programmatically without libraries is beyond my knowledge and expertise.
Comment: [Simpson's Rule](http://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson.27s_rule) is a quick-and-dirty numerical integration method that is dead easy to implement (it might still be taught in elementary Calculus courses) and will produce reasonable values of the cumulative Student t distribution.  In this example it could even be even done with pencil and paper to an accuracy of better than one part per million using only *two* evaluations of the integrand (at $0.2853676$ and  $0.2853676/2$).


Getting "Cannot ioctl TUNSETIFF tun: Operation not permitted" when trying to connect to OpenVPN

Question: I'm trying to setup an OpenVPN Access Server in AWS using the market place AMI, but I;m struggling to connect to it.
The access server is up and running. I've also added a user with Auto-Login and generated the relevant client config and certificates.
I then copied said files down to my machine and tried to connect using openvpn client.ovpn but got the following output and error,
Wed Nov 26 12:41:10 2014 OpenVPN 2.3.2 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Feb  4 2014
Wed Nov 26 12:41:10 2014 Control Channel Authentication: using 'ta.key' as a OpenVPN static key file
Wed Nov 26 12:41:10 2014 Outgoing Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
Wed Nov 26 12:41:10 2014 Incoming Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
Wed Nov 26 12:41:10 2014 Socket Buffers: R=[212992->200000] S=[212992->200000]
Wed Nov 26 12:41:10 2014 UDPv4 link local: [undef]
Wed Nov 26 12:41:10 2014 UDPv4 link remote: [AF_INET]<REMOVED_IP>:1194
Wed Nov 26 12:41:10 2014 TLS: Initial packet from [AF_INET]<REMOVED_IP>:1194, sid=2a06a918 c4ecc6df
Wed Nov 26 12:41:11 2014 VERIFY OK: depth=1, CN=OpenVPN CA
Wed Nov 26 12:41:11 2014 VERIFY OK: nsCertType=SERVER
Wed Nov 26 12:41:11 2014 VERIFY OK: depth=0, CN=OpenVPN Server
Wed Nov 26 12:41:11 2014 Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key
Wed Nov 26 12:41:11 2014 Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Wed Nov 26 12:41:11 2014 Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key
Wed Nov 26 12:41:11 2014 Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Wed Nov 26 12:41:11 2014 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 2048 bit RSA
Wed Nov 26 12:41:11 2014 [OpenVPN Server] Peer Connection Initiated with [AF_INET]126.96.36.199:1194
Wed Nov 26 12:41:14 2014 SENT CONTROL [OpenVPN Server]: 'PUSH_REQUEST' (status=1)
Wed Nov 26 12:41:14 2014 PUSH: Received control message: 'PUSH_REPLY,explicit-exit-notify,topology subnet,route-delay 5 30,dhcp-pre-release,dhcp-renew,dhcp-release,route-metric 101,ping 12,ping-restart 50,comp-lzo yes,redirect-private def1,redirect-private bypass-dhcp,redirect-private autolocal,redirect-private bypass-dns,route-gateway 172.16.224.129,route 172.16.1.0 255.255.255.0,route 172.16.224.0 255.255.255.0,block-ipv6,ifconfig 172.16.224.131 255.255.255.128'
Wed Nov 26 12:41:14 2014 Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]:4: dhcp-pre-release (2.3.2)
Wed Nov 26 12:41:14 2014 Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]:5: dhcp-renew (2.3.2)
Wed Nov 26 12:41:14 2014 Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]:6: dhcp-release (2.3.2)
Wed Nov 26 12:41:14 2014 Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]:18: block-ipv6 (2.3.2)
Wed Nov 26 12:41:14 2014 OPTIONS IMPORT: timers and/or timeouts modified
Wed Nov 26 12:41:14 2014 OPTIONS IMPORT: explicit notify parm(s) modified
Wed Nov 26 12:41:14 2014 OPTIONS IMPORT: LZO parms modified
Wed Nov 26 12:41:14 2014 OPTIONS IMPORT: --ifconfig/up options modified
Wed Nov 26 12:41:14 2014 OPTIONS IMPORT: route options modified
Wed Nov 26 12:41:14 2014 OPTIONS IMPORT: route-related options modified
Wed Nov 26 12:41:14 2014 ROUTE_GATEWAY 192.168.0.1/255.255.255.0 IFACE=wlan0 HWADDR=c4:85:08:c9:14:f4
Wed Nov 26 12:41:14 2014 ERROR: Cannot ioctl TUNSETIFF tun: Operation not permitted (errno=1)
Wed Nov 26 12:41:14 2014 Exiting due to fatal error

Any idea what the problem is? I assume it's failing to create the tunnel due to the ERROR line?
I'm running server version 2.0.10 and client version,
OpenVPN 2.3.2 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Feb  4 2014
Originally developed by James Yonan
Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <firstname.lastname@example.com>
Compile time defines: enable_crypto=yes enable_debug=yes enable_def_auth=yes enable_dependency_tracking=no enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown enable_eurephia=yes enable_fast_install=yes enable_fragment=yes enable_http_proxy=yes enable_iproute2=yes enable_libtool_lock=yes enable_lzo=yes enable_lzo_stub=no enable_maintainer_mode=no enable_management=yes enable_multi=yes enable_multihome=yes enable_pam_dlopen=no enable_password_save=yes enable_pedantic=no enable_pf=yes enable_pkcs11=yes enable_plugin_auth_pam=yes enable_plugin_down_root=yes enable_plugins=yes enable_port_share=yes enable_selinux=no enable_server=yes enable_shared=yes enable_shared_with_static_runtimes=no enable_small=no enable_socks=yes enable_ssl=yes enable_static=yes enable_strict=no enable_strict_options=no enable_systemd=no enable_win32_dll=yes enable_x509_alt_username=yes with_crypto_library=openssl with_gnu_ld=yes with_ifconfig_path=/sbin/ifconfig with_iproute_path=/sbin/ip with_mem_check=no with_plugindir='${prefix}/lib/openvpn' with_route_path=/sbin/route with_sysroot=no

Comment: // , Why these errors? This seems like a pretty stupid way to detect that you don't have `sudo` privileges.
Answer: Looks like this is a simple matter of sudo.
sudo openvpn client.ovpn worked a treat.
Comment: ** insert hair pulling comment here ** wow this took me a while. Thanks for the reminder. Might also need the --config option depending on the distro.
Comment: // , Can you say anything about why this is the case?
Comment: But how to run connection from 'Network connection manager' which has no `sudo` option
Comment: `sudo` put me on the right track, but on my ubuntu 22.04 setup i also needed to `mv config.ovpn /etc/openvpn/client/`, otherwise i got `Options error: In [CMD-LINE]:1: Error opening configuration file: config.ovpn`, maybe helps someone..
Comment: Ok so this is weird because I have a setuid script owned by user root, group root, that fails with the above error - but if I use `sudo` *while the script is already running as root* it works!
Answer: Creating the TUN or TAP adaptor requires privileges that you possibly don't have - hence the command works with sudo, but not without.
On my system, if the openvpn command is run like this;
sudo openvpn --config file.ovpn
then a device tun0 is created.
Almost always, creating devices requires privileges.
Answer: Using Linux Mint, and connecting via the Network Manager UI (which does not prompt for a sudo pwd) -- I assumed it wasn't necessary. Turns out, this was the problem for me! Connecting via sudo from a terminal worked perfectly.
Answer: You could always run chmod u+s on the openvpn binary as root (setting uid 0).
sudo chmod u+s $(which openvpn)
This will allow a local user to execute the process as the root user. At this point your network manager/nm-applet stuff will also allow connection establishment.
Comment: This is Server Fault, for Professional System Administrators in a business environment. What you are suggesting is bad business and security practice. In a business environment you never assume that any particular system is `safe` because it can be used as a vector to attack the rest of your network.  If you want to do this in a home user situation, then you need to go back over to the Super User stack https://superuser.com/
Comment: Do you think it depends on circumstances or not? Do you think that some guys desktop require the same level of protection as a public service? Or do you think that a box that does not see exposure can be assumed to be pretty damn safe even if a program has suid 0? Many programs require this and comes with systems by default as suid 0 you know. It all depends on the use of the system, same with sudo, even though i rate sudo more critical as scripts can absuse it.
Comment: Adding the SUID bit to an application can be a major security violation.
Comment: I don't fully disagree with you, yet having sudo without password protection is better? , yes one can tweak sudoers to only allow for password less use of a spesific program e.t.c However.. It all depends on the type of exposure the machine is facing right?

Normally some applications need the SUID bit set to achieve a good experience, this is why i suggest it under this circumstance. This will also enable the use of NetworkManager e.t.c.
Comment: sudo should always have password protection and it can be limited in the sudoers file to be a particular application per user.


Run code only once in entire Windows Forms Application Lifetime

Question: I am working on a Windows Forms Application using Visual Studio 2010 IDE. My need is that I have certain block of code that needs to be run only once, at the starting of the application and never again for the entire lifetime(by lifetime I mean never again on the same system,unless the system is reconfigured). I have placed that code in a separate .cs file and for now, I run it's assembly(.exe) manually for testing purposes. But for deployment purposes, how do I go about it? It contains code for creating scheduled tasks using the schtasks command through command prompt. I know there are workarounds for the same, but I need to stick to the schtasks approach. I know there is something like Setup Projects that help us configure all the files that are required for the installation of our project and also create an installation file in the end, but can I write some code in it to ensure that it runs once, during installation, before my application is executed?
Comment: A Singleton Pattern , creates only one instance throught the application ,also its thread safe. Try implementing that pattern. This is an Idea not a solution. If u can paste the code, we would come up with some idea!
Comment: @madhairsilence: Singleton Pattern is useless here. The OP doesn't want to create a single instance. The OP wan't to execute some routine once on a system and then never again (unless the system is reconfigured).
Comment: What does creating an instance mean. calling a constructor. Cant he place a code in the constructor, make it private, instantiate the static variable inline??
Answer: Yes you can have a Setup and Deployment package run an exe during installation. You will have to create a Custom Action in the setup to do that.
Comment: [link](http://msdn.microsoft.com/en-us/library/d9k65z2d(v=vs.80).aspx) [link](http://www.codeproject.com/Articles/335516/Custom-Action-in-Visual-Studio-setup-projects) - just Google "visual studio setup and deployment custom action".
Comment: Could you elaborate on it a bit? Maybe a link? I think this is what I'm looking for.


Linux arp cache timeout values

Question: I'm trying to configure sane values for the Linux kernel arp cache timeout, but I can't find a detailed explanation as to how they work anywhere. Even the kernel.org documentation doesn't give a good explanation, I can only find recommended values to alleviate overflow.
Here is an example of the values I have:
net.ipv4.neigh.default.gc_thresh1 = 128
net.ipv4.neigh.default.gc_thresh2 = 512
net.ipv4.neigh.default.gc_thresh3 = 1024

Now, from what I've gathered so far:

gc_thresh1 is the number of arp entries allowed before the garbage collector starts removing any entries at all.
gc_thresh2 is the soft-limit, which is the number of entries allowed before the garbage collector actively removes arp entries.
gc_thresh3 is the hard limit, where entries above this number are aggressively removed.

Now, if I understand correctly, if the number of arp entries goes beyond gc_thresh1 but remains below gc_thresh2, the excess will be removed periodically with an interval set by gc_interval.
My question is, if the number of entries goes beyond gc_thresh2 but below gc_thresh3, or if the number goes beyond gc_thresh3, how are the entries removed?
In other words, what does "actively" and "aggressively" removed mean exactly? I assume it means they are removed more frequently than what is defined in gc_interval, but I can't find by how much.
Answer: Every time when there is a forced garbage collection of entries, last_flush field is updated in the neighbor table, neigh_table.
Forced garbage collection of entries happens if one of the following conditions are met:

Number of entries in the table is greater than gc_thresh3
Number of entries in the table is greater than gc_thresh2, and time since last_flush is greater than or equal to 5 HZ

When a forced garbage collection of entries is requested, entries that meet both the following criteria are discarded:

Nobody refers to the entry
Entry is not permanent

A periodic work, neigh_periodic_work tries to free unreferenced entries if the total number of entries is greater than gc_thresh1.
Source: Linux kernel source, neighbour.c
Comment: OK, I'm not a developer so let me try to see if I understand correctly.

Entries less than gc_thresh1 are left alone.

Entries above gc_thresh1, but below gc_thresh2 are periodically garbage collected with a frequency set by gc_interval.

Entries above gc_thresh2 but below gc_thresh3 are garbage collected every 5 seconds.

Entries above gc_thresh3 are garbage collected immediately, triggered by not by a periodical check, but by the event of adding a new entry.
Is that accurate?
Comment: That sounds correct from what I observed in the source code.

Linux arp cache timeout values


Migration tries to create existing entity

Question: I have a D8 migration where I pull remote resources and for each one I create new entity object, apply the resource onto the entity via custom methods on that entity and return the data for this resource as $entity->toArray(). This is how my iterator is getting build. So basically it is an array of entity definitions.
On the target entity I have a field called 'name' which is a unique fields so no two entities with the same 'name' can exist. In the migration I have this field as id key. But for some reason when I run the migration it tries to create a new entity and so the UniqueField constraint will prevent the entity to be saved(I am doing validation in entity's preSave() method) and my migration will fail.
And I cannot figure out why it won't match the existing entity if the 'name' field has a value(I have checked this on multiple places in the code).
The only thing I can come up with it so try to load an existing entity in the prepareRow() myself but that seems as very strange approach and I could basically just completely scratch the migration and write a simple batch.

This is my iterator:
  /**
   * {@inheritdoc}
   */
  protected function initializeIterator() {
    $items = $this->getResourceEntity()->getResourcePlugin()->loadAll();
    $storage = $this->entityManager->getStorage($this->getDerivativeId());

    $items = array_map(function($resource) use ($storage) {
      $entity = $storage->create();
      $entity->resourceMap($resource);
      return $entity->toArray();
    }, $items);

    return new \ArrayIterator($items);
  }

After debugging \Drupal\migrate\Plugin\migrate\id_map\Sql::sourceIdFields and \Drupal\migrate\Plugin\migrate\id_map\Sql::destinationIdFields it looks like it tries to map 'name' => 'id' fields for some reason instead of 'name' => 'name'.
I guess that is because the destination plugin(content entity) returns the entity id field which in this case is id in \Drupal\migrate\Plugin\migrate\destination\EntityContentBase::getIds.
I guess I am missing some crucial information here on how the migrations work.
So yeah, I had to use 'id' in getIds(), and in the iterator I had to try to figure out entity id of an existing entity.
Answer: It's rather premature to create an entity at the source plugin, when the destination plugin will create the entity for you... It's much simpler for the iterator to simply produce an array of fields representing the raw data, have the process pipeline map those source fields to the Drupal destination entity's field names, and have the destination plugin 'entity:my_entity' create and save the entity to Drupal.
Comment: That's what I'm doing. I am only creating stubs, I'm not saving them.
Comment: But why are you creating entities in the source plugin? Normally your source plugin would simply create an array of the source data to iterate over.


Why is the $x$ axis for a histogram labeled "bin"?

Question: When talking about histograms, why do we refer to the x-axis as "bin"?
Comment: In vernacular English, a "bin" is a container for holding things.  On the horizontal axis, we have a number bins, each of which holds data points that are sufficiently similar.  We are essentially sorting the data into box.
Comment: https://www.google.com/search?q=bin+statistics+histogram&oq=bin+statistics+histogram
Answer: When wanting to create a histogram of a continuous variable, you first need to split those into bins (sometimes referred to as buckets). Subsequently, this procedure is called binning or bucketing.
So the x-axis of a histogram represents the bins of the continuous variable.
Comment: You could also bin discrete/count data, in whole or in part. For example, number of sexual partners often has a long right tail that researchers top code at X+.  Histogram construction is largely a tradeoff
between detail and generalization (or variance and bias), and this tradeoff does not depend on the type of data.
Comment: Yes you are correct, binning works on discrete data as well, however I wanted to point out that you can't have a histogram from a continuous variable without binning it first.