Conditioning pandas Dataframe on an Array

Question: I'm trying to figure out how to condition on an array I've created.
first6 = df["Tbl_Name_Dur"].unique()[0:6]
for element in first6:
    print(element)

df_test = df[df['Tbl_Name_Dur'] for element in first6]

I've printed the elements and that works. How do I condition on selecting my dataframe based on first6. I've tried the following:
df_test = df[df['Tbl_Name_Dur'] in first6]
df_test = df[df['Tbl_Name_Dur'] == first6]

Any help would be much appreciated!
Answer: You can use the isin method. Here is an example:
import pandas as pd

data_dict = {'col': pd.Series([1, 2, 3, 4, 4, 5, 6, 7, 8 ,8 ])}
df = pd.DataFrame(data_dict)
first6 = df.col.unique()[0:6]

df = df[df.isin(first6)]
df.dropna(inplace=True)
print(df)

Alternatively, you can use a lambda function together with map:
import pandas as pd

data_dict = {'col': pd.Series([1, 2, 3, 4, 4, 5, 6, 7, 8, 8 ])}
df = pd.DataFrame(data_dict)
first6 = df.col.unique()[0:6]
df = df[df.col.map(lambda x : x in first6)]
print(df)

Output:
   col
0  1
1  2
2  3
3  4
4  4
5  5
6  6


applications of topology or abstract algebra to astronomy

Question: That is my question, there are applications of the branch of topology or abstract algebra to the astronomy? I know that there are to physics but to astronomy?
Comment: This might be better suited for http://physics.stackexchange.com/.
Comment: If there are applications of physics to astronomy, by transitivity...
Comment: Yes, there are - for example, see a similar question http://math.stackexchange.com/q/474884/
Answer: The whole area of qualitative dynamical systems, which contains plenty of topology, was inaugurated by Poincaré to answer questions in celestial mechanics. (I hope this counts as astronomy.)


Why for any doubly stochastic matrix, there exist a permutation $\pi$, such that $A_{[i,\pi(i)]}\ne 0$?

Question: Or put it simply, for any $n$-by-$n$ doubly stochastic matrix $A$, you can always find $n$ non-zero entries in $A$, none of them lies in the same row or column. Why is that?
Comment: I had an "answer" to this that some criticized; I'm going to remove it. Basically I did some gyrations on A to get it into the format with a 1 at upper left, such that the result is still doubly stochastic. But this has no bearing on the question, since there is no relation between the choices of nonzero entries of the original A and where nonzero entries might be in the "gyrated A".
Answer: According to the Birkhoff-von Neumann theorem the set of doubly stochastic $(n\times n)$ matrices is the convex hull of the set of $(n\times n)$ permutation matrices. For a simple proof see here (there are many proofs in the literature):
http://mingus.la.asu.edu/~hurlbert/papers/SPBVNT.pdf
Given that, for any doubly stochastic $(n\times n)$ matrix $D$ by Caratheodory's theorem there are $<n^2$ permutation matrices $P^{(\ell)}$ and numbers $\lambda_\ell>0$ summing to $1$ such that
$$D=\sum_\ell\lambda_\ell P^{(\ell)}\ .$$
It follows that $d_{ik}>0$ whenever $P_{ik}^{(1)}>0$, and the latter happens exactly once in each row and each column.
Comment: That link isnt working.


Console doesnt display histogram

Question: I ran the following code, but nothing came up on the console....
<code>#include <stdio.h>

#define MAXWORDLEN 10

int main(void)
{
  int c;
  int inspace = 0;
  long lengtharr[MAXWORDLEN + 1];
  int wordlen = 0;

  int firstletter = 1;
  long thisval = 0;
  long maxval = 0;
  int thisidx = 0;
  int done = 0;

  for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++)
  {
    lengtharr[thisidx] = 0;
  }

  while(done == 0)
  {
    c = getchar();

    if(c == ' ' || c == '\t' || c == '\n' || c == EOF)
    {
      if(inspace == 0)
      {
        firstletter = 0;
        inspace = 1;

        if(wordlen <= MAXWORDLEN)
        {
          if(wordlen > 0)
          {
            thisval = ++lengtharr[wordlen - 1];
            if(thisval > maxval)
            {
              maxval = thisval;
            }
          }
        }
        else
        {
          thisval = ++lengtharr[MAXWORDLEN];
          if(thisval > maxval)
          {
            maxval = thisval;
          }
        }
      }
      if(c == EOF)
      {
        done = 1;
      }
    }
    else
    {
      if(inspace == 1 || firstletter == 1)
      {
        wordlen = 0;
        firstletter = 0;
        inspace = 0;
      }
      ++wordlen;
    }
  }

  for(thisval = maxval; thisval > 0; thisval--)
  {
    printf("%4d  | ", thisval);
    for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++)
    {
      if(lengtharr[thisidx] >= thisval)
      {
        printf("*  ");
      }
      else
      {
        printf("   ");
      }
    }
    printf("\n");
  }
  printf("      +");
  for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++)
  {
    printf("---");
  }
  printf("\n       ");
  for(thisidx = 0; thisidx < MAXWORDLEN; thisidx++)
  {
    printf("%2d ", thisidx + 1);
  }
  printf(">%d\n", MAXWORDLEN);

  return 0;
}
</code>
Comment: which compiler are you using?  What error are you getting?
Comment: Where are you seeing that this is 'not allowed'? Which standard?
Comment: I'm marking this down due to this being a truly incoherent question. With some work, I think this could be a good question.
Comment: Follows on from http://stackoverflow.com/questions/1413644/frequency-histogram-in-c.
Answer: getchar is still an int by the POSIX and C standards.  Did you forget to include stdio.h or include something that redefines it?  This example works for me:
<code>#include <stdio.h>
int main()
{
  int c;
  c = getchar();
}
</code>
Answer: getchar() is a macro function. Maybe you're missing the right include file.
In a pinch,
<code>#ifndef getchar
#define getchar() getc(stdin)
#endif
</code>
Comment: @stragler, according to the K&R book, both exist.
Answer: http://codepad.org/Fp8kmzbv
It compiles and runs fine @codepad. What is your compiler, your compile options, and how are you running it?
And running it on my home machine:
<code>$ gcc-trunk --version
gcc-trunk (GCC) 4.5.0 20090907 (experimental)

$ gcc-trunk -Wall -ansi -Wall -W -pedantic tt.c
tt.c: In function 'main':
tt.c:73:5: warning: format '%4d' expects type 'int', but argument 2 has type 'long int'

$ ./a.out
This is a test of your histogram program.
   3  |          *
   2  |    *     *
   1  | *  *     *           *  *
      +---------------------------------
        1  2  3  4  5  6  7  8  9 10 >10
</code>
So it should still do what you want it to do, assuming you're running it correctly (as a console application within a console).
Answer: I am curious if you mean getch() as being a problem.
4 mths ago there was a discussion regarding getch() that may be of use:
getch is deprecated
In the second answer getchar() is suggested, so it shouldn't be returning an error, but that also depends on which compiler you are using.
Answer: maybe you have to call fflush(stdout) at the end of your program to flush console output.

Console doesnt display histogram


lilypond - hide tuplet numbers

Question: I am working on translating BWV 772 into a lilypond file. I want to make it match the manuscript as much as possible. In the first bar, Bach writes the 3s for the triplets in both voices and then you can see where the triplets are but the numbers are gone, which I think is kind of common, right?

In blue you can see the tuplet number, in the red squares (and in all the other triplets), the number is gone.
I have found that I can hide the brackets like this:
\override TupletBracket.bracket-visibility = ##f

But how can I hide the number of the tuplet? Didn't find anything straight-forward in TupletNumber: http://lilypond.org/doc/v2.23/Documentation/internals/tupletnumber
I am using lilypond 2.22.2.
Answer: If you want to get rid of anything in Lilypond, two commands can make themselves useful: \hide and \omit. Both of them get a parameter telling what should be got rid of — in this case, a TupletNumber. So you could use either \hide TupletNumber or \omit TupletNumber.
The difference between the two is easily seen from the names of the commands: \hide hides stuff, i. e. the hidden things still take up space but are invisible. On the other hand, \omit omits stuff, i. e. the omitted things are never put into the score in the first place and they don't take up any space. So \omit TupletNumber would be probably slightly more fitting.
(By the way, both of those commands can be done only \once. So \once\omit TupletNumber hides only the next TupletNumber encountered in the score. And they can be undone with \undo (e. g. \undo\omit TupletNumber), should you decide that you will need those numbers back later.)
Comment: This is a textbook great answer; one that doesn't just answer the question, but *teaches* the reader how to approach it both in this situation and in others. Bravo/a!

lilypond - hide tuplet numbers


flutter length of nullable TextEditingController

Question: I try to read a nullable TextEditingController
  final TextEditingController? nameController = TextEditingController();

     if(nameController != null) {
       if (nameController.text.isNotEmpty && nameController.text.length >= 3) {
         ...
       }
     }

But get the error:
The property 'text' can't be unconditionally accessed because the receiver can be 'null'. (Documentation)  Try making the access conditional (using '?.') or adding a null check to the target ('!')

Answer: To fix this error, you can use the ?. operator. Use to access text so that if nameController has a null value, text cannot be accessed using this operator.
final TextEditingController nameController = TextEditingController();

if (nameController?.text?.isNotEmpty == true && nameController!.text.length >= 3) {
  // ...
}

Comment: you already assign value to nameController so it will never null, better way is to remove ? from TextEditingController nameController = TextEditingController();


85% of the samples come from an unknown distribution, the rest come from the same distribution with a larger variance.How to recognize them?

Question: Assume I have a data, say columns are the samples, and rows are the features, the problem is that around 85% of the samples come from an unknown distribution but the rest come from the same type of distribution but with a larger variance. Is there any method that I could recognize which samples (or columns) comes from the distribution with larger variance? Thank you very much!
Comment: Could you clarify what "same distribution but with a larger variance" might mean specifically?  After all, if it has a larger variance, it is *a fortiori* a different distribution.  In what respects are the two distributions "the same"?
Comment: @whuber I mean the same type of distribution, it is just an assumption, I don't know if this assumption is correct, or I should say the rest come from another different unknown distribution? Thanks
Answer: I have no idea what features are in this context, but given $n$ sample values $x_1, x_2, \ldots, x_n$, each of which is either a realization of a random variable with density $f_0(x)$ (hypothesis $\mathsf H_0$) or a realization of a random variable with density $f_1(x)$ (hypothesis
$\mathsf H_1$), then the standard maximum likelihood decision rule $$\Lambda(x_i) = \frac{f_1(x_i)}{f_0(x_i)} ~ \begin{array}{c}\mathsf H_1\\\gtrless\\\mathsf H_0\end{array}~ 1$$ applied to each sample will classify the samples into those which are from distribution $f_0(x)$ and those which are from distribution $f_1(x)$. Unfortunately, this rule does not minimize the probability of mis-classification which I assume is one of the goals of the exercise. For the minimum probability of mis-classification, one must compare $\Lambda(x_i)$ to the threshold
$\displaystyle \frac{\pi_0}{\pi_1}$ where $\pi_0$ and $\pi_1$ are the
prior probabilities of the two hypotheses ($0.85$ and $0.15$ in this case), and decide in favor
of $\mathsf H_1$ or $\mathsf H_0$ according as $\Lambda(x(i))$ is larger than or smaller than the threshold $\displaystyle \frac{\pi_0}{\pi_1}$.
For the specific case when $f_0((x)$ and $f_1(x)$ are normal densities with common mean $\mu$ and standard deviations $\sigma_0 < \sigma_1$, the minimum probability of mis-classification rule works out to be what one would expect from common sense: samples that are greatly different from the mean are classified as having density $f_1$ while samples close to the mean are classified as having density $f_0$. The decision rule merely quantifies the exact location of the dividing line(s) between large deviations from the mean and small deviations from the mean. Note that with normal distributions,  the bulk of the probability mass lies in the vicinity of the mean, and consequently, the Type II error probability is quite large.
Comment: There are a lot of features, and I don't know what $f_0$ and $f_1$ are, they could be anything even without analytic form, how could I calculate them?(cuz the data had been mixed up). Is there any algorithm? Thanks


Problemas com SELECT option com PDO

Question: Amigos reeditei a conexão PDO abaixo:
<?php
$conn = new PDO( 'mysql:host=localhost;dbname=pbfjacar_site' , 'pbfjacar_murilo' , 'smc100164' );
$stmt = $conn-> prepare('SELECT font FROM fontes');
$stmt-> execute();
$result = $stmt-> fetchAll(PDO::FETCH_ASSOC);
?>

Para executar essa nova operação:
<select name="tipo_font_end">
<?php foreach( $result as $row ) ?>
<option value="<?php echo $row['font'];?>"><?php echo $row['font'];?></option>

</select>

Mas não estou obtendo o resultado esperado, pois ele agora puxa somente o ultimo "ID" de um total de 10 cadastros na tabela "fontes", conforme imagem abaixo:

Estou inserindo o endereço de acesso para teste abaixo, para poderem ver o que esta acontecendo!
http://www.pbfjacarepagua.com.br/teste/end.php
Se os amigos puderem me mostrar onde estou errando ou ate mesmo o que esta faltando, ficarei muito agradecido.
Abraços a todos.
Comment: Murilo, notei que você editou totalmente sua publicação, o que acabou descaracterizando uma dúvida que poderia ser útil para outros, pois agora quem entrar aqui vai ver coisas totalmente fora de contexto. Se alguma resposta resolveu o seu problema você pode marcar como resolvido (não precisa colocar RESOLVIDO no título) e acrescentar informações nos comentários. Se você mesmo tiver resolvido, crie sua própria resposta. Mas é bom sempre manter sua dúvida inicial.
Comment: Antes dessa linha `return $result;` coloque isso `var_dump($result);`, se possível edite sua resposta com o resultado, ok?
Comment: O seu `` não tem loop?
Comment: Amigo o que seria loop? Sou muito leigo em php.
Comment: Não funcionou!!! Entre no endereço (http://www.pbfjacarepagua.com.br/teste/end.php), e veja o resultado. O código ficou assim:
`prepare($count);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($result);
return $result;
foreach($result as $res)
?>`
Comment: Peço desculpas Paulo, não irá acontecer novamente.
Answer: $conn = new PDO( 'mysql:host=localhost;dbname=DATABASE' , 'USUARIO' , 'SENHA' );
$stmt = $conn-> prepare( 'SELECT * FROM fontes' );
$stmt-> execute();
$result = $stmt-> fetchAll( PDO::FETCH_ASSOC );

<select name="tipo_font_end">
    <?php foreach( $result as $row ) ?>
        <option value="<?php echo $row['font'];?>"><?php echo $row['font'];?></option>
    <?php } ?>
</select>

Você estava usando fetch, que é usado para retornar uma unica linha DOC

Obtém a próxima linha de um conjunto de resultados

O correto seria fetchAll para retornar um array de vários itens DOC

Retorna um array contendo todas as linhas do conjunto de resultados

OBS: Se você só vai fazer uso do nome da fonte, então troque SELECT * FROM fontes por SELECT font FROM fontes, e se pretende usar o nome da fonte e o ID então use SELECT id, font FROM fontes... Evite usar SELECT *
Comment: Papa irei editar a minha pergunta para vc. ver como ficou os códigos, e verificar se eu errei em algo, valeu?
E esta linha do SELECT '', esta causando o erro "Parse error: syntax error, unexpected '}' in /home/pbfjacar/public_html/teste/end.php on line 19".
Quando eu retiro-a ele me traz somente o ultimo item cadastrado.
Verifique no endereço de teste (http://www.pbfjacarepagua.com.br/teste/end.php)
Comment: Resolvido Papa, estávamos esquecendo de inserir uma chave na linha do "foreach", por isso estava dando o erro que mencionei no comentário anterior.
Bem resumindo, com a sua ajuda consegui puxar todos os itens da tabela fontes.
Muito obrigado pela sua ajuda, abraços.

Problemas com SELECT option com PDO


Diagonalizable vs full rank vs nonsingular (square matrix)

Question: There are many discussions of such type problems (comparison), for example:
Diagonalizable vs Normal
Today, I want to clearly understand the  topic.
Suppose the matrix $A\in \mathbb{R}^n$.

Since the multiplication of all eigenvalues is equal to the determinant of the matrix, $A$ full rank is equivalent to $A$ nonsingular.
The above also implies $A$ has linearly independent rows and columns.  So $A$ is invertible.
$A$ is diagonalizable iff $A$ has $n$ linearly independent eigenvectors. ($A$ is nondefective).
Note: $A$ is defective if geo. multiplicity $<$ alge. multiplicity.
A diagonalizable matrix does not imply full rank (or nonsingular).

My problem is

Does full rank matrix (nonsingular) imply it is diagonalizable?

Equivalently:

Does a matrix with all its columns or rows linear independently imply all its eigenvectors linear independently?
Answer: Full rank and diagonalizability are independent from one another.

A diagonalizable matrix with full rank:
$$
\begin{bmatrix}1 & 0 \\ 0 & 1\end{bmatrix}
$$
A non diagonalizable matrix with full rank:
$$
\begin{bmatrix}1 & 1 \\ 0 & 1\end{bmatrix}
$$
A diagonalizable matrix without full rank:
$$
\begin{bmatrix}1 & 0 \\ 0 & 0\end{bmatrix}
$$
A non diagonalizable matrix without full rank:
$$
\begin{bmatrix}0 & 1 \\ 0 & 0\end{bmatrix}
$$
Comment: how's the second matrix non-diagonalisable ?
Comment: @MahNeh A $2\times2$ matrix with coincident eigenvalues is diagonalizable if and only if it is diagonal. Anyway, the eigenspace relative to the unique eigenvalue $1$ has dimension $1$.
Answer: $1.$
No. A full rank matrix implies it's determinant is non-zero or the matrix is non-singular.
Speaking in terms of linear operator $T$ over a vector space $V$ is diagonalizable if and only if there exists an ordered basis consisting of eigenvectors of $T$, Furthermore if $T$ is diagonalizable and $\beta$ is an ordered basis of $T$ consisting eigen vectors of $T$, then $M=[T]_\beta$, the matrix representation of $T$, is a diagonal matrix.
One can check if a given matrix $M_{n\times n}$ is diagonalizable or not by-

Characteristic polynomial splits or not,
$n-rank(M-\lambda_iI)=$multiplicity of $\lambda_i$.

If this two criteria fulfills then a matrix is diagonalizable.
Counterexample: $\begin{bmatrix}3 & 1 &0 \\ 0&3&0\\ 0&0&4\end{bmatrix}$
$2$. Consider the identity matrix $I$, all it's rows and columns are linearly independent. What can you say about the eigenvectors?
Comment: $\begin{bmatrix} 1& 1 \\ 0& 1 \end{bmatrix}$ is Full rank, but not diagonalizable.
Comment: A polynomial splits if it can be written as a product of linear polynomials. This depends on the field you're working in, e.g. $X^2 - 2$ splits in $\mathbb{R}$, but not in $\mathbb{Q}$.
Comment: What do you mean 'splits'?  And in your answer, how do you link between diagonalizable and nonsingular(full rank) after you say no? Or simply speaking, is there any example to say $A$ is full rank but not diagonalizable?
Comment: If $A$ is full rank, then there is no eigenvalues $=0$. Therefore, we have only to consider $U$ if $A = U^{-1}\Lambda U$ Then can we say $U$ is full rank by knowing that $A$ is full rank?


Nodejs MySQL multiple query in a loop

Question: i'm actually having a problem by doing alot of query in a loop
It's seem to not work aswell, 100% of time is only query the latest data in the array.
CurrentSocket.biznessStatus.ListOfItemsToAdd = ["1", "4"];
if(Object.keys(CurrentSocket.biznessStatus.ListOfItemsToAdd).length >= 1){
        for(var id in CurrentSocket.biznessStatus.ListOfItemsToAdd){
            var readedIt = CurrentSocket.biznessStatus.ListOfItemsToAdd[id];

            pool.getConnection(function(id, err, connection){
                if(err) throw err;

                console.log("doAction of ListOfItemsToAdd for itemID -> "+readedIt);

                connection.query("SELECT COUNT(*) AS it FROM users_biznesspanel WHERE user_id = ? AND ui_id = ?", [CurrentSocket.user_id, readedIt], function(err, result){
                    if(err) console.log(err);
                    if(result[0]["it"] != 0){
                        connection.query("UPDATE users_biznesspanel SET nb = nb + 1 WHERE user_id = ? AND ui_id = ?", [CurrentSocket.user_id, readedIt], function(err, result){
                            connection.release();
                            if(err) console.log(err);
                            console.log("Added item: "+readedIt);
                        });
                    }
                    else{
                        connection.query("SELECT type FROM items WHERE iid = ?", [readedIt], function(err, result){
                            if(err) console.log(err);
                            var catInfo = getItemType(result[0]["type"]);

                            var insertItem = "INSERT INTO users_biznesspanel(user_id, ui_id, icat, iscat) VALUES(?, ?, ?, ?)";
                            connection.query(insertItem, [CurrentSocket.user_id, readedIt, catInfo.cat, catInfo.scat], function(err, result){
                                connection.release();
                                if(err) console.log(err);
                                console.log("Inserted item: "+readedIt);
                            });
                        });
                    }
                });
            }.bind(pool, id));
        }
    }

Comment: You need to refactor your code to make better use of control flow. The site [callbackhell.com](http://callbackhell.com/) has some guides on how to do this.
Answer: I advise you to query SQL in one complex sql, you could use the "case when" grammar,for example:
case sex
when '1' then '男'
when '2' then '女'
else '其他' end

And I always use 'sequelize' module in NodeJS to help me query sql. It would be safer and you could focus on your logistic.

Nodejs MySQL multiple query in a loop


PHP_SQL query not returning right answer

Question: First I would like to know how to display an image in PHP just by using the path of the image? without using BLOB.
AND
I have a table in my database which is layed out this way..
columns : i1 i2 i3 i4  i5 i6 i7 i8
each field hold a value or is empty.
I would basically want to display the values of i5 i6 i7 i8 according to what is in i1 i2 i3 i4.
For e.g:
i1=a i2=b i3=e i4=q  i5=g i6=l i7= i8=
For this case i would like g and l to be displayed. But i want the values to be stored in an array.
I tried doing:
$list = array(g,l)
$query = " SELECT i5, i6, i7, i8  FROM Table WHERE i1 AND i2 AND i3 AND i4 IN ('$list') ";
$s = mysql_query($query);
while($data = mysql_fetch_array($s)){
    $r_1 = $data['i5'];
    $r_2 = $data['i6'];
    $r_3 = $data['i7'];
    $r_4 = $data['i8'];
}
echo "$r_1  $r_2 $r_3  $r_4"`

Which is not working even if i do $list[0]
Help would be appreciated. Thanks
Comment: What do you mean by not working? Error messages? Not the output you expect?
Comment: nothing is returned @BrendanLong
Comment: How are you actually doing your query? Can you show us the full code?
Comment: Have you checked the return value of [`mysql_query`](http://php.net/manual/en/function.mysql-query.php)? It should return `FALSE` if there's an error, but you're not checking for it. Also, the `mysql_*` functions are deprecated, with a giant red box on every page of documentation, saying not to use them..
Comment: I dont really understand, wht do you mean `mysql_*`
Comment: Any function starting with `mysql_` is deprecated and should not be used. See the warning at the top of this page: http://php.net/manual/en/function.mysql-query.php
Answer: First I would like to know how to display an image in PHP just by using the path of the image? without using BLOB.

You don't display images in PhP, you display it in html. If you've got the path then simply generate an img tag in html with src attribute set to path :

Blobs are used to store images (actually big binary data, images, movies, ...) directly in the DB.
Comment: could you show me an example, tried to look for tutorial but in vain. thanks @Bartdude
Comment: A tutorial to what ? An image tag in HTML ?
Comment: Please update your question and provide more details. What have you tried ? With which result ? Which info do you have in your DB ? Where are these "paths" stored ?
Comment: I was doing it using BLOB before, but i wanted to learn to do it using the path. Couldn't find much about it so i asked here. And thanks for your reply
Comment: sorted it out. Thanks for the help @Bartdude
Answer: $s = mysql_query($query);
while($data = mysql_fetch_array($s)){

You're not checking if there's an error during the query. From the documentation for mysql_query:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

So do:
$s = mysql_query($query);
if($s === FALSE) {
    // Do something to handle the error here, possibly calling die()
}

Next problem, what if there's no results? Your variables would all be empty. You can test for that:
if(empty($r_1)) {
    echo "Oops, I guess we didn't get any results";
    // die()?
}

What if we get more than one row of results? I'm not sure how your program should handle this.
And finally, I think your SQL query isn't doing what you think it's doing:
SELECT i5, i6, i7, i8  FROM Table WHERE i1 AND i2 AND i3 AND i4 IN ('$list')

This will give you i5, i6, i7, and i8 when i1 is true, i2 is true, i3 is true, and i4 is equal to the string $list. If you want find results where all of them are in the list, you'll need to do multiple IN statements, and you'll need to pass $list as a list, not a string. You can see this answer for how to construct the query string to pass a list to MySQL.
Also note that the mysql_* functions are deprecated, and you should really learn to use PDO or the mysqli_* functions. It won't take very much time, and secure database access is much easier with them.
Comment: Thanks, was thinking about using learning PDO, I will soon. I had a look at your link, but when you say i will need multiple `IN`statement do you mean this way `WHERE $i1 IN ($list) AND $i2 IN ($list)...` @BrendanLong
Comment: @StringerB Yes. Except just putting $list is incredibly dangerous and probably won't work.


Using NTFS "traverse" permissions, but user still denied access to network share (SBS 2003)

Question: We have a staff member who requires access to a single folder in the root of a network share. All other files and folders in the share should be inaccessible to them.
I thought if I added only "Traverse Folder / Execute File" and "Traverse Folder / List Data", it would be enough for the user to browse the root of the share; however, they are denied access to the network share itself with only these permissions and so cannot drill down to the subfolder they need access to.
My goal is to grant only the absolute minimum permissions necessary for folder traversal of the root of the network share.
Ideally, I want any new folders created in the root of this share by other users to automatically restrict access to the user in question (so new folders should not inherit traversal permissions for the user).
Here are the NTFS options I have to choose from:

Just to be clear: the reason I am not simply using explicit deny permissions on the other subfolders is because I need any new subfolders created by staff to automatically inherit permissions which prevent the new user from accessing them.
I've never used the traversal permissions before, so am most likely making a basic mistake here.
Any advice would be appreciated.
Comment: What are the permissions on the share? You've only listed the NTFS permissions on the filesystem.
Comment: The share permissions were fine. It turned out other deny permissions were overriding the folder traversal permissions (as per my comment to your main answer).
Answer: You want Traverse Folder and List Folder like you've listed and you want to set the drop down at the top to This folder only. Then you need to set whatever other permissions you want that user to have on the explicit subfolder that they should have access to.
If you can't get into the root folder with what you've posted, it's likely because of the folder's share permissions and not the NTFS permissions - double check those.
Comment: If you enable access based enumeration on the share you get the added benefit of the user only seeing folders they can access.
Comment: @MDMarra: thanks for the "This folder only" tip. The problem was that the explicit deny permission on the root of the folder was set to "this folder, subfolder and files", when it should just have been "subfolder and files only". The share permissions were fine, and there was not even any need for me to use traverse permissions on the root of the share, as the user is a member of a security group which gives access to the root of the share anyway. My screenshot didn't show the deny permissons, which had a separate entry. Works great now. Just needed a minor tweak as deny was overriding access.
Comment: @Molotch: I've heard of Access-Based Enumeration many times before and I've often wished there was an easy way of only allowing users to see what they had access to. Little did I know that that was exactly what ABE does! Apparently this is supported on SBS 2003, so I will be experimenting with this today. Thanks for mentioning that. Pretty excited to get this feature working.
Answer: All users have the Bypass Traverse Checking user right by default, so my suggestion would be to not assign the permissions for the user the way you have but instead to assign the permissions for the user only on the file you need them to access and then give them a shortcut to that file. That will allow them to access the file without having to directly navigate through the shared folder to find the file.
http://technet.microsoft.com/en-us/library/cc739389(v=ws.10).aspx
If you need them to directly traverse/browse the shared folder structure then you'll have to do it the way MDMarra suggested in his answer.
Comment: I've got it working the way I originally wanted now but will read up on Bypass Traverse Checking as I don't fully understand the implications of using that yet. Thanks.


How to extract photos from JPG with white background?

Question: I have a JPG file which contains multiple photos over a white background.
I'm looking for a CLI tool which can extract photos from the source JPG (without supplying coordinates) into separate JPG files maintaining quality and photo resolution.
From some research I suspect ImageMagick can achieve this though unsure of the correct CLI command.
If useful, I'm on OSX 10.13.2 and have ImageMagick 7.0.7-28 installed.
Comment: I have two bash unix shell scripts using Imagemagick, multicrop or multicrop2, that will do that. The former searches a grid for the images. The latter each contiguous region for the images. Both should work. See  http://www.fmwconcepts.com/imagemagick/index.php. They can be run on Windows only in Unix environment such as Windows 10 built-in Unix or Cygwin. They can be run also via PHP exec(). You can also do that by converting all non-white to black and then using Imagemagick's -connected-components command to find the black regions and then crop your original at those bounding boxes.
Comment: CONTINUED: What is your Imagemagick version and platform?
Comment: @fmw42 updated question with OS and Imagemagick version
Answer: Here are two ways to do this in Unix using Imagemagick. I just cropped out your base image from your diagram, since I was not sure it that was part of your image or not. If it is part of the image, then you would have to trim that off first using -trim.
Input:

The first is my script, multicrop2:

(-f 10 is the fuzz factor for extracting the background)

(-u 3 means no attempt to unrotated the results)
multicrop2 -f 10 -u 3 image.jpg resulta.jpg

Processing Image 0
Initial Crop Box: 113x84+81+89

Processing Image 1
Initial Crop Box: 113x67+144+10

Processing Image 2
Initial Crop Box: 113x66+10+11

The second is using Imagemagick -connected-componets (which is what I use in my script)
What this does is:
1) fuzzy flood fill the background to transparent (since jpg is loss and does not preserve a uniform background.
2) change the color under the transparent to white and remove the transparency
3) change anything not white to black
4) apply -connected-components to throw out areas smaller than 400 pixel area and extract each bounding box and color
5) if the color is gray(0), i.e. black, then crop the original image to the bounding box and save to disk

OLDIFS=$IFS
IFS=$'\n'
arr=(`convert image.jpg -fuzz 10% -fill none -draw "matte 0,0 floodfill" \
-background white -alpha background -alpha off \
-fill black +opaque white -type bilevel \
-define connected-components:verbose=true \
-define connected-components:mean-color=true \
-define connected-components:area-threshold=400 \
-connected-components 4 null: | tail -n +2 | sed 's/^[ ]*//'`)
IFS=$OLDIFS
num=${#arr[*]}
j=0
for ((i=0; i<num; i++)); do
bbox=`echo "${arr[$i]}" | cut -d\  -f2`
color=`echo "${arr[$i]}" | cut -d\  -f5`
if [ "$color" = "gray(0)" ]; then
convert image.jpg -crop $bbox +repage resultb_$j.jpg
j=$((j+1))
fi
done

EDIT: Add processing of your actual image
Input:

The first thing to note is that your actual two images are right at the right side, but there is a black edge there. Also one at the top. That black edge connects the two image so that they cannot easily be separated by the multicrop2 script. So you need to shave off the right side by enough pixels to remove that edge. There is also the edge at the top and you can shave that off if you want. If you do, you can reduce the -d argument. The -d argument needs to be smaller that the area of the smallest image you want to extract and larger than any other minor noise or the stripe at the top in area. So I clip off 20 pixels from the right side and then use multicrop2 with a very large value for -d. I have chosen a value for -f of 8, which is seems to be in a rather narrow range due to the non-constant background. You can add -m save to look at the mask the script creates to see that you get a good separation between your two images. I seed the processing at -c 20,20 to avoid the black border at the top of your image, so that the script gets a good measure of the background color for the flood fill step.
convert test.jpeg -gravity east -chop 20x0 tmp.png
multicrop2 -c 20,20 -f 8 -d 100000 tmp.png result.jpg

Processing Image 0
Initial Crop Box: 2319x1627+968+2153

Processing Image 1
Initial Crop Box: 2293x1611+994+436

Comment: Thanks @fmw42, unfortunately i'm not having much luck with the real-life case. Have been tweaking the command params but getting nowhere fast. eg. trying to extract the following photos - https://www.dropbox.com/s/9qh1vg7mw2m197p/test.jpeg?dl=0
Comment: For future reference it is always better to add actual example rather than "something like". File resolution will change as you are saving as jpg. There would be less loss if your original images were of a better format than jpg. You may be having problems as two of your edges have black borders. I assume you can not rescan the photos?
Comment: I have modified my answer to show an example of using multicrop2 with your newly provided actual input image.
Comment: im using a simpler convert command: `convert input.png -blur 20x20 -threshold 99% -define connected-components:verbose=true -define connected-components:mean-color=true -define connected-components:area-threshold=400 -connected-components 4 null:` - see also [Convert a greyscale image to 1-bit black/white](https://stackoverflow.com/questions/64297092/convert-a-greyscale-image-to-1-bit-black-white-with-definable-threshold-maintai)


Facebook Page Plugin

Question: there's a problem at installing the new facebook page plugin. I create a simple test.html file with the following code including the plugin-code from https://developers.facebook.com/docs/plugins/page-plugin. But there is an error message from my browser that file://connect.facebook.net/de_DE/sdk.js#xfbml=1&version=v2.4 cannot find on the server. I also completed the adress by http: or saved the Facebook-file local and embedded it as a local js-file, but the page plugin doesn't appear. What's the problem?!
HTML-Code in test.html:
<!doctype html>

<meta charset="UTF-8">

Facebook

Comment: try this : http://stackoverflow.com/a/32134145/1956964
Answer: You do not appear to be including an App ID in your URL for the SDK request. If you have not yet created an App ID, you can do so here: https://developers.facebook.com/apps
Note the appended &appId=[APP_ID_NUMBER_GOES_HERE] in the example below from my Website (real App ID removed, obviously)
js.src = "//connect.facebook.net/de_DE/sdk.js#xfbml=1&version=v2.4&appId=[APP_ID_NUMBER_GOES_HERE]";

The Facebook SDK quick start guide and documentation should answer any other question you have about getting started: https://developers.facebook.com/docs/javascript/quickstart/v2.4
Comment: But in https://developers.facebook.com/docs/plugins/faqs facebook says that "you do not need to create a Facebook app for integrating a Social Plugin" or "to have a Facebook Developer account". In fact there are websites (http://lars-castellucci.de for example), which exactly using the code from facebook, which I put in the example above. The only thing I did is copying the code from facebook and putting it into the simplest html-file you can create - and it doesn't work. Seems a little bit strange to me...
Answer: Ok managed the problem. The only thing I had to do is uploading my site to an online server.

Facebook Page Plugin


Make half the div one color using Twitter Bootstrap

Question: I need some help here. I am trying to create a page header with some trickiness to it. I need to have a container-fluid with the left half background blue and the right half white. I then need a h2 "Title" /h2 inside a ? container to center it in the 12 columns the title has a border-bottom which stretches the width of the browser though. Here is my code but again I know it is some what half done since I cant figure out the best way to get the 50% background color. I need this to work on IE8 to present and the rest of the major updated browsers.
I hope I can get an image in here for you guys. If not I will set up a bootply for my example.

Thanks ahead of time for your help.

Case Studies

Answer: You are on the right track, just change the class to body element.
For the fancy underling of the h2 element I have combined border-bottom property and styled hr (horizontal rules) element.
h2 here is an inline-block element, therefore the border-bottom element is present only for the length of the h2 text. Margins for heading and horizontal rule have been modified to zero pixels.

body {
  background: linear-gradient(to right, black 0%, black 50%, #fff 50%, #fff 100%);
  display: block;
  padding: 0;
}
/* couldn't find it in html
.halfAndhalf {
  width: 50%;
  background: blue;
  display: inline-block;
}
*/

.halfWrapper h2 {
  color: #fff;
  font-family: monospace;
  font-size: 26px;
  text-transform: uppercase;
  border-bottom: 2px solid #4EB2DF;
  display: inline-block;
  padding-bottom: 0px !important;
  margin-bottom: 0px !important;
}
.style-one {
  border: 0px;
  height: 1px;
  background: #4EB2DF;
  padding-top: 0px !important;
  margin-top: 0px !important;

}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

Case Studies

Comment: omg really it was that easy or am I brain farting on a Tuesday!( I will try this asap. I can see right away that I cannot add this to the body since it is just this one particular page that will have this style of header.
Comment: I added a better screenshot image of the entire page and what I need. I tried the solution you added but I do not think it will work properly. I also need it to work for IE8 and above.
Comment: the new screenshot changes everything. you will have to take a different approach. I am thinking of something like this - a nav, then a container with 2 divs -one div having the text "CASE STUDY" and the second div again containing two divs and the respective boxes (divs again).
Comment: also there are workarounds to make `linear-gradient` work with old browsers (read IE8+)
Comment: I know the workarounds with linear-gradient which is why I did not include all of that code. I am trying something like what your talking about but I am not seeing how I can get that dumb border to stretch like it is in the pic... @Ashesh can you add any code examples of what you are trying to suggest?
Comment: that is a just a rough sketch I came up with, you should try your own so that you will be able to actually build it. If you get stuck, post a new question. I was able to emulate that underline effect to the `h2` element. Hope it's good enough.
Answer: Ok so I tried this several ways and feel this may be the best solution. Here is what I came up with. I hope it can solve other peoples issues that are similar.

CASE STUDIES

Comment: I feel that `` is more elegant than using a blank heading. Not good for SEO and more lines of code too :P
Comment: Ashesh what about the edit I made. Is this better? The main reason I used two col-xs-6's and added background color this way was to avoid using so much browser specific css hacks. What do you think?
Comment: I am going to try again using a similar method of using colored columns like what I am trying to do above. I am open to a better solution but I am getting annoyed trying to find a workable solution using bootstrap.
Comment: The above answer is not keeping the right layout for all media screens. This makes this a less desirable solution. Does anyone have any suggestions for me?


Como Salvar o Campo Data de uma Aplicação Java SE no PostgreSql

Question: Eu preciso salvar essas duas datas (DATA DE ALOCAÇÃO e DATA DE DEVOLUÇÃO) de uma alocação, aonde eu eu tenho a seguinte Tabela Aloca:
CREATE TABLE public.aloca
(
  alocod serial NOT NULL,
  alodtdevolucao date NOT NULL,
  alodtalocacao date NOT NULL,
  alo_eqcod integer NOT NULL,
  alo_setcod integer NOT NULL,
  alo_funcod integer NOT NULL,
  CONSTRAINT pk_aloca PRIMARY KEY (alocod),
  CONSTRAINT fk_equipamento FOREIGN KEY (alo_eqcod)
      REFERENCES public.equipamento (eqcod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_funcionario FOREIGN KEY (alo_funcod)
      REFERENCES public.funcionario (funcod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_setor FOREIGN KEY (alo_setcod)
      REFERENCES public.setor (setcod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

A classe Bean Aloca:
import java.sql.Date;

public class Aloca {
    private Integer alocod;
    private Date alodtdevolucao;
    private Date dtAlocacao;
    private Equipamento equipamento;
    private Setor setor;
    private Funcionario funcionario;

    public Integer getAlocod() {
        return alocod;
    }

    public void setAlocod(Integer alocod) {
        this.alocod = alocod;
    }

    public Date getAlodtdevolucao() {
        return alodtdevolucao;
    }

    public void setAlodtdevolucao(Date alodtdevolucao) {
        this.alodtdevolucao = alodtdevolucao;
    }

    public Date getDtAlocacao() {
        return dtAlocacao;
    }

    public void setDtAlocacao(Date dtAlocacao) {
        this.dtAlocacao = dtAlocacao;
    }

    public Equipamento getEquipamento() {
        return equipamento;
    }

    public void setEquipamento(Equipamento equipamento) {
        this.equipamento = equipamento;
    }

    public Setor getSetor() {
        return setor;
    }

    public void setSetor(Setor setor) {
        this.setor = setor;
    }

    public Funcionario getFuncionario() {
        return funcionario;
    }

    public void setFuncionario(Funcionario funcionario) {
        this.funcionario = funcionario;
    }
}

A classe AlocaDao:
 public class AlocaDao {
    Connection conn = null;
    PreparedStatement ps   = null;
    ResultSet rs   = null;
    String sql  = "";

    public boolean salvar(Aloca aloca){
        conn = Conexao.getConexao();
        boolean teste = false;
        sql = "INSERT INTO aloca(alodtdevolucao, alodtalocacao, alo_eqcod, alo_setcod,alo_funcod)\n" +
                "    VALUES (?, ?, ?, ?, ?);";

        try {
            ps = conn.prepareStatement(sql);

                        ps.setString(1, aloca.getAlodtdevolucao().toString());
                        ps.setString(2,aloca.getDtAlocacao().toString());
                        ps.setString(1,aloca.getAlodtdevolucao().toString());
                        ps.setInt(2,aloca.getEquipamento().getEqcod());
                        ps.setInt(3,aloca.getSetor().getSetCod());
                        ps.setInt(4, aloca.getFuncionario().getFuncod());
            ps.execute();
            teste = true;
        } catch (Exception e) {
            System.out.println("Erro no salvar -> "+e.getMessage());
                        JOptionPane.showMessageDialog(null, "Erro ao Salvar !!!");

    }
        return teste;
    }
}

A classe Controle do Aloca:
public class ControleAloca {
    AlocaDao aloDao = new AlocaDao();
    Aloca aloca = new Aloca();
    public boolean salvar(Aloca aloca){
        boolean salvou = aloDao.salvar(aloca);
        return salvou;
    }

}

E por último o método da classe View que Salva:
private void bt_realizar_alocActionPerformed(java.awt.event.ActionEvent evt) {
    aloca.setDtAlocacao((Date) data_alocacao.getDate());
    aloca.setAlodtdevolucao((Date) data_alocacao.getDate());
    aloca.setEquipamento((Equipamento) comboBox_Equipamento.getSelectedItem());
    aloca.setSetor((Setor) comboBox_Setor.getSelectedItem());
    aloca.setFuncionario((Funcionario) comboBox_Func.getSelectedItem());

    boolean salvou = controllerAloca.salvar(aloca);
    if(salvou){
        JOptionPane.showMessageDialog(null, "Registro Salvo com Sucesso !!!");
    }

}

Na minha View os campos para as datas são: data_alocacao e data_alocacao.

E acima é minha tela.
   PERGUNTA: como eu faço para salvar essas duas datas no meu banco de dados, ficaria muito agradecido e vocês me ajudassem please.
Comment: Qual o erro? Tentou usar ps.setDate(1, data)?
Answer: A data deverá ser convertida, segue exemplo abaixo:
ps.setString(1, new java.sql.Date(aloca.getAlodtdevolucao()));
ps.setString(2, new java.sql.Date(aloca.getDtAlocacao()));
...


Mann Whitney U or Wilcoxon Sign Rank test?

Question: I have been collecting data where participants have been allocated to one of three different conditions and had to answer some questions. The data looked like this:
  Condition  Response
1  a            5
2  b            2
3  a            7
4  c            6
5  b            3

I was planning to do an ANOVA but the assumptions of normality was broken so I did a Kruskal-Wallis test. For the post-hoc would I do Mann-Whitney or the Wilcoxon Sign-rank test? I am unsure of the difference between the two other than with r coding I believe one to use wilcox.test and the other to use wilcox_test (please correct me if I'm wrong).
If this is necessary to know, I hypothesised the results from the questions the participants answered should be affected by the condition they were allocated. Specifically, condition 'a' would be the most effective.
So I guess what I'm asking is:
Should I use Mann-Whitney or Wilcoxon Signed Ranked or something else entirely as the post hoc?
Comment: 1. Try searching *Kruskal Wallis post hoc* (and variations on that theme). There are many posts relevant to this. 2. Why would you consider a signed rank test?  3. What do the integer response values represent?
Answer: Wilcoxon Signed Ranked test is performed when the samples are paired. An example would be if for every individual you had different measurements (for instance at different phases of an experiment) and you wanted to see if there is a difference between each phase.
It seems that in your case your samples are independent because every participant has a single condition and participates one time. In this case, you can use the Mann-Whitney test.
That being said, it is recommended that you use the Dunn's posthoc test rather than the Mann-Whitney test as per here or here.
Comment: Thank you so much for clarifying! I have taken your suggestions into consideration and have done the Dunn's test instead. At least I can't confuse Dunn's test for something else haha


Closing database connection

Question: I am doing project using mongodb and zendframework 2 so here I create connection in the constructor
private $conn;

public function __construct(){
    $this->conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
}

It contain several actions to perform database operations like createdb, dropdb, renamedb like wise. so I close that connection within the __distruct() method
public function __destruct(){
    $this->conn->close();
}

my code works fine. but I would like to know is this ok?
Comment: I'm pretty sure you dont actually need that as php will close the connection right after it has run the script.
Comment: Can't you use an ORM instead of doing your own abstraction layer?
Comment: @j0k yes I use docrain odm tool. but create database I use PHP core classes
Comment: Plus 1 for Tikkes. PHP closes the connection right after executing a query.
Answer: PHP closes database connections automatically.
You can read more about this in this post
however
read this
quote:
"Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."
So basically, in case you have tons of things going in and out of the database, then yes, you might want to close right after.
In my opinion it is rather optional and your own choice wether to kill the process or not.

Closing database connection


Get object by HTML tag and remove from localstorage

Question: this is my first question on stackoverflow.
and a little bit experience on code.
so I have a localstorage like this:
myDB: "[{"key:"123","label":"abc"}]

I have a div with "abc" as value:

abc

And many id's div clone with different value

abc

cde

efg

I want to read the value of the ID "name", make a if/else like looking "abc" are in the localstorage, if yes delete it with the key. else not delete.
I have thinking of using document.getElement to get value from ID and compare it to localstorage and using if else to do that thing. But there are many clone have that event to trigger the function to delete it. So the function don't know which ID's value to be compare and delete it.
I really awkward for this newbie question. But I have to ask, many thanks first :)
*New question:
I want to delete last element of the localstorage.
Can I convert localstorage to array then using array.pop(). Then convert the changed array again to the localstorage?
Comment: `id`s should be unique on the page; what you probably want to do is use `class` instead, then `getElementsByClassName` will give you an HTMLCollection of all your elements
Comment: I agree with Hamms, your `div`s should have a unique id. Also, for managing local storage here are some good methods:

`setItem()` Add key and value to local storage
`getItem()` Retrieve a value by the key
`removeItem()` Remove an item by key
`clear()` Clear all storage
Answer: First, as was mentioned by others, id must be unique. You can use any other attribute instead, for example, class:

abc

def

ghi

jkl

mno

Then, to query these elements, you could use document.getElementsByClassName("name") which will return you an array-like object. You can convert this object to an array of values using a combination of spread syntax and map method:
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);

To work with the local storage you can use localStorage.setItem and localStorage.getItem. As you know, the local storage stores only strings, so JSON.parse and JSON.stringify methods will be helpful too.
Here is the example of code:
localStorage.setItem("myDB", '[{"key":"123","label":"abc"}, {"key":"456","label":"mno"}]');
console.log('Local storage before: ', localStorage.getItem("myDB"));
// extracting div values to an array
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);
// creating a js object from myDB string
let db = JSON.parse(localStorage.getItem("myDB"));
// leaving only those elements, which labels are not in the values array
localStorage.setItem("myDB", JSON.stringify(db.filter(item => !values.includes(item.label))));
console.log('Local storage after: ', localStorage.getItem("myDB"));

JSFiddle link: https://jsfiddle.net/v03wpgq1/4/
Comment: @JonP agreed. it's what id stands for
Comment: @JonP - I mean, they really shouldn't. But that doesn't necessarily mean *must* be unique: http://jsfiddle.net/s91moxdu/ ...
Comment: @TravisJ, nope, as per the spec it **must** be unique see: https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute & https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
Comment: @JonP - I mean, just to be pedantic, the definition of must is should. So, semantically, there was no difference between the two in your earlier comments. From a use standpoint though, there are situations where non unique identifiers can be used, as shown.  They should be unique. They can also not be unique and still be used as valid identifiers to locate elements. Hopefully no one does that, but it is best to at least show all the information.
Comment: @TravisJ, we've derailed this enough but, being pedantic, the definition of "must" is **not** "should" : https://blog.oxforddictionaries.com/2014/03/03/must-should-ought/. "Should" implies that there is an option, but a preference. With "must" there is no option, and this is what the spec states.
Comment: @JonP - Google defines it as "be obliged to; should (expressing necessity)." But I understand where the author of the blog was coming from as well. While the spec may indicate uniqueness, that is not how the implementation works in all cases. Id's should be unique, there is the option for them to be used as non unique identifiers. It may be a bad option, but regardless, it exists.
Answer:
id attributes should be unique on the page, otherwise only the last one on the page has the ability to be referenced easily (or at least, properly).
There should be a section that contains these which makes them easily queryable. Perhaps inside of an element with an id guaranteed to uniquely hold a set of name value pairs.
Using document.querySelectorAll is your best bet for finding these elements, and will be made easier by creating a structure that can be queried.
With a set of items to look for, it should be easy to iterate and test for values and keys inside of localStorage.


Qual a função do método mágico __wakeup no php?

Question: Eu li a documentação, porém não ficou muito claro. __wakeup() restabelece a conexão com o banco de dados?
Por exemplo, tenho um script que é executado por bastante tempo, chega uma hora que a conexão com o banco que foi aberta é perdida. Se eu colocar no __wakeup() o método que estabelece a conexão, ela será refeita? Se não, como posso fazer isso? Lembrando que tudo, transações, conexão com o DB e etc; estão dentro da mesma classe.
Answer: Com método mágico __wakeup() você pode reconstruir objetos serializados através do método unserialize(). A serialização de objetos é útil quando você precisa transportar objetos para serem executadas em um outro lugar (em filas (queues) rodando em outro servidor por exemplo) ou precisa armazenar o estado de um objeto em uma string.
Lembrando que esse método mágicos está em desuso em favor da interface Serializable presente desde o PHP 5.1.
Veja um exemplo de como implementar a interface Serializable:
<?php
class obj implements Serializable {
    private $data;
    public function __construct() {
        $this->data = "My private data";
    }
    public function serialize() {
        return serialize($this->data);
    }
    public function unserialize($data) {
        $this->data = unserialize($data);
    }
    public function getData() {
        return $this->data;
    }
}

$obj = new obj;
$ser = serialize($obj);

var_dump($ser);

$newobj = unserialize($ser);

var_dump($newobj->getData());

O retorno será:

string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"

Código extraído da documentação.

Por exemplo, tenho um script que é executado por bastante tempo, chega
  uma hora que a conexão com o banco que foi aberta é perdida. Se eu
  colocar no __wakeup() o método que estabelece a conexão, ela será
  refeita?  Se não, como posso fazer isso? Lembrando que tudo, transações, conexão com o DB e etc; estão dentro da mesma classe.

Esses método mágico não funciona dessa forma. Nesse caso você pode capturar algum tipo de Exception e dar um retry na conexão sem precisar serializar um objeto por exemplo. Provavelmente você perderá informações de transactions nesse caso.


get form_state values from ajax callback through hook_form_alter?

Question: I'm having a little problem with my drupal 7 module.
I'm trying to get the $form_state['values'] from $form['base']['st-volume-pricing']['price'] and $form['base']['st-volume-pricing']['till-amount'] in my ajax callback so that I can add them to a results table.
Is this the right way to do it or am I missing something?
function mymodule_form_alter($form, &$form_state) {
  $form['base']['st-volume-pricing']['price'] = array(
    '#type' => 'uc_price',
    '#title' => t('Price'),
    '#description' => t('Set the price for this volume\'s reduction'),
    '#size' => 10,
    '#prefix' => '

',
    '#suffix' => '	',
  );
  $form['base']['st-volume-pricing']['till-amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Till Amount'),
    '#description' => t('The amount till which the volume discount applies'),
    '#size' => 10,
    '#prefix' => '',
    '#suffix' => '	',
  );
  $form['base']['st-volume-pricing']['add'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
    '#submit' => array('mymodule_add_volume_standard'),
    '#ajax' => array(
      'callback' => 'mymodule_add_volume_standard_ajax_callback',
      'wrapper' => 'st-volume-results',
      'method' => 'append',
      'effect' => 'fade',
    ),
    '#prefix' => '',
    '#suffix' => '
',
    '#title' => t('Click this button to add a standard volume price'),
  );

  //this is our results table
  $form['base']['st-volume-pricing']['st-volume-results'] = array(
    '#type' => 'markup',
    '#markup' => '

' . t('Price') . '	' . t('From Amount') . '	' . t('Till Amount') . '

',
  );
  variable_set('vol-st-price', NULL)
  variable_set('vol-st-from', 1)
  variable_set('vol-st-till', NULL)

  //this is our row that will be inserted
  $form['base']['st-volume-pricing']['st-volume-results']['row'] = array(
    '#type' => 'markup',
    '#markup' => '
' . variable_get('vol-st-price') . '	' . variable_get('vol-st-from') . '	' . variable_get('vol-st-till') . '
',
  );
}

When I'm using it inside here:
function mymodule_add_volume_standard_ajax_callback($form, &$form_state) {
  //check if there is a previous volume price and set the from field
  if (variable_get('vol-st-till') !== NULL) {
    variable_set('vol-st-from') = variable_get('vol-st-till') + 1;
  };
  //add or overwrite the value entered in price
  variable_set('vol-st-price') = $form_state['values']['base']['st-volume-pricing']['price'];
  //add or overwrite the value entered in till
  variable_set('vol-st-till') = $form_state['values']['base']['st-volume-pricing']['till-amount'];
  //create new row in results table
  return $form['base']['st-volume-pricing']['st-volume-results']['row'];
}

drupal_set_message("
" . print_r($form_state['values']) . "
");
displays 1.
I suppose that $form_state['values'] should only work during the submission of a form.
How would one go about doing this when using a hook_form_alter() and ajax callbacks?
I also tried displaying drupal_set_message("
" . print_r($form_state['values']) . "
"); in my function mymodule_add_volume_standard. Which also displayed 1.
Neither does it work when trying it in the hook_form_alter() which is default behaviour I suppose?
I'd really appreciate it if someone could clarify some things for me.
Answer: Some basics:
function mymodule_form_alter($form, &$form_state) {

hook_form_alter is a generic alter function that receives a third argument $form_id to distinguish the possible forms. Right now you would alter every form in your site.
The correct function signature is:
function mymodule_form_alter(&$form, $form_state, $form_id) {

You can see, that the $form itself is passed as a reference and can be changed. There is no way of changing $form_state directly during the form building process, which is when hook_form_alter is invoked.

Concerning $form_state['values'] in validation and submit handlers: All elements defined in the $form array are by default inserted into a flat structure in $form_state['values']. This means that with your setup, you would access the value entered in $form['base']['st-volume-pricing']['till-amount'] as $form_state['values']['till-amount']. You can change that behavior by defining #treefor the form element's parent, see for example: https://drupal.org/node/48643
Edit: The general approach for ajax forms is that in the submit you store values inside $form_state, e.g. in $form_state['storage'], set $form_state['rebuild'] which assures that the form builder and hence your alter function is called again, and then test for the presence of stored values inside your form alter function. Depending on the submitted values you would then implement the logic to achieve what you want.
Comment: 1. my bad I meant I'm using: `hook_form_FORM_ID_alter()` instead.

2. Yes I understood that part. Thank you for confirming.

I shall have a look at the reference you gave and report back.

Thank you for the help.
Comment: @Simbaclaws I have updated the answer regarding ajax.
Comment: Thank you!! It works!
I'll update the solution in a short while.
I still have to find a way of validating user input through the callback.
Comment: @Simbaclaws The validation would be done in a validation handler, not in the callback. Form processing is essentially the same as with non-ajax forms. Check this doc if you don't know it yet: https://drupal.org/node/752056


square root in $Z_n^*$

Question: Let $n$, $x$ be two numbers s.t. $x \in Z_n^*$. And lets assume there exists $y$ s.t. $y^2=x$ (mod n). Is it true that this implies that $y \in Z_n^*$? and if so, how can I show it ($gcd(n,y)=1$)?
Comment: If $y^2$ is invertible, then so is $y$.
Answer: $$x\in\Bbb Z_n^*\Longleftrightarrow (x,n)=1$$
Now, suppose $\,\exists\,y\in\Bbb Z_n\,\,s.t.\,\,y^2=x\,$ , and suppose further that
$$(y,n)=d\Longrightarrow n=ad\,,\,y=bd\Longrightarrow y^2=b^2d^2=x\Longrightarrow (x,n)\ge d$$
and from the above it follows at once that $\,(y,n)=d=1\Longleftrightarrow y\in\Bbb Z_n^*\,$
Comment: I'm not sure I understand your question: do you mean "...but $\,y^2\neq x\,$"... in $\,\Bbb Z\,$? If so then yes, of course, since the proof given above applies for $\,\Bbb Z_n\,$ and thus also for the integers (which I still am not sure why would be important for you...)
Comment: Is that also true when $y^2=x$ (mod n) but $y^2 \neq x$?
Answer: From the fact that $y^2 = x$ is a unit we know there exists an inverse $u y^2 \equiv 1^2 \pmod n$.
From the fact that quadratic residues form a subgroup of the units group and that a residue times a non-residue is a non-residue we deduce that $u$ is a quadratic residue so $y$ is a unit.
Theorem A residue times non-residue is a non-residue in the units group.
proof: Let $n$ be a non-residue, suppose $r^2 n = u^2$ then $n = (r^{-1} u)^2$.

square root in $Z_n^*$


Outlier detection and normality assumption

Question: So I am following this applied statistics class, and we were taught 5/6 tests for outlier detection and normality test, then told to apply these to some datasets. I am quite confused on how to go for it.
I plotted an histogram of each dataset, and noticed that some of them were clearly not normal, so I rejected their normality with the test, and skipped outlier detection (as the tests presume the population is normally distributed), so far so good.
The problem comes when the histogram looks approximately normal. How can I know whether normality is a valid assumption or not? I could apply the test, but its result could be invalid due to possible outliers in the data, but to know if there are outliers I need normality, but... It's a serpent biting its tail.
I should then start from something, e.g. if I want to use a test for outliers then I can filter out the datasets that are not normally distributed by looking at the histogram. But that is subjective, so what is the point of applying a "precise" outlier test after cherry picking the datasets? To me, it has the same value as directly detecting outliers by looking at the histogram.
What is a sound way to proceed?
Comment: You have a problem of confusion.  Outlier models assuming normality are really saying that in the absence of outliers the data are normal.  When outliers are present the data should not look normal and so why test the data sets for normality.?  So just apply a test like Grubbs test or Dixon's test for a single outlier. Multiple outliers raise the issue of masking.
Comment: @Xi'an sorry, I didn't know. Added
Comment: No problem, it simply helps with constructing an answer.
Comment: @MichaelChernick so, after all, the two tests are looking at the same thing? Because normality implies no outliers, and no outliers imply normality. Or am I misunderstanding? Maybe outlier tests need normality of the population, while normality tests test the normality of the sample?
Answer: I think these 2 previously answered questions will be very useful for you as you ponder testing for normality:
(1) how-to-choose-between-t-test-or-non-parametric-test-e-g-wilcoxon-in-small-sample
(2) is-normality-testing-essentially-useless
This answer has some especially useful info about test selection based on your N and what the tails look like of the distribution.
I would not recommend basing test selection on the results of a normality test. I would look at the data, think about your expected distribution based on the type of data you have, and follow the advice from above. A QQ plot can be helpful for 'eye-balling' if the data are approximately normal and test if a simple transformation of the data could help.


What are restrictions for junior tennis players on number of senior tournaments?

Question: Recently in a discussion I have heard that young players can only enter a limited number of senior tournaments. The number depends on the age of the player. (This information was mentioned in an interview with a coach of a girls' singles grand-slam champion, when discussing her transition into competing at senior level.) I would like to know more about these limits.

What are limits for the number of senior tournaments a junior player can enter. Do they depend on age? Are they different for men/women?
Answer: WTA/ITF - Women Competitions
For more details you can look into
2015 WTA Official Rulebook (Internet Archive). Briefly summarized it says in the section XV. Age eligibility and player development that:

Players under 14 cannot enter tournaments on WTA or ITF Women's Circuit.
Above 14 players can play in Fed Cup.
14 years old player can play at 8 ITF Women's Circuit tournaments. (This limit is on the number of tournaments between her 14th and 15th birthday.)
15 years old player can play 10 tournaments (and WTA Finals or WTA Elite Trophy if she qualifies).
16 years old player can play 12 tournaments  (and WTA Finals or WTA Elite Trophy if she qualifies).
17 years old player can play 16 tournaments  (and WTA Finals or WTA Elite Trophy if she qualifies).
For players that reached 18 years there is no limit on the number of professional tournaments.

ITF - Junior Competitions
There are also limits on the number of junior tournaments a player may enter. Again, for more details see 2014 Junior Circuit Regulations (Internet Archive).
I will reproduce here the table from that document (Appendix G: ITF junior circuit age eligibility rule) which gives an overview.
<code>--------------------------------------------------------------------|
|   Age | Number of Tournaments permitted                           |
|   18  | Unrestricted                                              |
|   17  | Unrestricted                                              |
|   16  | 25                                                        |
|   15  | 16 (and 4 additional tournaments for players in Top 20)   |
|   14  | 14 (and 4 additional tournaments for players in Top 20)   |
|   13  | 10 (and 4 additional tournaments for players in Top 50)   |
| 11/12 | 0                                                         |
--------------------------------------------------------------------|
</code>
Comment: I did not find anything about Boys' and Men tournaments. If I find some information about this, I will update my answer.
Answer: ATP World Tour / Challenger
According to section 7 of the ATP Rulebook, the following restrictions apply for male players:

7.02 Entries
A. Gender / Age Limitation
The ATP will use the age of a player on the first (1st) day of the
  qualifying competition. Male players age sixteen (16) or older are not
  limited in the number of tournaments they may enter. Players under the
  age of sixteen (16) are subject to the following entry restrictions in
  ATP World Tour or ATP Challenger Tour tournaments (includes entry as a
  wildcard):

Male players under the age of fourteen (14) shall not be eligible for entry into any ATP World Tour or ATP Challenger Tour tournament.
Male players aged fourteen (14) shall be eligible for entry into a maximum of eight (8) ATP World Tour or ATP Challenger Tour
  tournaments.
Male players aged fifteen (15) shall be eligible for entry into a maximum of twelve (12) ATP World Tour and ATP Challenger Tour
  tournaments.


OpenJPA fetching entity with a lazy collection

Question: I have two entities :
A:
class A {

 @Id
 Long id;

 @OneToMany(fetch = FetchType.LAZY)
 List listOfB;
}

and class B :
class B {

 @Id
 Long id;

 @ManyToOne(fetch = FetchType.LAZY)
 A a;
}

now in my spring data repo I'm creating a query like :
@Query("SELECT a FROM A a INNER JOIN a.listOfB b WHERE b.id = :id")

The problem is, that the query is executed and returns some A objects, but when I want to access the listOfB I'm getting a NullPointerException ...
A a = aRepository.findByOwnQuery(id);
a.getListOfB().size(); -> NullPointerException

Comment: so the list field is NULL, and the object "a" is presumably detached by that point so cannot fetch the field from the database. So fetch it before unmanaging the "a" object
Comment: Post your code, and post the exact and complete stack trace of the exception.
Comment: What code do you need ? There'are two entities with relation marked as lazy, and a query.
Comment: The code that causes the NPE.
Comment: @NeilStockton how ? I assume that when I'm joining the B class by `INNER JOIN a.listOfB b` I will have this list in result object ...
Comment: nope. that simply joins to form the query. "JOIN FETCH" is valid JPQL syntax ...
Answer: The NullPointerException could be because you are fetching your child listOfB Lazily in your parent class A.
Try JOIN FETCH like so
@Query("SELECT a FROM A a JOIN FETCH a.listOfB b WHERE b.id = :id")

Comment: The JPA spec doesn't allow use the 'b' defined on a fetch join clause within the query. You would have to create a separate join for the query to use in the where clause.
Comment: With such contruction I'm getting the `ArgumentException` error `Encountered "b" at ... but expected: [",", "GROUP", "HAVING", "INNER", "JOIN", "LEFT", "ORDER", "WHERE", ]`.
Comment: Are you sure this exception is because of the single change i suggested.?Because my change doesn't change the argument. It only changes the strategy to fetch to children. Please cross check.
Comment: Yep, because the previous query executes fine but returns null for the list.
Comment: @Chris Thats something i didn't know. Can you post some reference.
Comment: I don't have a link to the spec, but the definition in "22.214.171.124 Fetch Joins" of jpa 2.1 does not include aliases.  Its posted in other answers elsewhere as well though https://stackoverflow.com/a/16693590/496099


Trouble installing NodeJS on Kali Linux docker image

Question: I am trying to create a docker image based on the Kali Linux base image, and I need to install NodeJS as a dependency for my application.
Here's my Dockerfile:
FROM kalilinux/kali-linux-docker

RUN apt-get update -y && \
    apt-get dist-upgrade -y && \
    apt-get autoremove -y && \
    apt-get clean -y

RUN apt-get install curl -y

RUN curl --silent --location https://rpm.nodesource.com/setup_8.x | bash - \
    && apt-get install nodejs -y

RUN npm i -g npm

ENV NODE_ENV production

WORKDIR /root/app
COPY . .

RUN npm i

EXPOSE 4000
ENTRYPOINT ["npm", "start"]

However, I hit the following error trying to install NodeJS:
Step 4/11 : RUN curl --silent --location https://rpm.nodesource.com/setup_8.x | bash -     && apt-get install nodejs -y
 ---> Running in a63e56802eba

## Installing the NodeSource Node.js 8.x LTS Carbon repo...

## Inspecting system...

## You don't appear to be running an Enterprise Linux based system,
please contact NodeSource at https://github.com/nodesource/distributions/issues
if you think this is incorrect or would like your distribution to be considered
for support.

The command '/bin/sh -c curl --silent --location https://rpm.nodesource.com/setup_8.x | bash -     && apt-get install nodejs -y' returned a non-zero code: 1

Admittedly I'm confused by a few things... namely that I was under the impression that NodeJS was already installed on Kali Linux (I have a VirtualBox VM using Debian 64-bit where it exists). I went as far as trying to install the kali-linux-all metapackage, but NodeJS/npm don't seem to exist.
Am I simply misunderstanding some basic premise of Docker and/or Kali Linux? Is there any other way to install NodeJS into my container?
Comment: I believe the Docker tag exists for the Docker API. Programming against the Docker API is certainly on-topic. Docker is just another lightweight VM like chroots. Neither are primarily programming or development related. They are something developers use on occasion. I ask my Docker and chroot questions on [Unix & Linux Stack Exchange](http://unix.stackexchange.com/). I think the down votes are due to the Kali tag. Nearly every Kali question is off-topic and those questions get hit hard nowadays. (In case it matters... I did not cast a down vote. I don't believe in piling them on).
Comment: Not to be argumentative, but isn't configuring Docker containers a programming/development question? Based on the negative downvotes and lack of answers I'm sure another site may have been more helpful, but I don't really agree that this is off topic. FWIW I also think my question is "Minimal, Complete, and Verifiable" - the code works exactly as posted and I accurately describe my problem.
Comment: Thanks for the clarification, I'll keep all of that in mind moving forward!
Answer: I still don't fully understand why NodeJS is installed on my VM but not the base Kali docker image... but in any case I did manage to unblock myself.
First, I was pulling down a NodeJS installation script from nodesource which required rpm -- I found a different script that works without it. However the new script also required that I install gnupg.
Here's my updated Dockerfile:
FROM kalilinux/kali-linux-docker

RUN apt-get update -y && \
    apt-get dist-upgrade -y && \
    apt-get autoremove -y && \
    apt-get clean -y

RUN apt-get -y install curl gnupg

RUN curl --silent --location https://deb.nodesource.com/setup_8.x | bash - \
    && apt-get install nodejs -y

RUN npm i -g npm

ENV NODE_ENV production

WORKDIR /root/app
COPY . .

RUN npm i

EXPOSE 4000
ENTRYPOINT ["npm", "start"]


How to skip the message according to the value in the message header in Kafka Streams?

Question: I want to skip messages that exceed the threshold value in the message headers. We can access the message headers in the streams using the KafkaStream#process method. But, I don't know how to skip messages that exceed the threshold value in the header. I couldn't use the filter because it couldn't access the header in the KStream#filter() method.
I'm trying to write in java using Spring Kafka Stream. Is there a way to do that?
public class MessageHeaderProcessor implements Processor<String, String, String, String> {

    String RETRY_COUNT = "RetryCount";
    Integer threshold;

    public MessageHeaderProcessor(Integer threshold) {
        this.threshold = threshold;
    }

    @Override
    public void init(ProcessorContext context) {
        Processor.super.init(context);
    }

    @SneakyThrows
    @Override
    public void process(Record record) {
        Headers headers = record.headers();
        Iterator retryCountHeader = headers.headers(RETRY_COUNT).iterator();
        if (!retryCountHeader.hasNext()) {
            headers.add(RETRY_COUNT, "1".getBytes());
        } else {
            headers.remove(RETRY_COUNT);
            var retryCount = extractRetryCount(retryCountHeader.next().value());
            var newRetryCount = String.valueOf(retryCount + 1).getBytes();
            headers.add(RETRY_COUNT, newRetryCount);
            if (retryCount > this.threshold) {
              //should skip the message
            }
        }
    }

    private int extractRetryCount(final byte[] bytes) {
        return Integer.parseInt(new String(bytes));
    }

    @Override
    public void close() {
        Processor.super.close();
    }
}

public class EventStreamProcessor {

  @Autowired
  public void streamTopology(StreamsBuilder streamsBuilder) {
      KStream<String, String> inputStream = streamsBuilder.stream("inputTopic");
      inputStream.process(new MessageHeaderProcessorSupplier(10));
      inputStream.to("outputTopic");
  }
}

Answer: Using a Processor you emit downstream record via context.forward(). Thus, you can skip a message by not call forward() inside process(...) method.
public class MessageHeaderProcessor implements Processor<String, String, String, String> {
  // ... omitted

  private ProcessorContext context;

  @Override
  public void init(ProcessorContext<String, String> context) {
    this.context = context;
  }

  @Override
  public void process(Record<String, String> record) {
    if (...) { // below threshold
      context.forward(record);
    }
  }
}


Excel IF + AND + Date range formula

Question: I am looking to create and IF function that does the following.
There is a ton of data with one column containing dates. I want and if functions that labels each row according to the following.
If date falls between 0-30 days of todays date in the past then label "GOOD" (so if todays date is 21/09/2017 then it should be labelled as "GOOD" should it falls between the dates 21/09/2017 and 21/08/2017)
If date falls between 31-60 days of todays date in the past then label "FAIR"
If date falls between 61-90 days of todays date in the past then label "ATTENTION"
If date falls between 91+ days of todays date in the past then label "CLEARANCE"
Hope someone can help.
Many thanks
Answer: Use
=IF(TODAY()-A2<31,"Good",IF(TODAY()-A2<61,"Fair",IF(TODAY()-A2<91,"Attention","Clearance")))

Column D shows the difference between today date and cell date.
Answer: Alternative Answer
Use VLOOKUP to potentially ease your future formula maintenance.  In an unused location, set up a table that has your break point ranges and associated return values.  For this example I used the following:

Technically speaking column G is not required, but it can be easier for some people to read.
Now assuming your dates are in Column A, you can use the following formula in B2 copying down:
=TODAY()-A2

and in C2 use the following look up formula and copy down to get your desired results:
=VLOOKUP(B2,$F$3:$H$6,3,1)

now if you are not keen on generating the extra column for calculate the number of days, you can substitute that first formula into the second to get:
=VLOOKUP(TODAY()-A2,$F$3:$H$6,3,1)

place the above in B2 instead and copy down.
The following is an example of the first approach:

The main advantage to this approach is you can manipulate the lookup table easily changing breakpoints, wording of results etc easily without touching your formula (when done right)
if you have the potential for negative days, instead of returning an error, you could wrap the lookup formula in an IFERROR function to give a custom message or result.
=IFERROR(VLOOKUP(B2,$F$3:$H$6,3,1),"In the Future")

Answer: Assuming your data starts with A2, A3 and so on.. as below

Apply the below formula in B2 and drag down up to A8
=IF(AND(--TEXT(TODAY()-A2,"@@")>=-1,--TEXT(TODAY()-A2,"@")<30),"GOOD",IF(AND(--TEXT(TODAY()-A2,"@@")>=30,--TEXT(TODAY()-A2,"@")<60),"FAIR",IF(AND(--TEXT(TODAY()-A2,"@@")>=60,--TEXT(TODAY()-A2,"@")<90),"ATTENTION",IF(--TEXT(TODAY()-A2,"@@")>90,"CLEARANCE","FUTURE DATES"))))

Excel IF + AND + Date range formula


How to get the return value of future

Question: Implementation is like this below.
Future<Duration?> getCurrentPosition() async {
  final milliseconds = await _platform.getCurrentPosition(playerId);
  if (milliseconds == null) {
    return null;
  }
  return Duration(milliseconds: milliseconds);
}

I want to get the Duration(milliseconds: milliseconds);
So I wrote this code.
Duration t = await widget.audioPlayerHandler.audioPlayer.getCurrentPosition();

My code is above.
But this shows error below, somehow it returns int??
How can I get the Duration that function returns?
lib/main.dart:468:18: Error: A value of type 'int' can't be assigned to a variable of type 'Duration'.
 - 'Duration' is from 'dart:core'.
    Duration t = await widget.audioPlayerHandler.audioPlayer.getCurrentPosition();

Answer: There are two things here
This method returns nullable data and milliseconds can only take int.
Future<Duration?> getCurrentPosition() async {
  final milliseconds = await _platform.getCurrentPosition(playerId);
  if (milliseconds == null) {
    return null;
  }
  return Duration(milliseconds:int.tryParse(milliseconds)??0);
}

and get nullable duration like Duration? t or provide default value.
Duration  t = await widget.audioPlayerHandler.audioPlayer.getCurrentPosition()??Duration.zero;

Comment: Thank you very much, I see the problem is null safety.
Comment: Glad to help you can check more about [null-safety](https://dart.dev/null-safety/understanding-null-safety)

How to get the return value of future


Quais as limitações da licença gratuita do Visual Studio Online?

Question: No site do Visual Studio Online existe uma opção de conta gratuita. Lá diz que essa conta oferece os seguintes benefícios:

5 licenças de usuário básico GRÁTIS
Participantes ilimitados
Assinantes qualificados do MSDN ilimitados
Repositórios de códigos privados e projetos de equipe ilimitados
Acompanhamento de itens de trabalho GRÁTIS para todos os usuários
60 minutos/mês de compilação GRÁTIS
20 mil minutos de usuário virtual/mês de teste de carga GRÁTIS
Análise e monitoramento de aplicativos de VISUALIZAÇÃO

Acontece que isso é vantagem demais. Repositórios privados no GitHub são pagos e essa conta oferece repositórios privados ilimitados de graça. Como parece ter muita vantagem aí fiquei me perguntando sobre as limitações dessa conta.
Quais limitações essa licença oferece? Projetos comerciais podem ser hospedados lá ou só projetos open source ou gratuitos? É como o Visual Studio Community que pode ser usado sem limitações para desenvolvedores que trabalham fora de empresas?
Comment: A lista do que cita como vantagens, me parece limitações da licença, em primeira leitura cheguei a pensar que era uma propaganda do produto. Acredito que se a pergunta for reformulada é dividida em três como é feita no final ficaria melhor.
Answer: É exatamente isto que você descreveu. A Microsoft não pode dar vantagens demais para seus usuários? :)
Qualquer projeto pode ser hospedado lá. Qualquer um pode usar em qualquer circunstância.
Na verdade, não é tão vantajoso assim para alguns tipos de usuários. Se mais do que 5 pessoas podem acessar o projeto você tem que partir para o pago. Mas se sua equipe é pequena é grátis mesmo. Não tem pegadinha. E pode ainda ter usuários extras desde que eles possuam uma conta paga ativa na MSDN (que vem junto com algumas edições do Visual Studio).
Note que é possível acessar work items e algumas outras coisas por usuários fora do projeto sem restrição. Ou seja, todos seus usuários podem ver e incluir tickets, acompanhar a evolução do projeto. Eles só não podem acessar o projeto como um todo e executar qualquer coisa, e provavelmente não é o que você quer mesmo.
Até onde eu sei ainda não está disponível em português (isto pode estar defasado).
Para equipes assim eu duvido que as outras limitações sejam muito problemáticas, e na verdade até são em cima de coisas que o Github, por exemplo, não oferece (agora não mão da Microsoft oferece algo bem semelhante).
Claro que a Microsoft não está sendo boazinha. Ela está dando muita coisa de graça para quem não pode pagar. Mas a concorrência também está dando. Pode não ser a mesma coisa, mas dão outras. Ela precisa mostrar que é barato usar suas tecnologias. E ela ainda ganha bastante com quem precisa mais e pode pagar por isto. Estes usam produtos Microsoft porque precisam, coisas grátis não vão influenciá-los.
A Microsoft também espera que um dia você que usa grátis cresça e seja um usuário pagante.
Agora ele se chama Azure DevOps.
E mais recentemente deve usar o Github Codespaces.
Coloquei no GitHub para referência futura.
Comment: Obrigado @bigown, eu já perguntei do VS Community e agora sobre o VSO porque realmente estou estranhando isso tudo ainda. Sempre trabalhei sozinho e antigamente o jeito era usar o VS Express mesmo porque o preço dos VS completos era meio complicado pra quem trabalha sozinho. Ainda bem que agora a MS está facilitando um pouco mais as coisas.
Comment: A MS está precisando conquistar desenvolvedores porque sem eles fazendo aplicações para suas plataformas ela não pode vender as plataformas. E ela sabe que quem é pequeno, não faz nada muito visível se realmente quer usar os softwares dela, vai usar pagando ou não. Não estou dizendo aqui publicamente que é isto que você deva fazer mas sabemos que muita gente faz.
Comment: Alguem sabe se as Team Room são gratuitas? pelo que vi tem que pagar, ou são gratuitas também?
Comment: http://www.visualstudio.com/pricing/visual-studio-online-pricing-vs os pacotes pagos possuem mais recursos mas até onde eu percebo está incluso nas contas gratuitas para até 5 usuários.


Enumerate the $m^n$ indexes of $m$ points along each axis of an $n$-dimensional space

Question: This is a little programming problem where I need to enumerate, as $i=1,2,3,\ldots,m^n$, the sequences of coordinates
$$\begin{array}{rc}
 i=1\ldots m: & (1,1,...,1,1), (1,1,...,1,2), ..., (1,1,....,1,m)\\
 i=m+1\ldots 2m: & (1,1,...,2,1), (1,1,...,2,2), ..., (1,1,....,2,m)\\
      & \vdots\\
i=m^n-m+1\ldots m^n: & (m,m,...,m,1), (m,m,...,m,2), ..., (m,m,....,m,m)
 \end{array}$$
where each sequence has $n$ numbers.
So I need a programmable (preferably easily/straightforwardly programmable:) function $f:\mathbb N\to\mathbb N^n$ that generates these sequences in the illustrated order as $i=1,\ldots,m^n$.
(Looks like maybe some recursion of the inverse pairing function, https://en.wikipedia.org/wiki/Pairing_function, but I can't see how to do that. And hopefully there's an easier way.)
      E d i t------------------
In case it's of any interest, below's the very short-and-easy C function
implementing @Haran's answer. Note that since this is C, my needed indices actually go from $0$ to $m-1$ rather than the $1$ to $m$ that I illustrated in the question above...
<code>/*===========================================================================
 * Function:    clxcoord ( i, ndim, npts )
 * Purpose:     enumerates coordinates (x_1,x_2,...,x_ndim)
 *              from (0,0,...,0) to (npts-1,npts-1,...,npts-1)
 *              corresponding to i=0...npts^ndim-1
 * --------------------------------------------------------------------------
 * Arguments:   i (I)           int containing 0...npts^ndim-1
 *              ndim (I)        int containing number of dimensions
 *              npts (I)        int containing number of pts along each axis
 * Returns:     (int *)         i^th sequence of coords (x_1,x_2,...,x_ndim)
 *                              or NULL for any error
 * --------------------------------------------------------------------------
 * Notes:     o
 *======================================================================== */
/* --- entry point --- */
int *clxcoord ( int i, int ndim, int npts ) {
  static int xbuff[16][99];
  static int ibuff = 0;
  int    *xcoord = xbuff[ibuff];
  int    idim = 0;
  if ( ++ibuff >= 16 ) ibuff=0;
  for ( idim=0; idim<ndim; idim++ ) {
    xcoord[(ndim-1)-idim] = i%npts;
    i /= npts; }
  return ( xcoord );
  } /* --- end-of-function clxcoord() --- */
</code>
And here's the short snippet testing the function, followed by its output...
<code>  if ( testnum == 3 ) {
    int *xcoord=NULL, *clxcoord();
    int ndim=3, maxcoord=4;
    int icoord=0,i=0, ncoords=(int)(pow((double)maxcoord,(double)ndim)+0.5);
    for ( icoord=0; icoord<ncoords; icoord++ ) {
      xcoord = clxcoord(icoord,ndim,maxcoord);
      printf(" icoord=%04d: (",icoord);
      for ( i=0; i<ndim; i++ )
        printf("%d%s",xcoord[i],(i<ndim-1?",":")\n")); }
    } /* --- end-of-if(testnum==3) --- */
 icoord=0000: (0,0,0)
 icoord=0001: (0,0,1)
 icoord=0002: (0,0,2)
 icoord=0003: (0,0,3)
 icoord=0004: (0,1,0)
 icoord=0005: (0,1,1)
 icoord=0006: (0,1,2)
 icoord=0007: (0,1,3)
 icoord=0008: (0,2,0)
 icoord=0009: (0,2,1)
 icoord=0010: (0,2,2)
 icoord=0011: (0,2,3)
 icoord=0012: (0,3,0)
 icoord=0013: (0,3,1)
 icoord=0014: (0,3,2)
 icoord=0015: (0,3,3)
 icoord=0016: (1,0,0)
 icoord=0017: (1,0,1)
...
 icoord=0047: (2,3,3)
 icoord=0048: (3,0,0)
 icoord=0049: (3,0,1)
 icoord=0050: (3,0,2)
 icoord=0051: (3,0,3)
 icoord=0052: (3,1,0)
 icoord=0053: (3,1,1)
 icoord=0054: (3,1,2)
 icoord=0055: (3,1,3)
 icoord=0056: (3,2,0)
 icoord=0057: (3,2,1)
 icoord=0058: (3,2,2)
 icoord=0059: (3,2,3)
 icoord=0060: (3,3,0)
 icoord=0061: (3,3,1)
 icoord=0062: (3,3,2)
 icoord=0063: (3,3,3)
</code>
Now, ... if I can only get @Haran to do the rest of my work for me :)
Answer: Simply convert $i-1$ to base $m$. Then, take convert all the digits (with leading $0s$) into a sequence of length $n$. Convert digits such as $A$ into $10$, $B$ into $11$ and so on. Finally, add $1$ to all the values in the sequence. This gives you the required.
Comment: Thanks, Haran. Wow, that was easy **>>now that you mention it<<** (P.S. I think you mean "sequence of length $n$").
Comment: @Haran Thanks, again. Note that I edited my question to include the little **C** function implementing your answer. Couldn't have been easier, and works like a charm.
Comment: @JohnForkosh Yes I did, thank you
Comment: @JohnOmielan I am considering the conversion to base $m$. Just wanted to convey that the values that are taken as digits must be converted to their base $10$ counterparts.
Comment: @JohnOmielan Looks okay to me... e.g., the last sequence $(m,m,...,m,m)$ is just the $n$-digit number $mm...mm$ in base $m+1$.
Comment: @Haran I just realized myself you were referring to the printing out of the values, so I deleted my previous comment.


WINS on a Windows 2016 cluster

Question: Our client is still tied to WINS (let's not get into the whys and wherefores, its just the way it is) but we need to update the clusters that WINS is running on from Windows 2008R2 to Windows 2016.  WINS on a 2016 failover cluster is evidently a supported configuration, but we have an odd problem that Microsoft Premier Support has not yet been able to resolve.  While everything looks OK from the cluster perspective, no WINS clients are able to register with WINS on any WINS 2016 cluster.  The cluster nodes themselves are pointed to the WINS resource virtual IP address, but even they don't register.  There are no issues with clients registering with WINS running on a stand-alone Windows 2016 server, just with WINS on a cluster.  Has anyone else seen this?  If so, what did you do to resolve it?
Comment: Hi, can you provide a wireshark ? as I suspect a network error, aka a packet coming from or to something the WINS cluster dont think it would, so probably discarded. Is there any firewall in between the cluster and the client too ? as the packet can die there too
Comment: I'll get a capture when I'm at the office tomorrow.  There are no firewalls between the clients and the WINS server other than the local Windows Firewall.  In our testing we disabled it on both nodes, but still no joy.
Comment: MS Premier Support has just confirmed that there is a bug in Windows 2016/2019 where WINS does not respond on port 137 when running on a cluster.
Comment: Not allowed by Corporate policy to post a Wireshark capture, but we have been able to determine that WINS is not listening on the cluster role IP address on port 137, but IS listening on 137 on the cluster node.
Comment: Thanks for keeping us updated, if they issue you a walkaround or a fix let us know. Thanks you for your time
Comment: Could you answer your question so it doesn't stay open forever?
Answer: Update:  Not a bug at all.  Here is the update from MS.

The cause was actually that cluster service wasn't sending the address down to the netbt driver.
  This is an intentional design change in Server 2016, I'm chasing down whether this is documented anywhere but wanted to get you the solution while I check on that.
  This blog documents the commands used to disable NetBIOS, we will use the same command to enable it.
Speeding Up Failover Tips and Tricks
  In the cluster mmc, Cluster \ Roles \ Select the WINS role
  In the bottom middle of the MMC select resources
  Double click the IP address so you can easily copy the name out,
  Open an admin PowerShell window and set the EnableNetBIOS property on the IP address resource using the name from above,
  Get-ClusterResource "name-of-IP-address-resource" | Set-ClusterParameter EnableNetBIOS 1
Answer: MS Premier Support has just confirmed that there is a bug in Windows 2016/2019 where WINS does not respond on port 137 when running on a cluster. We have requested a bug fix.

WINS on a Windows 2016 cluster