How many $4$-digit positive integers with distinct digits are there in which the sum of the first two digits equals the sum of the last two digits?

Question:
Objective: find the amount of $4$-digit positive integers with distinct digits, in which the sum of the first two digits is equal to the sum of the last two digits.

For the sake of clarity:

these are examples of numbers to be found: $1524,\ 9045,\ 3461$;
these are examples of numbers to avoid: $6161$ (digits are not distinct), $7235$ ($7$+$2\ne 3$+$5$), $0312$ (it is a $3$-digit number).

I would like to solve the exercise by a probabilistic/rigorous manner. But until now I was only able to use reasoning.
One way to see the problem is: "how many ways are there to get a number as a sum of two distinct digits?". Notice that the sum of two distinct digits is at least $1\ (0+1)$ and at maximum $17\ (8+9)$; moreover notice that we need at least two ways to obtain a number because we have two distinct pairs of distinct digits, so we can discard the numbers $1,2,16$ and $17$ because they can be obtained in only one way $(0+1,\ 0+2,\ 7+9$ and $8+9$ respectively).
It's easy to see how many ways there are to get a number a sum of two distinct digits, for example $3=0+3=1+2\ (2 \text{ ways}),\ 4=0+4=1+3\ (2),\ 5=0+5=1+4=2+3\ (3)$ and so on. Notice that if we fix the first pair of digits and their sum is $s$, the remaining ways to get $s$ are $\text{"number of ways to get s"}-1$ because $1$ way was already taken by the first two digits.
It follows that, excluding the way taken by the first pair of digits, the number of ways to get the numbers $3,4,...,15$ as a sum of two distinct digits are: $3\ (1),\ 4\ (1),\ 5\ (2),\ 6\ (2),\ 7\ (3),\ 8\ (3),\ 9\ (4),\ 10\ (3),\ 11\ (3),\ 12\ (2),\ 13\ (2),\ 14\ (1),\ 15\ (1)$.
Let's say we want to find all the numbers of four digits with first digit equal to $2$ and such that the sum of the first two digits equals the sum of the last two digits. The second digit can be $1,3,...,9$ (cannot be $2$ because digits have to be distinct, cannot be $0$ for what we said before about discarded numbers), so the sum of the first two digits can be $3,5,...,11$. Now, in order to get the amount of numbers of four distinct digits knowing that the first digit is $2$ and that the sum of the first two digits equals the sum of the last two digits, we simply need to sum all the possible ways to get the numbers $3,5,...,11$ and multiply the result by $2$ (because if we switch the third digit with the last one we get a different number, for example if we fix the first pair of digits to be $2$ and $1$, there is only one remaining way to get $3$ ($0+3$) but we can costruct two different numbers using $0$ and $3$: $2103$ and $2130$): $1+2+2+3+3+4+3+3=21$, and $21\cdot2=42$.
If the first digit is $1$, the sum of the first two digits can be $3,4,...,10$, so there are $(1+1+2+2+3+3+4+3)\cdot2=19\cdot2=38$ four-digit positive integers with distinct digits, first digit $1$, and such that the sum of the first two digits equals the sum of the last two digits.
If the first digit is $3$, we get $(1+1+2+3+3+4+3+3+2)\cdot2=22\cdot2=44$ four-digit numbers.
If the first digit is $4$, we get $(1+2+2+3+4+3+3+2+2)\cdot2=22\cdot2=44$ four-digit numbers.
If the first digit is $5$, we get $(2+2+3+3+4+3+2+2+1)\cdot2=22\cdot2=44$ four-digit numbers.
If the first digit is $6$, we get $(2+3+3+4+3+3+2+1+1)\cdot2=22\cdot2=44$ four-digit numbers.
If the first digit is $7$, we get $(3+3+4+3+3+2+2+1)\cdot2=21\cdot2=42$ four-digit numbers.
If the first digit is $8$, we get $(3+4+3+3+2+2+1+1)\cdot2=19\cdot2=38$ four-digit numbers.
If the first digit is $9$, we get $(4+3+3+2+2+1+1)\cdot2=16\cdot2=32$ four-digit numbers.
So the total amount seems to be $368$.

The are some problems with this reasoning: it cannot be applied to different exercises, it cannot be written in a probability test because it doesn't use probabilistic manner, it needs a lot of time to be made, and more importantly, we don't know if the result is correct since the reasoning is not rigorous.
So what is the proper way of solving it?
Answer: First ignore the leading zero problem.
If the digits are $a<b<c<d$, the first two digits must be $a,d$ in some order or $b,c$ in  some order, similar for the others. So this $(a,b,c,d)$ gives us $8$ numbers.
How many such tuples $(a,b,c,d)$ are there? For fixed $\delta:=b-a$, we have $10-2\delta\choose 2$ ways to pick two distinct elements $x<y$ of $\{0,1\ldots,9-2\delta\}$ and let $a=x$, $b=x+\delta$, $c=y+\delta$, $d=x+2\delta$. As $\delta$ may run from $1$ to $4$, we get
$$\tag18\cdot\left({8\choose 2}+{6\choose2}+{4\choose 2}+{2\choose 2}\right)=400.$$
Now, we have to get rid of the leading zeroes, which are those where we pick $x=0$ above and also choose to put $a$ in front. That's
$$\tag22\cdot\left({7\choose 1}+{5\choose1}+{3\choose 1}+{1\choose 1}\right)=32.$$
The final answer is $(1)-(2)=$ $$368.$$


Simple Zero of the Riemann Zeta Function

Question: Let $s=σ+it$.
Assume that $ζ(s)-1/(s-1)$ has an analytic continuation to the half plane $σ>0$.
Show that if $s = 1 + it$, with $t≠0$, and $ζ(s) = 0$ then $s$ is at most a simple zero of $ζ$.
I have no idea how to go about this. My initial idea was to differentiate, but I don't know much about the differential of $ζ$. I have also seen that no such $s$ exists in the first place, so Google has not helped much.
If it helps, the first part of the question was to show that $\zeta(s)^{-1}= \sum^{\infty}_{n=1}\mu(n)/n^{s}$ for $σ>1$, which I was able to do.
Comment: did you try mertens' trigonometric inequality ? it might even give a zero of order zero.
Comment: @CaptainDarling That's the first time I've heard of it but I've looked it up and it does solve my problem. Thank you.
Comment: There are nowadays too many proofs that no zeros on the line $\Re(s)=1$ exist, the Mertens identity is maybe the most accessible.
Answer: theorem : if $F(s) = \int_1^\infty x^{-s-1} f(x) dx$ and $|f(x)| = \mathcal{O}(x)$ then the integral converges for $\Re(s) > 1$ and $|F(1+\epsilon+it)| < \frac{C}{\epsilon} $ (if it has a pole  on $\Re(s) = 1$ then it is of order $\le 1$)
this is because $\int_1^{\infty} x^{-s-1} (C x^{\rho}) dx $ is a pole of order $1$ at $s = \rho$. thus $x^{1+it}$ is a pole of order $1$ at $s=1+it$.
application and demonstration of the theorem : because $\frac{1}{\zeta(s)} = \sum \mu_n n^{-s} = s \int_1^\infty M(x) x^{-s-1}dx$ and $M(x) = \sum_{n \le x} \mu_n = \mathcal{O}(x)$ you got that
$$\left|\frac{1}{s \zeta(s)}\right| < \int_1^\infty x x^{-\sigma-1}dx = \frac{1}{\sigma-1}$$
which is a pole of order $1$ (and not more) at $Re(s) = 1$.
the moral of that exercise is that looking at how $f(x)$ is small or not when $x \to \infty$ (and also $x\to 0$ if the integral goes to $0$) tells us how poles of $F(s)$ are distributed and of what order they are.


Duvida depurando um programa

Question: Estava depurando um programa e me surgiu a seguinte dúvida,
tinha arquitetura é 32 Bits Intel e tinha a seguinte instrução MOV EAX, DWORD PTR SS[0X401049], e abaixo dessa instrução tinha o seguinte comando MOV EDX, DWORD PTR SS[0X40104A]. Minha dúvida e que na primeira instrução o registro EAX recebeu 4 byte de dados , e na segunda apenas um byte de dados.
O por que disto sendo que cada endereço de memória em uma arquitetura de 32 bits tem 32 bits.
Não teria que transferir 4 bytes também à segunda instrução?
Comment: Duas coisas. Coloque títulos mais descritivos do seu real problema. Nem comece com dúvida, porque todo mundo que posta um pergunta aqui está com dúvida. É redundante e não descreve o problema. Coloque *tags* que tem a ver com o problema. Não use"C" em todas suas perguntas. Só use esta *tag* quando ela é sobre C. E sempre dê o máximo de detalhes possível. Mostre como você chegou à conclusão postada na pergunta, quem sabe sua afirmação é que está errada.
Comment: Do que consigo ver moveu 2x 4 bytes. DWORD é 4 bytes não consigo ver o problema.
Comment: Falta-te um `;` na linha 42 ... ou porquê C?
Answer: Não necessáriamente precisam ser 4 bytes. Por exemplo, quando estamos trabalhando com diversos tamanhos de tipos podemos usar tanto 4 bytes como 8 bytes como 2 bytes. Não importa qual o tamanho pois a arquitetura do computador corrige essa falha pulando para o próximo valor depois da palavra.
Por exemplo, se você usa um char, ele estará ocupando apenas 256 bits da palavra, o que é referente à 2^8. Nós sabemos que se a arquitetura de um computador é 32bits então cada palavra possuirá 2^32, porém não é um fator determinante. Cada tipo possui um certo tamanho na arquitetura, independente dela.
Dê uma olhada em climits e veja do que estou falando, lá você encontra todas os limites em bits dos tipos em C. Ficará evidente que não é necessário sempre ocupar os 4 bytes de uma palavra!

Duvida depurando um programa


Invalid expression term 'string' in c#

Question: public delegate void FileDelegate(List<string> str);
public event FileDelegate FilesCompleted;

void upload_Status(object sender, EventArgs e)
{
    FileUpload fu = sender as FileUpload;
    if (fu.Status == FileUploadStatus.Complete)
    {
        if (uploading)
            UploadFiles();
        if (FilesCompleted != null)
        {
            if (files.Count == files.Count(q => q.Status == FileUploadStatus.Complete))
                FilesCompleted(files.ToList(string));
        }
    }
}

When I build the program, I got below Error message:

FilesCompleted(files.ToList(string));
  "Invalid expression term 'string'"
Comment: Please take some time to read the help on formatting, and use the preview to make sure that you don't make a post until it actually looks readable. Now, what did you *expect* that use of `string` to do?
Comment: In this case, you are using a `Type` name as variable to pass to a method. string isn't a variable, it's a Type. ToList() method doesn't need any parameters.
Answer: I think if you simply change
FilesCompleted(files.ToList(string));

to
FilesCompleted(files.ToList());

it should compile.
string is a reserved keyword so cannot be used as a variable. Additionally, ToList does not take this as an argument.
If you are trying to cast to string, you can use:
file.Cast<string>().ToList()

Comment: i change my code and compile i got compilation errors ..                            "Delegate 'DC.FileUpload.FileDelegate' has some invalid arguments"  and "Argument 1: cannot convert from 'System.Collections.Generic.List
' to 'System.Collections.Generic.List'"
Comment: public delegate void FileDelegate(List string> str); is wrong.. it should be public delegate void FileDelegate(List str);
Answer: This is wrong :
FilesCompleted(files.ToList(string))
Correction :
FilesCompleted(files.ToList())
Also following is a typo ,
public delegate void FileDelegate(List string> str);

Should be
public delegate void FileDelegate(List<string> str);

Invalid expression term 'string' in c#


JavaFX Enter por TAB

Question: Alguém sabe como alterar o foco com a tecla enter ao invés de tab utilizando JavaFX.
Já pesquisei um monte e não acho nada sobre. Somente em Java.
Por favor alguém já conseguiu fazer?
Answer: Você pode fazer assim:
textfield1.setOnKeyPressed( (keyEvent) -> {
    if(keyEvent.getCode() == KeyCode.ENTER)
        textfield2.requestFocus();
} );

Answer: Oi, pode usar este metodo, tem que passar uma lista de TextField do formulario, com o ordem em que vc deseja q aconteça o focus .
public void setNextFocus(TextField... texFiels) {

    for (TextField txt : texFiels) {
        txt.setOnAction(event -> {
            if (txt.getSkin() instanceof BehaviorSkinBase)
                ((BehaviorSkinBase) txt.getSkin()).getBehavior().traverseNext();

        });
    }
}

Comment: Obrigada mas já havia conseguindo usando a classe Robot
`if (event.getCode() == KeyCode.ENTER) {
                try {
                    Robot avanca = new Robot();
                    avanca.keyPress(KeyEvent.VK_TAB);
                } catch (Exception ex) {
                }
            }`

JavaFX Enter por TAB


Erro com select no mysql

Question: Estou tendo um log de erro que não acontece freqüentemente. Em média 1 vez por mês. O problema é que não estou identificando o erro. Vou posta meu select para vcs poderem ver se tem algo errado.
<code>$result = $mysqli->query("
    SELECT SUM(a.qtd)
    FROM
        produtos_pedidos a,
        pedidos b
    WHERE
        a.id_pedido = b.id
        and (b.status = 0 or b.status = 4 or b.status = 7)
        and a.id_produto = $produto
        and b.pdv = 'n'
");
$row = mysqli_fetch_array($result);
$qtd_penhora = (float) $row['SUM(a.qtd)'];
</code>
O log de erro e esse aqui:
<code>[09-Jan-2017 16:56:55 America/Sao_Paulo] PHP Warning:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /var/www/webroot/ROOT/Funcoes/Movimentacao.php on line 35
</code>
A linha que ocorre e erro e essa aqui:
<code>$row = mysqli_fetch_array($result);
</code>
Tem alguma coisa errada no select?
Comment: Coloque sua consulta em uma variável. E dá um echo `$query`. Pegue o retorno e rode em seu SGBD. Veja se retorna resultados ou não. O que não pode é dar erro. Aparentemente está certo. Não sei como você está fazendo a conexão.
Comment: bom vou testar isso que vc falou.
Answer: Significa que sua query não está sendo executada corretamente.
Coloque estas linhas antes do fetch_array() para descobrir qual o erro:
<code>if (!$result)
   die ($mysqli->error);
</code>
Comment: nesse caso ele vai retornar um erro na tela. e eu desabilitei isso no servidor, como faço para ele retornar o erro no log?
Comment: die funciona como o exit, imprime uma mensagem e finaliza a execução. O PHP não irá considerar um erro, portanto a mensagem será exibida na tela.
Answer: Tente assim, usando o fetch_all:
<code>$mysqli->query("
    SELECT SUM(a.qtd)
    FROM
        produtos_pedidos a,
        pedidos b
    WHERE
        a.id_pedido = b.id
        and (b.status = 0 or b.status = 4 or b.status = 7)
        and a.id_produto = $produto
        and b.pdv = 'n'
");
$row = $mysqli->fetch_all(MYSQLI_ASSOC);
</code>
Comment: o que o fetch_all faz de diferente?
Comment: Então, sempre usei dessa maneira (quando não uso framework como laravel ou codeigniter).
Ele simplesmente traz os dados em forma de array, onde os indexes são os nomes das colunas.

Podendo usar os seguintes parâmetros: **MYSQLI_ASSOC**, **MYSQLI_NUM**, ou **MYSQLI_BOTH**. Onde o **mysqli_assoc** faz o que eu disse, o **mysqli_num** faz com que os indexes sejam números, e o **mysqli_both** traz os dois (números e nomes).

Erro com select no mysql


Case Expressions in Oracle SQL (Pentaho Report Designer)

Question: I need to pull ages of clients and have results broken down into categories (18-21, 22-35, 36-50, etc).
Using Pentaho Report Designer which is Oracle based.
I can pull a count of specific ages, but want the count to reflect the age ranges, not a single age.  Attempting to complete this through a case statement but continually get errors.
Minimal SQL exposure, new to Pentaho/Oracle, new to this website.
--SQL for Age and Count.
SELECT COUNT(*), "CLIENT_TABLE"."AGE"
FROM "CLIENT_TABLE"
GROUP BY "CLIENT_TABLE"."AGE"
ORDER BY "CLIENT_TABLE"."AGE"

--This is my CASE expression.
CASE
    WHEN "CLIENT_TABLE"."AGE" < 18 THEN 'Under 18'
    WHEN "CLIENT_TABLE"."AGE" > 18 AND <= 21 THEN '19 - 21'
    WHEN "CLIENT_TABLE"."AGE" > 21 AND <= 35 THEN '22 - 35'
END AS Age

I have placed the CASE expression in both the SELECT and WHERE clauses, but continually get these two error messages... "FROM keyword not found where expects" & "Missing expression".
Updated code produces error, "not a Group By Expression."
SELECT COUNT(*),
      (CASE
        WHEN "CLIENT_TABLE"."AGE" < 18 THEN 'Under 18'
        WHEN "CLIENT_TABLE"."AGE" <= 21 THEN '18 - 21'
        WHEN "CLIENT_TABLE"."AGE" <= 35 THEN '22 - 35'
        WHEN "CLIENT_TABLE"."AGE" <= 50 THEN '36 - 50'
        WHEN "CLIENT_TABLE"."AGE" <= 64 THEN '51 - 64'
        WHEN "CLIENT_TABLE"."AGE" >= 65 THEN '65+'
       END) AS AgeRange
FROM "CLIENT_TABLE"
GROUP BY (CASE
        WHEN "CLIENT_TABLE"."AGE" < 18 THEN 'Under 18'
        WHEN "CLIENT_TABLE"."AGE" <= 21 THEN '18 - 21'
        WHEN "CLIENT_TABLE"."AGE" <= 35 THEN '22 - 35'
        WHEN "CLIENT_TABLE"."AGE" <= 50 THEN '36 - 50'
        WHEN "CLIENT_TABLE"."AGE" <= 64 THEN '51 - 64'
        WHEN "CLIENT_TABLE"."AGE" >= 65 THEN '65+'
       END)
ORDER BY "CLIENT_TABLE"."AGE"

Comment: `case` **expression** not "statement".  Also, do you have something against 18-year olds?
Comment: update your question and showt the sql code you are really using  ..  not just a part
Comment: If you have no data in one of the ranges, e.g. nobody over 64, do you expect to not see that range at all, or to see a count of zero for that range?
Comment: Ideally, a '0' for any range that returns no data.  Also, I should have an ELSE in the CASE for null values.
Answer: I think you want:
SELECT COUNT(*),
       (CASE WHEN "CLIENT_TABLE"."AGE" < 18 THEN 'Under 18'
             WHEN "CLIENT_TABLE"."AGE" <= 21 THEN '19 - 21'
             WHEN "CLIENT_TABLE"."AGE" <= 35 THEN '22 - 35'
        END) AS Age
FROM "CLIENT_TABLE"
GROUP BY (CASE WHEN "CLIENT_TABLE"."AGE" < 18 THEN 'Under 18'
               WHEN "CLIENT_TABLE"."AGE" <= 21 THEN '19 - 21'
               WHEN "CLIENT_TABLE"."AGE" <= 35 THEN '22 - 35'
           END)
ORDER BY "CLIENT_TABLE"."AGE"

Notes:

In Oracle, you need to repeat the expression in the GROUP BY.
I simplified the logic for the conditions in the case expression.  The conditions are evaluated in order.
In doing so, the 18-year olds are included -- now in the '19 - 21' group.  Including them somewhere seems more right than putting them in the NULL group.
Comment: Does this make sense
Answer: Your 'updated code', based on @Gordon's answer, gets "ORA-00979: not a GROUP BY expression" because you're trying to order by "CLIENT_TABLE"."AGE" - and that column is not in the GROUP BY clause. You probably want:
ORDER BY MIN("CLIENT_TABLE"."AGE")

However, this will only show you ranges which have matching data. If you want to see all ranges, including zero counts, you can generate the ranges as an inline view or CTE and outer join to your real data, e.g.:
WITH "RANGES" ("MIN_AGE", "MAX_AGE", "LABEL") AS (
  SELECT 0, 17, 'Under 18' FROM "DUAL"
  UNION ALL
  SELECT 18, 21, '18 - 21' FROM "DUAL"
  UNION ALL
  SELECT 22, 35, '22 - 35' FROM "DUAL"
  UNION ALL
  SELECT 36, 50, '36 - 50' FROM "DUAL"
  UNION ALL
  SELECT 51, 64, '51 - 64' FROM "DUAL"
  UNION ALL
  SELECT 65, NULL, '65+' FROM "DUAL"
)
SELECT COUNT("CLIENT_TABLE"."AGE"),
       "RANGES"."LABEL" AS AgeRange
FROM "RANGES"
LEFT JOIN "CLIENT_TABLE"
ON "CLIENT_TABLE"."AGE" >= "RANGES"."MIN_AGE"
AND ("RANGES"."MAX_AGE" IS NULL OR "CLIENT_TABLE"."AGE" <= "RANGES"."MAX_AGE")
GROUP BY "RANGES"."MIN_AGE", "RANGES"."LABEL"
ORDER BY "RANGES"."MIN_AGE"

db<>fiddle
You could generate the labels from the min/max age, or even just from a min age (using lead to find the max), and there are other variations you can explore.
(I've assumed you have uppercase and quoted identifiers for a reason, possibly a requirement of your reporting tool - I know some odd things do need them; but from Oracle's point of view the double-quotes aren't needed, and personally I find lowercase or mixed code (maybe keywords uppercase) easier to read. You might want to use table aliases as well.)

I should have an ELSE in the CASE for null values.

COUNT() ignores nulls, so COUNT("CLIENT_TABLE"."AGE") will return zero if those are null. You would need to count any not-null column in the table instead; and would need another dummy row in the RANGES CTE, and modified logic to include the rows with no age set; e.g.:
with ranges (min_age, max_age, label) as (
  select 0, 17, 'Under 18' from dual
  union all
  select 18, 21, '18 - 21' from dual
  union all
  select 22, 35, '22 - 35' from dual
  union all
  select 36, 50, '36 - 50' from dual
  union all
  select 51, 64, '51 - 64' from dual
  union all
  select 65, null, '65+' from dual
  union all
  select null, null, 'Unknown' from dual
)
select count(client_table.id), -- count any not-null column from this table
       ranges.label as agerange
from ranges
left join client_table
on ((ranges.min_age is null and client_table.age is null)
  or client_table.age >= ranges.min_age)
and (ranges.max_age is null or client_table.age <= ranges.max_age)
group by ranges.min_age, ranges.label
order by ranges.min_age

db<>fiddle
Answer: Let's simplify this:
SELECT AGERANGE, COUNT(1) AS CNT FROM
SELECT (CASE
        WHEN "CLIENT_TABLE"."AGE" < 18 THEN 'Under 18'
        WHEN "CLIENT_TABLE"."AGE" <= 21 THEN '18 - 21'
        WHEN "CLIENT_TABLE"."AGE" <= 35 THEN '22 - 35'
        WHEN "CLIENT_TABLE"."AGE" <= 50 THEN '36 - 50'
        WHEN "CLIENT_TABLE"."AGE" <= 64 THEN '51 - 64'
        WHEN "CLIENT_TABLE"."AGE" >= 65 THEN '65+'
       END) AS AgeRange
FROM "CLIENT_TABLE")
GROUP BY AGERANGE
ORDER BY CASE AGERANGE
WHEN 'Under 18' THEN 1
WHEN '18 - 21' THEN 2
WHEN '22 - 35' THEN 3
WHEN '36 - 50' THEN 4
WHEN '51 - 64' THEN 5
WHEN '65+' THEN 6
ELSE 7 END;

Cheers!!
Comment: Thank you Tejash!  This is exactly what I was looking for.  I appreciate the help and guidance.
Comment: If this answer resolved your issue then please accept it so that it will be marked as resolved.


Finding nodes that have not been indexed

Question: On a Drupal 8 website I'm administering the ratio of paged indexed by search_cron stays at a value far below 100%.
New pages are indexed, but it looks as if updated pages are not indexed again. I suspect that there is some problem that keeps nodes from being (re-)indexed. However, I see no error in the log. Search_cron takes very long - several minutes even when indexing only 20 pages per cron run.
There is a page Troubleshooting cron which contains an SQL query (under "Check for problems with modules") to find nodes that haven't been indexed so one can inspect them for bad content. Unfortunately, this works only with Drupal 7, and I couldn't find a similar page for Drupal 8.
How can I find non-indexed nodes on Drupal 8?
Any other idea on how to track down the problem?
Update: I now found a way to log the nodes being indexed by adding a call to the logger to NodeSearch.php. Which admittedly is a hack.
I can now see that Drupal tries to index the same nodes again and again, without success and without error messages. However, I haven't found out the reason yet.
Comment: You can try https://www.drupal.org/project/ultimate_cron it will give you an overview and you'll be able to see if any parts of the cron are causing trouble, then you'll be able to debug more easily.
Answer: The status of node indexing is based on the search_dataset. This table stores content keyword blobs and their associated sid, the primary key for the content's keyword (i.e. the nid). When compared/joined against the node table, it should let you see which nodes aren't index.
From what it sounds like, you've already spotted problem node(s) so it's just a matter of confirmation. Removing the node(s) from being indexed (e.g. hacking
NodeSearch::indexNode()) to confirm it's the problem, then finding out what content in the node is blocking indexer.
Comment: I now found the cause of the problem: There are entries in search_dataset with langcode='und' which are not updated by the indexer, so the indexer is called again and again for these nodes. Deleting these entries fixes the problem.
Answer: We have a tracker to mark nodes indexed in the Drupal database in 'search_api_item' table.
\Drupal\search_api\Plugin\search_api\tracker\Basic

You can investigate the class. It will help to understand how to check if nodes were indexed.
For example, after updating a node this tracker will be called from this method
\Drupal\search_api\Entity\Index::trackItemsInsertedOrUpdated

Be care with 'indexing_order':
'fifo' => $this->t('Index items in the same order in which they were saved'),
It can make problems because we have this code in the tracker class:
    // Update the status of unindexed items only if the item order is LIFO.
    // (Otherwise, an item that's regularly being updated might never get
    // indexed.)
    if ($this->configuration['indexing_order'] === 'fifo') {
      $update->condition('status', self::STATUS_INDEXED);
    }


How to join 2 views block with a views page

Question: Created a content type x. Fields: title, body, serviceareas.
Added 5 nodes.
View1
Created a views page:

Views path: house/%.
Contextual Filter: added nid.
Selected body field to display.

View2
Created a views block:

Added nid. Excluded from display.
Added Title field. Output field as a link > link path: house/[nid]
Results:
When I click a title from the block, I get views page accordingly.
Addition:
View3
I would like to add one more views block which will select serviceareas field for that node.
This block will only display in all the views page.
When I click the title link (step 5), I like to display the body field(it works now already). I also like to display serviceareas field (step 7) to views 1 and views 2.
I am not sure how to join the views 3 to views 1 and views 2? So that I can see serviceareas related to the views page I am on.
Example:
Node/1
Title: title1
Body:  body1
Serviceareas: serviceareas1.
Node/2
Title: title2
Body:  body2
Serviceareas: serviceareas2.
When I click the title 1(views 2), views page(views1) should display body1(works) and on the same page another region, views block(views 3) should display serviceareas1.
When I click the title 2(views 2), views page(views1) should display body2(works) and on the same page another region, views block(views 3) should display serviceareas2.

------------------------<<<

I placed views2 and views3 block in the same region. Views 2 should display all the nodes titles(works). Views3 should display only field from the nid(does not work).
Views3 block: I added one field. Contextual filter: I added nid.
When I click a title link from views2, I get body from views1 page but I do not get the field from views3 block. Below is the view3 block -contextual section.
Answer: If I understand your question correctly, you want to display the result of a View into another View. You can do this by using the contributed module Views Field View:

views_field_view allows you to embed one view into another view and pass arguments along

By using this module you can add an extra field to your View1 and View2, which shows the result of your View3.
===
In your updated question, Views3 has become a separate block. Using a contextual filter you can limit the rows to be only from a specific node (id), the one that is being displayed. The answer on How to associate the current Node ID when running from Block layout? should point you in the right direction, your contextual filter should be similar to the one you used in View1.
Comment: It worked now. I did not clear the cache before. Thank you much.
Comment: Yes, clearing the cache does wonders ;) :)
Comment: Views3 block will be displayed  in a separate region. Will that work?
Comment: I interpreted "I am not sure how to join the views 3 to views 1 and views 2", that you want to show the contents of View3 in the other ones. But, your comment indicates that this is not the case. Is View3 also a block, if so, why can't you apply a contextual filter to View3 (which I assume you already did for View2)?
Comment: Views 3 is  a separate block.  I am confused how to use contextual filter in my case. What field should I select for contextual filter?Some specifics would help?
Comment: @Drupol I've updated the answer.
Comment: It did not help. Please see my updated message.


LSSVM: the estimation function in the case of multiclass classification task

Question: A version extended  from the SVM is the LSSVM (least square support vector machine) lssvm wiki. The y(x) is like in SVM it gives us the sign y(x)= sign(alpha* k(.,.)* y + b) in other words the sign of " alpha* k(.,.)* y + b"=Q which is +1 or -1  I guess I missed somthing does this means that it gives me the sign of the Q (since this Q is number and could be positive or negative is not it if positive it would be affected to class +1 otherwise -1 ? am I correct!  suppose now that we deal with multiclass please see the figure I'd joined I would have for example for an object of the first class [-1  1] see the first columns of the matrix in this case what the " sign(alpha* k(.,.)* y + b)" would give me !! there is no +1 or -1 it is a couple ! How to interpret this please !
Answer: For multiclass problems and SVM, you have to run all possible pairwise comparisons of 2-class problems.  So, for example, during the class 2 to class 4 comparison use +1 for objects in class 2 and -1 for objects in class 4.  (there would be no comparison needed for class 4 vs class 2).
Let $\Omega (\omega=1,2,\ldots,\Omega)$ be the number of classes.   Assume classes $l$ and $m$ are the two classes being compared, the decision function for test object $\bf{x}$ for this comparison is
\begin{equation}
D_{lm}({\bf x})=\sum_{i=1}^n \alpha_i y_i {\bf x}_i^T{\bf x} + b_{lm},
\end{equation}
where $y_i$ and ${\bf x}_i$ are for all the training objects.   Next, run all comparisons of classes $l$ and $m$ $(l<m)$.  Once $D_{lm}$ is obtained for the comparisons for test object $\bf x$, the assignment of test object $\bf x$
to class $l$ is
\begin{equation}
D_{l}({\bf x})=\underset{m \neq l, m=1}{\sum^\Omega} {\rm sign}(D_{lm}({\bf x})).
\end{equation}
For test object $\bf x$, there will be a value of $D_{l}$ for each class, and the greatest one is the class that object $\bf x$ is assigned to, which in functional form looks like
\begin{equation}
D_{l}({\bf x}\rightsquigarrow \omega)=\underset{l=1,2,\ldots,\Omega}{\arg \max}\{ D_l({\bf x}) \}.
\end{equation}
During run-time when comparing class $l$ vs $m$, you just don't use the data for the other classes.  The $D_{lm}(\bf x)$ is like the predicted value of the test object.  A common approach is to assign $\bf x$ to class $l$ if $D_{lm}<0$ and class $m$ if $D_{lm}>0$.  However, you simply only need a $D_{lm}(\bf x)$ for each test object for all possible class comparisons, i.e., $D_{12}(\bf x)$, $D_{13}(\bf x)$, $D_{14}(\bf x)$, $D_{23}(\bf x)$, $D_{24}(\bf x)$, $D_{34}(\bf x)$ -- and you only use training and test objects from true classes $l$ and $m$ when obtaining each $D_{lm}(\bf x)$ - because the trained SVM can only make predictions for the two classes of data it was trained with.  Then, using all the $D_{lm}(\bf x)$ values,  calculate $D_{l}(\bf x)$ for each class $(l=1,2,3,4)$, and the greatest value among $D_{1}(\bf x)$, $D_{2}(\bf x)$ , $D_{3}(\bf x)$  and $D_{4}(\bf x)$ is the predicted class.  These decision functions used for SVMLS are the same as those used in L2SVM.
SVMs offer many advantages over other classifiers, for example, they maximize generalization ability, avoid local maxima, and are robust to outliers.  However, their disadvantages are that they do not extend easily to multiclass problems, can require long training times when quadratic programming is used, and are sensitive to model parameters the same way artificial neural networks are sensitive to the number of hidden layers and number of nodes at each hidden layer.
I actually don't like SVMs, and would never use them first. Rather, I would use linear regression [inputs $y_i=-1,+1$, with $D_{lm}({\bf x})=\beta_0 + \mathbf{x}^T\boldsymbol{\beta}$], kNN, NBC, LDA to first assess linear separability, then SVM and ANNs if the classes were not linear separable.
Comment: thank you for your time and consideration, related to "can require long training times when quadratic programming is used" what causes this! compared to lssvm we have a linear equations set that is way they said that is speedier, why the resolution of linear equation set is more simple ( speedy) than a QP !
Comment: That statement is more for the L2SVMs, which most analysts use, not the LSSVM.  LSSVM are faster since they avoid QP.  However, LSSVMs use equality constraints instead of inequality like L2SVMs, so they are vulnerable to outliers (see Suykens and Vandewalle, Neural Processing Letters, 9(3):293-300; 1999).
Comment: please can you explain more this part "For test object x, there will be a value of Dl for each class, and the greatest one is the class that object xx is assigned to, which in functional form looks like..+ the equation of arg max!" and intuitevely what the Dlm (x) is exactly (an example I see each term but what is exactly the whole of it I dont understand let s take an example suppose I have bought 3 things each of which is about 500 .  1500 is the total price I would like to understand the Dlm (x) is what exactly :)
Comment: The $D_{lm}(\bf x)$ is like the predicted value of the test object.  A common approach is to assign $\bf x$ to class $l$ if $D_{lm}<0$ and class $m$ if $D_{lm}>0$.   (this is exactly what is used in SVM).
Comment: see expanded discussion of $D_{lm}(\bf x)$ after the last equation.
Comment: thank you it is very helpfull :) I am gratefull thank you


Unable to create json using gson

Question: I have to make dynamic hashes, so the class example won't work since the class variables are static. I am sending in a hashmap object to toJson but it isn't working. Any suggestions on what to do?
Comment: you should post your code and be more precise and what do you mean by "isn't working"
Comment: The Gson source code does register an adapter for `Map` type objects (http://google-gson.googlecode.com/svn-history/r513/trunk/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java), you're *sure* that `Gson.toJson(yourHashMap)` doesn't work?
Comment: When my hashmap is only initialized it seems to work, but actually adding values to it gives me Exception in thread "main" java.lang.IllegalArgumentException: condition failed: false
Comment: @tipu: Weird. Are your keys or values types that Gson doesn't understand?
Comment: Crowder, this is my hashmap declaration:

public HashMap word = new HashMap();
Comment: @tipu: So...safe to say that Gson already knows how to handle those. :-) Sorry, no idea!
Answer: If you can't work out the Gson problem, you might look at Crockford's JSON classes for Java, they deal with this exact use case. Not an answer for the Gson issue, though; just an end-run.

Unable to create json using gson


Does Facebook SDK support Swift 2.3/3.0?

Question: Ok, I can't figure out what's the catch here. I follow all the instructions to configure my new project using CocoaPods to use Facebook SDK. Once I open generated project workspace, Xcode offers me to convert some source code in Pods project to Swift 2.3 or Swift 3.0.
I tried twice - with converting to Swift 3.0 and converting to Swift 2.3. Neither works and both give me on average ~120 compilation-time errors.
What's the deal here? I can't find anyone with similar problems. They seem to support Swift 2.3, but it doesn't work actually.
Xcode 8.0, Deployment target 8.0, latest FB sdk available through pods - 4.16.1
Comment: Yes it supports Swift 3. Here is tutorial for [Facebook Login with Swift 3](http://ashishkakkad.com/2015/05/facebook-login-swift-language-ios/)
Answer: Facebook version 0.2.0 has support for Swift 3.0. Make sure you do the following before installing the latest version of Facebook SDK:
1: Get the latest version of Cocapods:
gem install cocoapods
(or if the above fails)
sudo gem install cocoapods

2: Update your local specs repo by running:
pod repo update

3: And then update your pod file and run pod update or pod install
pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'

I think your probably missing step 1.
Comment: Np, glad to help @peetonn
Comment: @RashwanL do you have any idea as to what FBSDK version supports Swift 2.3?
Comment: @Zonily Jame  for swift 2.3 go for FacebookShare version 0.1.1

pod 'FacebookCore', '~> 0.1.1'
pod 'FacebookLogin', '~> 0.1.1'
pod 'FacebookShare', '~> 0.1.1'
Comment: used it, there are bugs. used FBSDK (objective c) and just bridged to swift instead


Pinning evenly fragmented papers

Question:
Draw traces along two identical papers arbitrarily so that each one is divided into $k$ parts of the same size. Place $k$ pins through them with their boundaries coincided. Show that there exists a certain placement of the pins so that when the papers break apart along the traces drawn on them, each fragment has at least one pin through it.

I hope the question is clear enough with this picture.
I thought that since I have no idea how the paper was divided, I'd better consider it as a graph-theory problem instead of a combinatoric geometry problem.
So I construct graph with $2k$ vertices $a_1,\ldots,a_k;b_1,\ldots,b_k$ representing the fragments. Construct sides between fragments which have common area. If this can be proven:

There exists a one-one mapping between $\{a_1,\ldots,a_k\}$ and $\{b_1,\ldots,b_k\}$ so that each mapped pair are connected.

The problem would be solved.
Answer: Consider the bipartite graph $G$ on $k+k$ vertices where each vertex represents a fragment and each edge connects two overlapping fragments (one in each sheet). Since all fragments are the same size, given any subset $S$ of fragments in sheet $1$ with cardinality $n$, at least $n$ fragments in sheet $2$ are needed to completely overlap $S$.
Hall's marriage theorem and the symmetric argument with respect to swapping sheets together guarantee a perfect matching in $G$. For each edge in such a matching you push a pin; after splitting the fragments, all of them are guaranteed to have been pierced by a pin as required.

Pinning evenly fragmented papers


solr is running, but search isn't working: "The Solr server of Solr could not be reached."

Question: I am using Search API Solr (Version: 7.x-1.14), and search was working fine but has stopped working.  I now see "The Solr server of Solr could not be reached" at admin/config/search/search_api.  In the past, when I have gotten this message, it was because solr had stopped running. In this case, solr is running. I have confirmed this with the "bin/solr status" command.
My settings should all be fine, since they have not changed and were working fine before:
<code>Solr Host: localhost
Solr port: 8983
Solr path: /solr/drupal
</code>
What could cause Drupal to now be unable to reach solr when no settings have changed and solr is running?
Answer: I'm not sure what caused the problem in the first place, but it was ultimately resolved by running solr with a different user. In trying to address the original problem (whatever it was), I ran solr using the wrong user.  Once I ran it with my designated "solr" user, Drupal could then reach solr.


Adding a field to a registration form in my forum --how to alter the database?

Question: I'm using YAF (Yetanotherforum), and it's in asp.net 4.0 / C#.  I'm using Visual Studio 2010 and MS SQL Server Management Studio.  My goal is to put a "company name" field underneath the "email" field in the registration form; currently, no 'company name' field exists.
I think I could just go to the register.ascx page and create an extra field.  You could probably just copy the "email" field from tr to /tr and just paste it.  For instance, on the regiser.ascx page, the email field looks like this:

                            <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">
                                <YAF:LocalizedLabel ID="LocalizedLabel6" runat="server" LocalizedTag="EMAIL" />
                                :</asp:Label>

                            <asp:TextBox ID="Email" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email"
                                ErrorMessage="E-mail is required." ToolTip="E-mail is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

So I could just copy and paste the above, and switch all of the verbage from "email" to "company", and that would make the company name field show up on the register page, I'd think.
Assuming that's true, could anybody guide me as to how to handle the database?  Or is impossible without seeing how it's set up?  I'm just so new to databases, that I wouldn't feel comfortable doing anything without some solid advice -- although I already backed it up.
Thanks!
Answer: You really need to create a user profile - any other approach involves a hack to the out-of-the-box membership DB schema. Profiles are only supported for the ASP.NET Web Site template so if you're using the Web Application Project template, then you need to use a custom profile. More info here:
ASP.NET: Web Site versus Web Application Project
Web Profile Builder for Web Application Projects
How to add a Login, Roles and Profile system
Comment: Glad to help - this was tricky to figure out when I did it first because the difference between the project types is not exactly headlined in the documentation...
Comment: Thank you very much for the information, Irish.  I think I know what I have to do now, although it's not an easy task.  But what you said makes sense, and I don't want to have to tinker with the whole source code.  Thanks again for taking the time to respond!


Books and Papers that have treatment of properties like Idempotence and related operations

Question: Please recommend resources to study Idempotence and other similar properties of processes and operations in depth.
I want to know what other properties like Idempotence are there for an operation. I am a computer science student so these kinds of properties of a process intrigue me.
I don't even know which field of mathematics studies these properties. Is it relations theory? abstract algebra? For example, would a good book in abstract algebra have a nice treatment of these kinds of properties?
Edit : I just want a beginner's treatment on these kinds of operation.
Comment: The concept of idempotence is certainly a prominent one in abstract algebra, yes.  But your question seems way too broad to me.  I searched for "idempotent" on MathSciNet (on online compendium and review service for math papers) and got 11483 hits.  Probably you don't really want to read all these papers...so what is it you actually want to know?
Comment: Universal algebra is more likely to discuss different kinds of operations with different properties (permutability, idempotence, etc), but the question is still too broad (a bounty doesn't make it less focused).
Comment: Could you please give an example of what you mean?
Comment: Projection operators in vector spaces are idempotent. The convex hull operation in a real vector space is also idempotent. Except, perhaps at some very high level of abstraction, they are quite different. It might be useful to limit the question by giving some examples of idempotent operations that interest you.
Comment: I think that if you want a good answer, it should be clear what you're asking. It's not very clear what properties _like_ idempotents are. I'm adding a fewlinks, where you can find various properties of binary operations. Some of them are used frequently, some not so common.
http://en.wikipedia.org/wiki/Category:Binary_operations
http://en.wikipedia.org/wiki/Lattice_%28order%29#Properties_of_lattices
http://en.wikipedia.org/wiki/Special_classes_of_semigroups
Answer: The text Introduction to Lattices and Order has material on closure operators which are idempotent and there are also some sections that deal with theoretical computer science. Here is a link to Amazon's page: http://www.amazon.com/gp/reader/0521784514/ref=sib_dp_pt#reader-link
Answer: I work on elementary particle theory. Calculations using "Feynman diagrams" are done using "propagators" (which are Green's functions for wave functions, i.e. solutions to the Klein-Gordon or Schroedinger or Dirac or Pauli-Dirac equation) and "vertices" (which give the amplitude for particles interacting so as to replace one group of particles with another group). An example of this sort of thing is an up quark emitting a W+ particle and becoming a down quark. One models the movement of the W+ particle with the propagator appropriate to a spin-1 massive object. The up and down quarks get modeled with spin-1/2 propagators, while the interaction gets modeled by the weak force. In short, I'd like to see this redone completely in terms of the propagators. The idea is that propagators should carry the information sufficient to describe the interaction vertices.
So to me, the propagators are very important and should be studied at the most basic level. What can be a propagator? Since a propagator describes a particles that is moving through space-time without change to the nature of the particle (that is, we use the label "particle" to describe activity that tends to preserve itself in time), there is a requirement that the propagator be idempotent. As Green's functions, you have:
$$G(x,x'') = \int_{-\infty}^{+\infty}G(x,x')G(x',x'')\;dx'.$$
Eliminating the dependency on space and time gives you something that describes the particle's nature (i.e. electric charge, spin, weak hypercharge, weak isospin ..). The above becomes a matrix equation:
$$G = G^2$$
Solving the above should give attributes of the elementary particles, for example see http://brannenworks.com/Gravity/qioumm_view.pdf
For this reason, you might find my (incomplete) book on Clifford algebra and elementary particles of interest as it concentrates on understanding the idempotents of the Clifford algebra: http://www.brannenworks.com/dmaa.pdf Uh, Clifford algebra is the math term for the generalization of what the physicists call the "Dirac gamma matrices". These are used to define the wave functions for spin-1/2 particles such as the electron and positron.
If you google Clifford algebra you'll find a lot of applications in computer science, so this might be of interest.
Answer: Trying to guess what you mean.
A definition of idempotence would be, for $f$ a function on a typical element $x$,
$$f( f(x) ) = f(x)$$
This is an example of a functional equation. So you might be interested in a book or introductory article about functional equations.
There is no limit to the number of properties you can imagine for a function based on a functional equation. Classical algebraic notions such as commutativity, distributivity, associativity can be expressed this way (see below).
Idempotence is just one of the most basic and most meaningful, related to the geometric notion of projection. Even this is too broad to find the kind of elementary treatment you want.
In general a functional equation would be any kind of equality that you can write between a function, its successive iterations and its values. You can complicate matters by introducing derivatives, auxiliary functions, several variables, going into inequations, etc.
As others have already remarked, this is a broad subject touching on very different parts of mathematics. But I would guess you are more interested on discrete objects such as integers or trees than on continuous objects.
You can at first have a look at traditional web sources such as Wikipedia, when you will find a beginning of classification. You can also look at most books or articles about solving problems at Mathematics Olympiad where it is common to have functional equations (on the sets of integers but not only).
Functional equations are used in Computer Science in different contexts such as dynamic programming, automata theory, analysis of algorithms, among others. You may have also heard about Functional Programming. In some of them basic properties of functions are used in evaluating programs and optimizations. For instance, if you can declare that a function is associative, the interpreter or compiler can choose the order in which it will evaluates the arguments since it will not change the result.
Comment: Yes that is the direction that I want to go. Can you recommend other books/articles on "functional equations"


checkdnsrr does not work for .edu email addresses?

Question: The following is the function I am using to validate a users email address when we add him (or her) to our system:
private function validate_email($email){
    list($userName, $mailDomain) = split("@", $email);
    if (!checkdnsrr($mailDomain, "MX")) { //.edu does not work?
        return false;
    }
    return true;
}

For some reason this function always seems to return false when I enter a .edu address that I know is valid.
How do I fix the function so it both validates and returns true for all email types?
Comment: My 2 cents: Get rid of validation altogether. Check that it conforms to `*@*` and throw everything else out the window. It's useless anyway - if you need to be sure a particular E-Mail address exists, you need to send a confirmation link anyway.
Comment: @Pekka -- we send a confirmation link, but we dont know if they received it or not, if we assume that the address is always valid, we cannot know if they got the confirmation...
Comment: getting the confirmation back is still the only way to go really. An E-Mail could go lost even if the address *is* valid due to overzealous spam filters. I maintain: Any validation beyond `*@*` is essentially pointless. Look at the new `.xyz` TLDs coming up... IDNs... Eventually, IDN TLDs....
Comment: @Pekka basically this is a employment candidate system where they would login and get the test for them to take. If we do not know that they did not get the email, we assume they did and they fail the test -- I **do not** want that to happen.
Comment: checkdnsrr just uses the system resolver. You can check that yourself by doing `nslookup -type=mx mit.edu` or `host -t mx mit.edu` from the command line to see if your dns setup is working.
Comment: @Neal I don't completely understand your situation, but to be clear: I'm just advocating not trusting the validation, but absolutely send a confirmation E-Mail!
Answer: An MX record is actually not mandatory to receive email. If there is no MX record, standards-compliant MTAs will fall back to an A record if one is available. It's possible that some educational institutions are relying on this behavior; it's certainly not considered best practice, and it will lead to some mail delivery problems for them, but it will at least usually work.
Comment: The solution is implicit: Either remove the existing `checkdnsrr` check, or add a check for `A` records.
Answer: If a hostname does not have an MX record, but does have an A (or AAAA) record, conforming mail transport agents will attempt delivery directly to the address given in the A record (RFC 5321 section 5):

"If an empty list of MXs is returned,
the address is treated as if it was associated with an implicit MX
RR, with a preference of 0, pointing to that host."

Thus, the absence of an MX record does not necessarily indicate that mail cannot be delivered to that host.

Addendum: Much as Pekka says in the comments, the only reliable way to tell if an e-mail address is valid is to send mail to it and see if it gets delivered.  If you're worried about candidates trying to cheat by claiming that they didn't get the message, you could do something like this:

Ask for the candidate's e-mail address and send a confirmation message to it.  Include a confirmation link (and/or a confirmation code the candidate can enter in a form) in the message.
Once the candidate has confirmed that they've received the message by clicking the link, send them the actual test.
Comment: RE: your addendum -- a candidate still could claim that they did not get the test and then we would send out a new link, how would that work?
Comment: If they got the confirmation e-mail, you know the e-mail address they provided is correct and working.  That's as much confirmation as you can have.  What you want to do, if they still claim that they got the confirmation message but somehow didn't get the test, is then up to you.
Answer: Maybe your edu provider does not let anyone see their dns records.
Comment: That's highly unlikely, especially for a domain that's being used for email.


Colorbox - Only display some of the images in a gallery

Question: I've got colorbox set up and working great, but I'd just like to do one little thing that I can't figure out.  I want to have a colorbox gallery of, for example, a dozen photos, but select three to display on the page.  Once you click one of the three photos on the page, it opens up the colorbox, which allows you to click through all 12 photos.  Is this possible with Colorbox and Drupal 7?
EDIT: I'd like this to be a fix that I can use on a lot of different pages with varying numbers of photos.  Sorry for the ambiguity.
Answer: Create a custom template page.
Display the first 3 images - wrap the remaining images in a div that you hide, with css eg:  display: none; or add a hide class to them - attach the gallery_class class to them all so you can call them using
<code>$(".gallery_class").colorbox({rel:'gallery_class'});
</code>
Comment: That makes sense, but I want a fix that will work on a bunch of pages.  Sorry I didn't make that clear.  I have about 50 pages that each have a dozen photos.  How can I make this work for all those pages?
Comment: Hi again. This will work on a bunch of pages. If you use the file field with unlimited values you can tell it to simply show the first 3 as they have been sorted in the node edit page. So you create a template for that content type - hard code the 3 images into it with file checks etc (incase you only have 2 or even 1) - do a loop and output the rest of the images with a hidden class and gallery class and then call the colorbox slideshow ...


Entity Reference get nodes based on tags

Question: Let me try my best to make myself understood.
I have a node type Exhibition where I want to display related nodes of type Article, and these related nodes are tagged with taxonomy tags. On the Exhibition node I want a field where I can write one or more words, and related Articles tagged with these words should be displayed.
I want to use the Entity Reference module since this is already in use elsewhere, and I want to limit the number of modules in use. (I know of the Similar By Terms module).
Does anyone know if this is possible?
Answer: It can't be done with Entity Reference out of the box, your only option is to install another module or write some custom code (you would need to create a custom widget that searched additional fields on the entity if you went down the custom code route).
One possibility, which seems to be in keeping with your approach, is the Entity Reference View Widget module.  This module allows you to search on any field.  There is a little bit of additional setup since you have to create a view containing your Article nodes, but it means that you can specify your taxonomy as a field that can be filtered.
Comment: I would be careful with that module. It never became really stable and is an architectural dead end. (I wrote it)
Comment: Ah, I haven't actually tried the module but saw it on a recent Lullabot post.  You know best though, being the module author and all!!
Comment: I guess Similar By Terms module is the easiest way to go then since another module is needed anyway. Thank you both for answering.
Comment: I found this http://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3 - Works great.
Comment: @BojanZivanovic Best comment I've seen in a while. Still have the same opinion?
Comment: The 2.x version is very stable, since it uses a dialog instead of embedding the view.


summarize the results of multiple regressions done on different subsamples of the same dataset

Question: I want to estimate how robust is the result of a simple correlation test (Y~bX+c) to changes in the number and identity of the observations selected to perform it. For that, I have repeated such correlation many times, each time randomly selecting a different number of observations. E.G. My original data set has 20 observations and I have repeated the same correlation for 100 series of 10 to 20 observations.
Now, I would like to summarize the correlation results in a way that it shows the sensitivity of the parameters to changes in the number and identity of the observations included in the correlation. Any hint?
I have thought of two plots:
One would be a scatter plot of the obtained p value against the number of observations in each iteration
Another would be a scatter plot of the obtained p values against the mean X value of the observations (thus representing observations identity)
Would this be valid/enough?
Thanks in advance
Comment: Graphing data is never _in_valid. You could also plot sample size versus sample mean and label the points 1-20, then plot correlation versus sample label in decreasing order (so if sample 19 has the highest correlation, it is furthest to the left). The real question is: **what comparison do you want to emphasize?** All graphs are comparisons. [Maybe a graph is overkill and a table would suffice](http://andrewgelman.com/2011/12/22/tables-as-graphs-the-ramanujan-principle/). Easy three columns: sample size, sample mean, sample correlation
Comment: p-values *really* wouldn't be my choice for a way to summarize or compare regressions; they're random quantities that don't convey much information of interest. If you're interested in impact on correlations, *plot corrrelations*.
Comment: [why not both?](https://www.youtube.com/watch?v=OawrlVoQqSs)
Comment: I thought of using both, actually. Do you think it would be valid?
Answer: From the comments:

Graphing data is never invalid. You could also plot sample size versus sample mean and label the points 1-20, then plot correlation versus sample label in decreasing order (so if sample 19 has the highest correlation, it is furthest to the left). The real question is: what comparison do you want to emphasize? All graphs are comparisons. Maybe a graph is overkill and a table would suffice. Easy three columns: sample size, sample mean, sample correlation


Set select list option value

Question: I'm trying to set value of select list programmatically with hook form alter
I have select list with options:
<code>$options = array(125 => 'USA');
</code>
and setting value like this
<code>$form['field_news_rubrique']['und']['#options'] = $options
</code>
But this don't work.
if i change options like this
<code>$options = array(0 => 'USA');
</code>
it's working
if i have multiple value in options like this :
<code>$options = array(124=> 'EN', 125 => 'USA');
</code>
it's working too
Comment: I'm get it working by disable taxonomy term permission module
Answer: Do you want to set the value before submission or after?
Before submission:
Use $form and set the default value for the select list using the key.
After submission:
Use $form_state['values']
Comment: I want to set value before submission , but i get it working thank's for your post

Set select list option value


Revisão de código da classe CPF em Java

Question: Podem revisar o código da minha classe CPF?
Um ponto de crítica é o uso de regex que pode ser desnecessário. Mas a meu ver torna o código mais curto.
Outro ponto é a adoção de uma classe para isso, poderiam ser cálculos feitos isoladamente. Mas acho que encapsulado em uma classe fica melhor.
É só uma classe teórica, ela foi testada e funciona, mas não chegou a ser usada em produção. Aceita CPF's válidos ou sem dígito verificador, e gera CPF's aleatórios.
Cpf.java
import java.util.concurrent.ThreadLocalRandom;

public class Cpf {

    public static final int NRO_DIGITOS_SEM_DV = 9;
    public static final int NRO_DIGITOS_VERIFICADORES = 2;
    public static final int NRO_DIGITOS_COM_DV = NRO_DIGITOS_SEM_DV + NRO_DIGITOS_VERIFICADORES;

    private final String cpf;

    /** Recebe uma cadeia completa de dígitos de CPF, sem formatação */
    public Cpf(String cpf) {
        if (cpf == null) {
            throw new IllegalArgumentException("CPF não pode ser nulo.");
        } else if (ehCadeiaDeNoveDigitosNaoIniciadaEmZero(cpf)) {
            this.cpf = cpf + moduloOnze(cpf);
        } else if (ehCadeiaDeOnzeDigitos(cpf) && isValido(cpf)) {
            this.cpf = cpf;
        } else {
            throw new IllegalArgumentException("Número de CPF inválido: " + cpf);
        }
    }

    private static boolean ehCadeiaDeNoveDigitosNaoIniciadaEmZero(String cadeia) {
        return cadeia != null && cadeia.matches("[1-9]\\d{" + (NRO_DIGITOS_SEM_DV - 1) + "}");
    }

    private static boolean ehCadeiaDeOnzeDigitos(String cadeia) {
        return cadeia != null && cadeia.matches("[1-9]\\d{" + (NRO_DIGITOS_COM_DV - 1) + "}");
    }

    private static boolean isValido(String cpf) {
        return ehCadeiaDeOnzeDigitos(cpf)
                && cpf.substring(NRO_DIGITOS_SEM_DV, NRO_DIGITOS_COM_DV).
                        equals(moduloOnze(cpf.substring(0, NRO_DIGITOS_SEM_DV)));
    }

    /** Recebe uma cadeia de 9 dígitos decimais e retorna o módulo-11 dessa cadeia */
    private static String moduloOnze(String digitos) {
        if (false == ehCadeiaDeNoveDigitosNaoIniciadaEmZero(digitos)) {
            throw new IllegalArgumentException("Dígitos de CPF inválidos: " + digitos);
        }

        int dv1 = calcularDigitoVerificador(digitos);
        int dv2 = calcularDigitoVerificador(digitos + dv1);

        return String.valueOf(dv1) + String.valueOf(dv2);
    }

    private static int calcularDigitoVerificador(String digitos) {
        int peso = digitos.length() + 1;
        int dv = 0;
        for (int i = 0; i < digitos.length(); i++) {
            dv += (digitos.charAt(i) - '0') * peso;
            peso--;
        }

        dv = 11 - (dv % 11);

        return dv > 9 ? 0 : dv;
    }

    /** Exibe o CPF em formato 999.999.999-99 */
    public String formatado() {
        return cpf.substring(0, 3) + "." +
                cpf.substring(3, 6) + "." +
                cpf.substring(6, NRO_DIGITOS_SEM_DV) + "-" +
                cpf.substring(NRO_DIGITOS_SEM_DV, NRO_DIGITOS_COM_DV);
    }

    /** Exibe o CPF em formato 99999999999 (onze dígitos decimais) */
    @Override
    public String toString() {
        return cpf;
    }

    public String digitosVerificadores() {
        return cpf.substring(NRO_DIGITOS_SEM_DV);
    }

    public static Cpf criarAleatorio() {
        String noveDigitosAleatorios =
                String.valueOf(ThreadLocalRandom.current().nextInt(100_000_000, 999_999_999 + 1));
        return new Cpf(noveDigitosAleatorios + moduloOnze(noveDigitosAleatorios));
    }

    public static void main(String [] args) {
        Cpf cpf = new Cpf("526265690"); // Deve ter DV's 03
        System.out.println(cpf.formatado());
        System.out.println(cpf.digitosVerificadores());
    }
}

Comment: @Piovezan Sobre a validação, é o que eu disse na resposta: "*Você quer que a classe represente um CPF, ou só quer um validador/calculador de dígitos verificadores? Se fosse o segundo caso, faria mais sentido uma classe utilitária com métodos públicos e estáticos, que retornam apenas true/false*". Mas se a ideia é representar um CPF válido, aí faria sentido lançar exceção, pois assim ela não deixaria criar instâncias inválidas (mas se puder ter uma instância com número inválido, aí não lançaria exceção, etc). Enfim, é o que já foi dito, sem requisitos reais, só nos resta especular :-)
Comment: Esse código é curto? Então tá... :) O que eu já vi de problem a é a inconsistência do `is` e `eh`, eu usaria `é` :P Eu tenho um treco quando vejo um `false ==`. Mas você não usou RegEx pro cálculo que era o que estava sendo discutido no chat. Usou pra validação, aí até faz algum sentido, ainda que eu não usaria (eu faria em uma linha mais rápido e na minha opinião mais legível), mas não está estritamente errado usar. Fica a questão se precisa fazer essa validação isolada, se não precisa, aí está usando algo desnecessário. Huum, acabei de ver, tá tudo privado, então acho que é exagerado.
Comment: Tá com cara de modularização sem ganho algum. A função principal eu faço em 4 linhas :P, desde que não coloque mais nada nela como a validação. Por que a formatação não fez com RegEx? :P
Comment: A função principal que você fala é o cálculo do dígito né? Esse eu peguei da internet, dei uma guaribada só, não sei como ficaria mais curto. Mostra aí :P não entendi o problema que ocorre em ser tudo privado.
Comment: É que acontece aquilo que estávamos falando no chat, você valida e depois cria o dígito, dá pra fazer ao mesmo tempo. De início eu achei que era um método pra ser usado pelo consumidor da classe.
Comment: Talvez eu devesse ter me perguntado "o que é realmente necessário de responsabilidade para a classe?" antes de fazer, isso poderia ter mudado a cara dela, o que você acha? Eu fiz no achômetro, não no requisito real. Nunca trabalhei em algo que eu precisasse fazer uma classe para tratar CPF :P
Comment: _"Tá com cara de modularização sem ganho algum"_ Eu concordo, pelo que entendi o erro foi querer modularizar um candidato a entidade que não tem comportamento (responsabilidade) algum e pode muito bem ser um campo de uma outra entidade. Vê-se então que só porque um algoritmo é associado a um dado não quer dizer que eles devam estar juntos sempre, seria isso? Onde deveria ser validado o CPF então, no modelo de negócio? Em uma classe validadora? Ou dentro da entidade que o contém?
Comment: O problema é só ter esse monte de função, não vi motivo, parece ser só para parecer organizado, forçar o SRP, mas a responsabilidade é simples demais, por isso eu disse que dá pra fazer em 4 linhas. O problema não é o tipo, é a implementação.
Comment: Estou achando realmente que há um erro na modelagem, que CPF não deveria ser uma entidade. Foi nesse sentido que entendi a "modularização sem ganho algum", apesar de ter entendido agora que você falou dos métodos. Eu falo responsabilidade do sentido de interface pública, não da razão para mudar do SRP. Eu não vou pedir código de contra-exemplo porque dá trabalho escrever :P acho que consigo visualizar como ficaria um código mais curto, mas se quiser dar uma descrição para ajudar agradeço.
Comment: Ele pode ser sim, em muitos casos é vantajoso ser (ainda que em Java sempre será ruim :D) Essa entidade só está complexa demais, só precisa ser mais simples. Na verdade não lembro mais de todos detalhes e esfriei nisso, pode ser que a interface esteja boa, o problema é a implementação,
Comment: A interface (coisas que o objeto deve saber e fazer, "know" e "do", `getStuff()` e `doStuff()`) pelo exemplo é só exibir o CPF formatado (como o @hkotsubo fala na resposta dele) e gerar um número aleatório. Não sei se é uma interface muito significativa ou coerente.
Comment: Também tem o problema (eu não percebi, um colega apontou) que o construtor dispara exceção se o CPF é inválido, ou seja, está tratando fluxo de execução com exceções. Então como um CPF inválido não é uma situação excepcional (o usuário pode inserir facilmente um inválido), o mais certo seria ter algum tipo de validador.
Comment: @hkotsubo Tem razão, desculpe, não tinha me atentado para essa parte.
Answer: Como é uma classe teórica (sem um requisito real), vou tomar como premissa que a responsabilidade dela é representar um CPF (e não somente validar ou formatar, pois aí algumas coisas poderiam ser mudadas, conforme discutido mais abaixo). Ou seja, eu passo uma String contendo um possível número de CPF e ela só cria a instância se esse número for válido (sendo que "válido" considera apenas se os dígitos verificadores estão corretos, caso existam - se não existir, a classe calcula automaticamente).
Se a ideia é somente essa, não precisa de regex, pois ela só está servindo para verificar se a String tem uma determinada quantidade de dígitos. Mas você pode fazer essa verificação durante o cálculo dos dígitos verificadores, economizando assim um loop desnecessário (a regex terá que varrer toda a String para verificar que ela só tem dígitos). Na verdade dá para economizar 2 loops (o da regex e um dos que calculam os dígitos verificadores), pois ambos os dígitos verificadores podem ser calculados no mesmo loop. Uma alternativa para o construtor e os métodos auxiliares usados por ele seria:
public Cpf(String cpf) {
    if (cpf == null) {
        throw new IllegalArgumentException("CPF não pode ser nulo.");
    } else if (cpf.length() != NRO_DIGITOS_COM_DV && cpf.length() != NRO_DIGITOS_SEM_DV) {
        throw new IllegalArgumentException("Número de CPF deve ter " + NRO_DIGITOS_SEM_DV + " ou " + NRO_DIGITOS_COM_DV + " dígitos");
    }
    this.cpf = verificaDigitos(cpf);
}

private static String verificaDigitos(String cpf) { // este método só é chamado depois que eu já sei que o tamanho da string é 9 ou 11
    int total1 = 0, total2 = 0;
    int multiplicador = 10;
    for (int i = 0; i < NRO_DIGITOS_SEM_DV; i++) { // percorre somente os 9 primeiros dígitos
        int c = cpf.charAt(i) - 48;
        if (c < 0 || c > 9) { // não é dígito de 0 a 9, inválido
            throw new IllegalArgumentException("CPF deve ter somente dígitos: caractere inválido na posição " + i);
        }
        total1 += multiplicador * c;
        total2 += (multiplicador + 1) * c;
        multiplicador--;
    }
    int dv1 = dv(total1, 1, cpf);
    int dv2 = dv(total2 + dv1 * 2, 2, cpf);

    if (cpf.length() == NRO_DIGITOS_SEM_DV) { // tem 9 dígitos, concatenar os dígitos verificadores
        return cpf + dv1 + dv2;
    }
    return cpf; // se chegou aqui é porque tem 11 dígitos e os dígitos verificadores são válidos, então retorna sem modificações
}

// recebe o total, o número do dígito verificador (i pode ser 1 ou 2) e a string do CPF
// se o tamanho da string é 11, verifica se o dígito verificador calculado é o mesmo que está na string
private static int dv(int total, int i, String cpf) {
    int resto = total % 11;
    int dv = resto < 2 ? 0 : 11 - resto;
    if (cpf.length() == NRO_DIGITOS_COM_DV && dv != cpf.charAt(NRO_DIGITOS_COM_DV - (3 - i)) - 48)
        throw new IllegalArgumentException((i == 1 ? "Primeiro" : "Segundo") + " dígito verificador não bate");

    return dv;
}

No método verificaDigitos eu faço apenas um loop pelos primeiros 9 dígitos, calculando as somatórias.
Um detalhe/curiosidade é que dentro do loop eu também poderia fazer assim:
if (i != 0) {
    total2 += (multiplicador + 1) * c;
}

Pode parecer estranho pular a multiplicação do primeiro dígito por 11 em total2, mas no final vamos calcular o resto da divisão por 11 e portanto o primeiro termo é redundante: se eu tiver um número n e fizer n % 11, o resultado será o mesmo que (n + (11 * x)) % 11 (para qualquer x inteiro). Somar qualquer múltiplo de 11 não mudará o resto da divisão por 11, então somar "11 vezes o primeiro dígito" em total2 não faz diferença (se bem que nesse caso, talvez esse if não passe de micro-otimização).
Depois de terminado o loop, eu vejo se o primeiro dígito verificador é igual ao do CPF informado, mas só se o tamanho da String for 11 (se for 9, não tem o que verificar). Se for válido, eu prossigo para o segundo dígito. Repare que no if do método dv eu nem preciso verificar se o décimo e décimo primeiro caracteres são dígitos de 0 a 9, pois se não forem, o valor com certeza não baterá com os dígitos verificadores.
Por fim, eu verifico se devo concatenar os dígitos no final da String (o que só deve ser feito se o tamanho dela for 9).
Com isso, o método que cria um CPF aleatório pode simplesmente trabalhar com strings de 9 dígitos (já que os dígitos verificadores serão calculados e concatenados dentro do próprio construtor):
public static Cpf criarAleatorio() {
    String noveDigitosAleatorios = String.valueOf(ThreadLocalRandom.current().nextInt(100_000_000, 999_999_999 + 1));
    return new Cpf(noveDigitosAleatorios);
}

Como nesse caso específico eu já sei que a String terá apenas dígitos, talvez valesse a pena refatorar a classe para separar a validação do cálculo dos dígitos verificadores, pois neste caso não preciso verificar que todos os caracteres são dígitos - fica como "exercício para o leitor" :-).

Quanto à adoção de uma classe para isso, depende do objetivo. Você quer que a classe represente um CPF, ou só quer um validador/calculador de dígitos verificadores? Se fosse o segundo caso, faria mais sentido uma classe utilitária com métodos públicos e estáticos, que retornam apenas true/false (CPF válido ou inválido), ou se quiser ser mais específico, retornam códigos de erro que indiquem qual foi o problema (não tem dígitos, quantidade errada, dígitos verificadores não batem, etc). Outra alternativa seria encapsular esse código de erro em uma classe ou enum específico (CpfValidationResult?) caso valha a pena criar tal abstração (como é uma classe teórica sem requisito real, fica difícil opinar sobre o que é mais adequado).
Porém, se a ideia é que a classe represente um CPF, então eu acho que tudo bem lançar a exceção caso o CPF seja inválido (já que não parece fazer sentido criar uma instância se o número não é válido, pois aí ela deixaria de representar um CPF de fato - mas novamente, sem requisitos reais, não dá pra saber, vai que tem um requisito que permite ter "CPF's" com números inválidos, sei lá). Mas se fosse um validador, eu usaria uma das opções do parágrafo anterior, em vez de lançar uma exceção.
Por fim, o código nem ficou tão mais curto que o original, mas você não deve usar isso como critério principal para decidir qual implementação usar. Código menor não é necessariamente "melhor", tem que usar o que faz mais sentido em cada caso (e entendo que nesse caso não precisava usar regex, por exemplo). Sem contar que, por mais que eu goste de regex, usá-la nem sempre é a melhor solução, além de gerar um overhead muitas vezes desnecessário.
Uma coisa que dá para melhorar são os nomes dos métodos verificaDigitos e dv, mas estou sem criatividade no momento (talvez calculaEValidaDigitosVerificadores e calculaDigitoVerificador, respectivamente? Não sei).

Se quiser continuar com a regex (e não mudar tanto o restante)
Se quiser muito continuar usando regex, uma pequena melhoria seria criá-las separadamente, já que cada chamada de String::matches compila a regex novamente. Mas como elas serão usadas várias vezes (toda vez que criar uma nova instância) e não mudam, então uma alternativa seria compilá-las apenas uma vez:
private static final Pattern REGEX_9_DIGITOS = Pattern.compile("^\\d{9}$");
private static final Pattern REGEX_11_DIGITOS = Pattern.compile("^\\d{11}$");

private static boolean ehCadeiaDeNoveDigitosNaoIniciadaEmZero(String cadeia) {
    return REGEX_9_DIGITOS.matcher(cadeia).matches();
}

private static boolean ehCadeiaDeOnzeDigitos(String cadeia) {
    return REGEX_11_DIGITOS.matcher(cadeia).matches();
}

Ou:
private static final Matcher REGEX_9_DIGITOS = Pattern.compile("^\\d{9}$").matcher("");
private static final Matcher REGEX_11_DIGITOS = Pattern.compile("^\\d{11}$").matcher("");

private static boolean ehCadeiaDeNoveDigitosNaoIniciadaEmZero(String cadeia) {
    return REGEX_9_DIGITOS.reset(cadeia).matches();
}

private static boolean ehCadeiaDeOnzeDigitos(String cadeia) {
    return REGEX_11_DIGITOS.reset(cadeia).matches();
}

A diferença é que a primeira opção com Pattern é thread-safe, enquanto a segunda (com Matcher) não. Sem saber qual o cenário em que será usada a classe, não dá para sugerir qual o "melhor".
Detalhe que existem CPF's que começam com zero, e não considerar esses casos pode dar problemas no mundo real. Por isso mudei suas regex, que não deixavam o CPF começar com zero. Agora elas só verificam se tem 9 ou 11 dígitos, sejam eles quais forem.
Os métodos ehCadeiaEtc não precisam verificar se a String é null, pois você só chama esses métodos em pontos onde já é garantido que não é.
Tem outro detalhe "estranho", neste if dentro do construtor:
else if (ehCadeiaDeOnzeDigitos(cpf) && isValido(cpf))

É estranho porque dentro do método isValido temos:
private static boolean isValido(String cpf) {
    return ehCadeiaDeOnzeDigitos(cpf) && cpf.substring(NRO_DIGITOS_SEM_DV, NRO_DIGITOS_COM_DV).equals(moduloOnze(cpf.substring(0, NRO_DIGITOS_SEM_DV)));
}

Ou seja, ehCadeiaDeOnzeDigitos(cpf) é chamado duas vezes, desnecessariamente. Decida onde é melhor chamá-lo (no if ou dentro de isValido) e faça-o somente uma vez. Decida também se vai usar o prefixo eh ou is (tanto faz, desde que seja consistente em todo o código).
E dá para ficar elucubrando eternamente sobre várias coisas: as constantes NRO_DIGITOS_etc são realmente necessárias? Se forem, precisam ser públicas? Os métodos private também precisam ser static? (funcionalmente, não faz diferença, já que nenhum deles altera ou acessa o estado da instância) A mesma classe que representa o CPF deveria ser responsável pela formatação e criação de uma instância aleatória? E por aí vai... (e sem requisitos reais, fica difícil decidir ou opinar algo - mesmo com requisitos já seria uma discussão boa)
Comment: Bastante detalhado @hkotsubo, obrigado. Não sabia desse requisito de aceitar 0 no início do CPF, devo ter pego o algoritmo de fonte ruim, ou pior, deduzi isso de alguma maneira. :P Tem que tomar cuidado com os requisitos. Não faço questão do regex, mas achei um pouco exagerado otimizar o número de loops, não precisava tanto :) Dar-me-ia por satisfeito com um loop só para validar os dígitos, ficaria mais claro, na minha opinião. E bem observada a chamada de `ehCadeiaDeOnzeDigitos()`, como vê, eu não estava preocupado com performance. :)
Comment: @Piovezan É, calcular os 2 dígitos no mesmo loop talvez seja micro-otimização também, mas achei válido mencionar que é perfeitamente possível, e sem complicar demais o código :-)
Comment: Dado o cenário que o CPF tem um tamanho conhecido de 11 caracteres o ganho de performance ao fazer apenas um loop é imperceptível. Vale lembrar também que existe uma conta sendo feita onze vezes nesse loop aumentando um pouco o tempo de processamento também, de maneira ínfima considerado o cenário da mesma maneira que economizar no loop. Algo que eu não fiz o benchmarking, mas pode ter um ganho de performance é a validação se o o caractere corrente é numérico ou não sem usar um Pattern (declarado como constante). Eu só usaria o método isDigit da classe Character pra verificar.

Revisão de código da classe CPF em Java


Confused about free variables

Question: What is the difference between a free variable and a basic variable (the opposite of a free variable) when the free variable only appears once in only one equation in the system. It seems to me that the purpose of getting row reduced echelon form is to only get one equation for each basic variable (correct me if I'm wrong), but what happens when a free variable also only appears once? Why can't the free variable be considered a basic variable?
Comment: The opposite of a free variable is presumably a [bound variable](https://en.wikipedia.org/wiki/Free_variables_and_bound_variables)
Comment: Your terminology is rather opaque, it would help if you explained a bit more. "Free variable" is a standard term but "basic variable" is not. Also, I would hate to guess what RREF means.
Comment: Just made a correction. For basic variable, I meant the opposite of a free variable --- a variable that can't be simply anything but something well defined by other variables.
Comment: [Free vs. basic variable](https://www.math.wsu.edu/math/faculty/hudelson/free.html). A basic variable is one with a basic column in the RREF, that is a column with a pivot. *Basic* comes from the fact pivot columns form a standard basis. This answers your question "*Why can't the free variable be considered a basic variable?*"
Answer: Note that what you refer to as a 'basic variable' is more commonly referred to as a bound variable, which you might find useful in learning more about linear algebra. In a sense which variables are free and which are bound is just a question of choice. Consider the somewhat degenerate example of the equation
$$
x_1+2x_2 = 0
$$
Which has the corresponding matrix
$$
\begin{bmatrix}
1&2&0
\end{bmatrix}
$$
We could think of this as $x_1$ being a bound variable and $x_2$ being free and that would be correct, but we would be equally correct (if a bit more confusing) to write our original equation $2x_2+x_1 = 0$, which has RREF
$$
\begin{bmatrix}
1&\frac{1}{2}&0
\end{bmatrix}
$$
The general idea that you can take from this is that as long as one is careful you can permute the columns of your matrix (or equivalently change the order of your variables) and still faithfully encode a linear system.
Comment: Why can't you have two bounded variables?
Comment: @mathisfun you totally can, that just isn't the case in the example I gave. In the given example, only one of $x_1,x_2$ can be bound, since the bound variable by definition depends on the other one. It can be helpful to write the final expression in terms of your bound variables, i.e. $x_1 = -2x_2$ in the first presentation I gave or $x_2 = -1/2x_1$ in the second. In either case, we call the variable(s) on the right as being free, but once they are fixed to a particular value, the variable on the right is bound because it is completely determined by the expression on the right. Does that help?

Confused about free variables


CodeIgniter: How do I correctly run two queries with each other based on the first query result?

Question: I am querying my database for results (which all display correctly) and then while running a foreach statement I am attempting to look in another table for a matching ID to gather an override price which will take the place of the 'storeprice' listed in the first result.
Here is my model:
public function fetch_products($limit, $start, $manuid) {
    $this->db->order_by('productname', 'ASC');
    $this->db->limit($limit, $start);

    $query = $this->db->get_where('products', array('manuid' => $manuid, 'active' => 1));
    if($query->num_rows() > 0){
        foreach($query->result() as $row){
            $data[] = $row;
            $pid = $row->id;
            // Check for Price Override
            $squery = $this->db->get_where('price_override', array('id' => $pid));
            if($squery->num_rows() > 0){
                $result = $squery->row();
                $override = $result->storeprice;
                $data['override'] = $override;
            } else {
                $override = 0;
                $data['override'] = $override;
            }
        }
        return $data;
    }
    return false;
}

The $data['override'] is what is causing me an error. The following error to be precise:
Message: Undefined property: stdClass::$override

In the controller I am using the following:
$data['results'] = $this->store_products_model->fetch_products($config["per_page"], $page, $manuid);

And finally in the view I am calling the results inside of a table to display. All will display except for the override:
foreach ($results as $product){
               echo '
';
               echo '' . $product->productname . '	';
               if($product->override != 0){
                echo '$' . $product->override . '	';
               } else {
                echo '$' . $product->storeprice . '	';
               }
               echo '$' . $product->saleprice . '	';
               echo '' . $product->storepoints . '	';
               echo 'id . '">Edit';
               echo '
';
            }

Anyone see what I could be doing wrong here to give me the following error?
Message: Undefined property: stdClass::$override

Answer: The row is an object, not an array. Try:
$data->override = $override

edit:
Well, actually, $data is an array, but your inserting an object into it, so it would be
$last_index = sizeof($data) - 1;
$data[$last_index]->override = $override;

Comment: That definitely did the trick. Thank you kindly good sir. I perhaps was misunderstand how the object was being added to the array.


Access to SQL Server when administrator account deleted

Question: An interesting situation here.
We have a database server, used for testing only, where someone went in and deleted the administrator login.
Since this is a test server the was no other admin level login on the server.
Is there a way to get access to the server again without reinstalling SQL Server?
We do not need the data in the databases, these are droped and recreated everytime the tests are run.
Answer: I realize this is a little bit old, but I found a workaround today that worked for me and thought it might be helpful to others.
If your NT Authority/System account has admin access, you can use the following trick to log in as the NT Authority/System account and create a new login/reset credentials on other logins.
Steps:

Download PsExec: http://technet.microsoft.com/en-us/sysinternals/bb897553. This will allow you to run a program as the system user.
Extract the Zip and copy everything to your executable path
Open a command prompt and type the following: psexec /s /i "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe"

That should open up SQL Server Management Studio as the NT Authority/System login.
This also shows why it is probably a good idea to limit access to the NT Authority/System account unless you've got some other good reason.
Answer: The simplest solution might well be to reinstall SQL Server. Don't forget that you need to consider the time (and hence money) it will take to look for and try alternate solutions which may or may not work.
Though the first thing I'd try is a "repair" installation, to see if it covers this eventuality.
Comment: Thanks, we ended up with a full reinstall, it is running now :)
Answer: The best solution would have been to use the dedicated admin connection (DAC) which will let any administrator of the windows machine access the SQL instance.  Unless you have absolutely no way to log in as the built-in windows administrator account or any account that is a member of the local Administrators group you would probably need to do a full reinstall of both Windows and SQL to gain access again unless the sa account (or some other SQL login that was assigned the sysadmin fixed role) was available.  A SQL login doesn't help with your lack of administrator access to the Windows machine itself though... if that is what you meant anyway.
http://msdn.microsoft.com/en-us/library/ms189595.aspx
Comment: I don't know about MSSQL but restoring the Windows admin account most definitely does NOT require Windows to be reinstalled.
Comment: Right, I am just assuming based on what they said that they some how locked themselves out from being able to access any administrator account on the machine and worst case scenario, they have bitlocker enabled so something like http://pogostick.net/~pnh/ntpasswd/ won't work.  I believe deleting the actual built-in administrator account is not technically possible... but I'm not completely certain.


I don't understand this theorem about covering spaces or it is a typo?

Question: Isn't it a trivial conclusion the first part of the following theorem from Theodore Frankel book (The Geometry of Physics: An Introduction) or it is a simple typo?

Theorem: The orientable cover of $M$ is always orientable. The number
  of sheets is $1$ if $M$ is orientable and $2$ if $M$ is not orientable.
Comment: You might be fooled by the choice of terminology "orientable cover". Think of this as an [a posterior](https://en.wikipedia.org/wiki/A_priori_and_a_posteriori) terminology. Still, though, with improved terminology, this issue goes away. For example, some authors use the terminology "orientation cover" instead of "orientable cover".
Comment: @Max: It seems that's how it is written in that textbook. My guess is that this physics textbook is using "sheets" in a way that sounds nonstandard to our mathematical ears, i.e. as a synonym for "connected components".
Comment: To me it looks like it should be universal cover rather than orientable cover
Comment: By the way if I'm not mistaken the number of sheets doesn't depend on orientability : it's always $2$. The number of connected components, however, varies
Comment: @LeeMosher Ah so something along the lines of "number of sheets in one of the connected components" ? That's reasonable enough, but sounds unpractical
Comment: Something like that. I agree that its a misuse of terminology *at best*.
Answer: Whether this theorem is trivial depends on the definition of orientable cover. With that name one would hope that it is orientable but if that is not part of the definition than it has to be proven.
Answer: I find this paragraph on the page 573 in the same book:

... If $M$ is orientable, then
  the covering obtained reduces to $M$ itself, but if $M$ is not orientable we obtain a new
  space $\overline{M}$. In any case $\overline{M}$ is called the orientable cover of $M$, for, as we shall see, this
  $\overline{M}$ is always orientable.

So the theorem is correct.


PHP Verifica Fins de Semanas e Feriados

Question: Eu preciso de uma função em PHP que que me retorne se é feriado nacional ou fim de semana, alguem tem algum exemplo?
Comment: Não existe tal função. Verificar feriado é complicado. Tem que ter uma banco de dados com todos, mesmo assim pode mudar.
Comment: [Como criar uma lista de datas do ano em php, pulando os finais de semana?](http://pt.stackoverflow.com/q/111656/91)
Comment: [Script de dias úteis](http://pt.stackoverflow.com/q/61369/91)
Comment: Feriado nacional é impossível de representar nativamente.
Answer: Não há função nativa para isso, mas você pode usar o Holiday API, ele suporta feriados do Brasil e de outras localidades, Portugal não é suportado por enquanto.
Para demonstração fiz este JavaScript:

$(':button').click(function() {
  var dia = $(':input[dia]').val();
  var mes = $(':input[mes]').val();
  var ano = $(':input[ano]').val();
  var pais = $(':input[pais]').val();

  $.ajax({
    url: 'http://holidayapi.com/v1/holidays?country=' + pais + '&year=' + ano + '&month=' + mes + '&day=' + dia,
    type: "get",
    dataType: "json",
    success: function(data) {
      alert(data.holidays[0] != null ? data.holidays[0].name : 'Não é feriado');
    }
  });
});
input {
  width: 40px;
}

    Data:

      <input dia value="21">/
      <input mes value="04">/
      <input ano value="2016">

    Local:

      <select pais>
        <option value="BR">BR</option>
        <option value="US">US</option>
        <option value="FR">FR</option>
        <option value="ES">ES</option>
      </select>

<button>VERIFICAR</button>

Para PHP pode usar o cURL:
   function verificarFeriado($data, $boolean = false) {

    $param = array();

    // Sua chave (exigida após 01/08/2016!), leia no final dessa postagem!
    $param['key'] = '';

    // Listas de países suportados!
    $paisesSuportados = array('BE', 'BG', 'BR', 'CA', 'CZ', 'DE', 'ES', 'FR', 'GB', 'GT', 'HR', 'HU', 'ID', 'IN', 'IT', 'NL', 'NO', 'PL', 'PR', 'SI', 'SK', 'US');

    // Define o pais para buscar feriados
    $param['country'] = $paisesSuportados[2];

    // Quebra a string em partes (em ano, mes e dia)
    list($param['year'], $param['month'], $param['day']) = explode('-', $data);

    // Converte a array em parâmetros de URL
    $param = http_build_query($param);

    // Conecta na API
    $curl = curl_init('https://holidayapi.com/v1/holidays?'.$param);

    // Permite retorno
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // Obtem dados da API
    $dados = json_decode(curl_exec($curl), true);

    // Encerra curl
    curl_close($curl);

    // Retorna true/false se houver $boolean ou Nome_Do_Feriado/false se não houve $boolean
    return isset($dados['holidays']['0']) ? $boolean ? true : $dados['holidays']['0']['name'] : false;

    }

    var_export( verificarFeriado('2016-04-21') );
    // Resposta: 'Tiradentes'

    var_export( verificarFeriado('2016-04-21', true) );
    // Resposta: true

    var_export( verificarFeriado('2016-04-20') );
    // Resposta: false

    var_export( verificarFeriado('2016-04-20', true) );
    // Resposta: false

Importante:

A partir do dia 01/08/2016 será necessário obter uma chave para a API,
  para isso gere uma, gratuitamente, através do próprio site:
  https://holidayapi.com/.
A partir do dia 01/08/2016 será necessário usar o HTTPS ao invés do
  HTTP.

A função (em PHP) foi atualizada no dia 12/07/2016 para suportar essas alterações da API.
Answer: function mod_date($str){

    $addtime = new DateTime($str);
    $data_pre = $addtime->format('N');

    if(!in_array($data_pre, array(6,7))){

        return $addtime->format('Y-m-d');

    } elseif($data_pre == 6){

        $addtime->modify('+2 days');
        return $addtime->format('Y-m-d');

    } elseif($data_pre == 7){

        $addtime->modify('+1 day');
        return $addtime->format('Y-m-d');

    }

}

Obtendo a próxima data utilizando a função acima:
echo mod_date('2022-08-20');
// Retorna: 2022-08-22

PHP Verifica Fins de Semanas e Feriados


common slice function for validation

Question: I've to check more than 10 fields and slice its value.So I wrote below common function.
export const sliceFunction = (e: string, limit: number) => {
  console.log(e.length > limit ? e.slice(0, limit) : '','llllllllllllllllllllllll')
  return e.length > limit ? e.slice(0, limit) : '';
};

and I'm calling this function to validate as shown below:
   const handleChange =
        (fieldName: keyof EnrollmentFields) =>
        (e: React.ChangeEvent<HTMLInputElement>) => {
          setAlertError(false);
          if (fieldName === 'address2' || fieldName === 'address1') {
            sliceFunction(e.currentTarget.value, 55);
          }
if (fieldName === 'address3') {
            sliceFunction(e.currentTarget.value, 30);
          }
if (fieldName === 'phonumber') {
            sliceFunction(e.currentTarget.value, 14);
          }
    }

Issue is that console.log slices and returns correctly inside the sliceFunction. But in the input field its accepting more than the limit value. Ideally it should only accept the limit and shouldnt accept inputs after the limit.
Answer: You should assign the result returned by the function to the html input :
 if (fieldName === 'address2' || fieldName === 'address1') {
          e.currentTarget.value =  sliceFunction(e.currentTarget.value, 55);
          }

Or you can simply add maxLength attribute to your the html input
<input type="text" maxLength={5} name="address1" />

Comment: I tried with e.currentTarget and it didnt work. I cant use Maxlength cause I'm using customized input fields.
Comment: I changed the function toexport const sliceFunction = (e: React.ChangeEvent, limit: number) => {
  if(e.currentTarget.value.length > limit ){
    e.currentTarget.value = e.currentTarget.value.slice(0, limit);
  }
  return e.currentTarget.value;
}; and it worked

common slice function for validation


More than one input file in this Python code

Question: I am using this code for searching a target_string in a single input file (input.txt) and "extracting" those lines with the target_string in an output file (output.txt). Now I want to perform the same procedure but with several input files, for instance, input1.txt, input2.txt, input3.txt, ...
How can I modify this code for doing this?
from collections import deque
input_file = 'input.txt'
output_file = 'output.txt'
buscado = 'target_string'
 contexto = deque([], 4)

 for line in f_in:
    with open(input_file) as f_in, open(output_file, "w") as f_out:
     contexto.append(line)
         if  len(contexto) < 4:
           continue
         if buscado in contexto[1]:
           f_out.writelines(contexto)

Many thanks!
Answer: You can create a list with the filenames, such as:
file_list = ['file-1.txt', 'file-2.txt', ...]

for each of the filenames you can then run your existing code:
for file in file_list:
    # open file
    # loop through lines
    ...

Comment: I tryed to add these line in the code and it's not running. I'm not a proffesional coder, can you help me showing how should I add this part of the code into mine, please?
Answer: from collections import deque
output_file = 'output.txt'
buscado = 'target_string'
contexto = deque([], 4)
file_list = ['input1.txt', 'input2.txt', 'input3.txt']

def myfun(input_file):
    for line in f_in:
        with open(input_file) as f_in, open(output_file, "w") as f_out:
            contexto.append(line)
        if  len(contexto) < 4:
            continue
        if buscado in contexto[1]:
            f_out.writelines(contexto)

for file in file_list:
    myfun(file)

Comment: Thank you, but I don't understand this code. It totally changed my code and I don't know where to set my target_string
Comment: Combine two answers
Comment: how? I can't understand your answers