Como dividir um array e gravar no banco de dados em PDO

Question: Possuo esse código:
<?php
    foreach ($_POST as $dados =>$value) {
    $list = explode('_', $value);
    echo '
' . print_r( $list, TRUE ) . '
';
?>

Ele gera a saída da array:
Array
(
    [0] => Manoel da Silva
)

Array
(
    [0] => firstname.lastname@example.com
)

Array
(
    [0] => (21)2481-3232
)

Array
(
    [0] => 41106
)

Array
(
    [0] => 21215430
)

Mas quero que a saída seja assim:
Array
(
    [1] => Manoel da Silva
)

Array
(
    [2] => firstname.lastname@example.com
)

Array
(
    [3] => (21)2481-3232
)

Array
(
    [4] => 41106
)

Array
(
    [5] => 21215430
)

Após isso, quero gravar os valores no banco de dados, mas algo está dando errado:
$conn = conecta();

foreach ($_POST as $dados =>$value) {
    $cadastro = $conn->prepare('INSERT INTO clientes(:nome) VALUES $value');
    $cadastro->bindValue(':nome', $value); //to colocando um valor só...
    $cadastro->execute();
}

Quero inserir as informações separadas no banco, como faço isso?
Comment: Qual é o output original? O formato do array que está a percorrer com o foreach? Dê um exemplo e melhore o display do código acima sff
Comment: Eu não entendi a pergunta  vc tem mais campos p colocar informação além do `nome`?
Comment: sim ray eu tenho 11 campos:, so não coloquei tudo para nao ficar muito extenso a pergunta:
Answer: Ele gera essa saída indesejada porque está sempre a substituir o valor da $list, ou seja, vai sempre imprimir a $list gerada na linha anterior:
Creio que esta lógica será melhor:
$user = array();
foreach($_POST as $dado => $value) { // nota que mudei de dados para dado para ficar mais claro
   $list = explode('_', $value);
   $user[$dado] = $list[0]; // armazenamos cada dado (nome, telefone, etc..) dentro de um array
}
print_r($user);

Pode também inserir logo na base de dados:
foreach($_POST as $dado => $value) { // nota que mudei de dados para dado para ficar mais claro
    $cadastro = $conn->prepare('INSERT INTO clientes(' .$dado. ') VALUES :' .$dado); // nota que a chave do post ($dado) deve ser igual ao nome da coluna que tem na tabela em que vai inserir isto
    $cadastro->bindValue(':' .$dado, $value); //to colocando um valor só...
    $cadastro->execute();

}

É de notar que esta não a forma mais segura de fazer isso
Comment: continua no array[0], todos os valores:
Array
(
    [nome] => Array
        (
            [0] => Manoel
        )

    [email] => Array
        (
            [0] => firstname.lastname@example.com
        )

)
cada array com um numero diferente e o q preciso.
Comment: Tem razão. Editei na parte do explode. Desculpe, assim já deve dar certo. Mas ao que é que está a fazer explode? Dê-me um exemplo. Não ponha `True` como segundo elemento do `print_r`
Comment: Estou usando explode para substituir split do mysql, na verdade eu quero "separar" os valores do array para poder inserir no bd. a saída agora está assim : Array ( [nome] => [email] => [telefone] => [servico] => 41106 [sCepDestino] => [num] => 48 [comp] => casa 1 ) , acho que agora dá pra inserir os dados separadamente, alguma sugestão no insert?
Comment: Não era o array nesse formato que queria? E se não puser o explode e deixar só `$user[$dado] = $value;`? Será isso que quer?
Answer: Ao utilizar prepared statemens coloque as marcações(placeholders) na consulta, não passe os valores direto na sql e lembre nomes de colunas, tabelas não podem ser associados com placeholders apenas valores.
Código atual:
$cadastro = $conn->prepare('INSERT INTO clientes(:nome) VALUES $value');

Para corrigir faça:
$cadastro = $conn->prepare('INSERT INTO clientes(nome) VALUES :nome');

Para inserir todos os valores de forma mais pratica passe um array no execute() e use as interrogações como bind.
foreach($_POST as $dado => $value) {
   $valores = explode('_', $value);
   $binds = str_repeat('?,', 10) .'?';
   $cadastro = $conn->prepare('INSERT INTO clientes(nome,email,telefone,servico,cep,tipo_logradouro,logradouro,numero,complemento,bairro,cidade,estado) VALUES ('. $binds .')');
   $cadastro->execute($valores);
}

Comment: Consegui ! a saída agora está assim :   Array ( [nome] => Clayton Campos ) Array ( [nome] => Clayton Campos [email] => email@example.com ) Array ( [nome] => Clayton Campos [email] => firstname.lastname@example.com [telefone] => (21)2481-3232 ) ,como faço agora para inserir cada array num campo da tabela (INSERT) em PDO ?
Comment: eis o código:   $lista = array();
foreach($_POST as $dados => $value) {
$list = explode('_', $value);
$lista[$dados] = $list[0];
print_r($lista).'';
}
Comment: @ClaytonCampos daqui a pouco edito
Comment: @ClaytonCampos sempre são vem os 11  campos?
Comment: oops faltou um , são 12 , são eles: nome,email,telefone,servico,cep,tipo_logradouro,logradouro,numero,complemento,bairro,cidade e estado.serão preenchidos com o valor de array que vem do post,essa é a idéia.
Comment: @ClaytonCampos isso fica dentro do `$list` depois do `explode()` certo?
Comment: não vem antes: $lista = array();
foreach($_POST as $dados => $value) {
$list = explode('_', $value);
$lista[$dados] = $list[0];
print_r($lista).'';
}  o resultado vem de $value
Comment: @ClaytonCampos editada, veja se os valores vão para os campos corretos.
Comment: Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\Program Files (x86)\EasyPHP-126.96.36.199\www\Loja\test.php on line 108 ( $cadastro->execute($valores);)
Comment: `$valores` tem qtos elementos?
Comment: coloque 13 elementos, por favor.
Comment: @ClaytonCampos algum é vazio? se não basta deixar assim `$binds = str_repeat('?,', 12) .'?';`
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/40011/discussion-between-clayton-campos-and-rray).


free software for radical algebraic equations

Question: I want to study an algebraic curve defined by equations of the form
$$ a_1 \sqrt{f_1(x)} + ... + a_n \sqrt{f_n(x)} = 0, $$
where $x$ is a real variable and $f_i$ are polynomials. $ a_1,... a_n $ could be functions of $x$, and there could be more than one equation (that is a system), and it has also constant parameters (not just numbers) and other variables ($y$ for two dimensions), though all this may be not important for this question.
I wanted to use SageMath, but it seems it can't even solve an equation
$$ \sqrt{x} + \sqrt{1-x} = 1 $$
with obvious solutions 0 and 1.
x = var('x')
rad_pol = sqrt(x) + sqrt(1-x) - 1
solve(rad_pol, x)
# Out: [sqrt(x) == -sqrt(-x + 1) + 1]

I checked Mathematica online, and it solves such an equation.
However, I can't be sure that I will be able to solve my systems of equations online (because of proprietary software restrictions or online limitations), and maybe there exists an even more powerful instrument to solve such equations. In fact, I'm more interested in a good instrument to solve a system of equations, because I could do radical simplifications manually, but in this respect I see little difference between systems, because the Gröbner basis is almost universally implemented. However, a decent computer algebra system may have more advanced methods to solve radical equations than I could do manually (like this method with resultants).
I checked that online Sage can neither solve the simple equation, so the problem is likely not my installation. Do you know good free software to do that? If not, what could be considered the most powerful software for these kinds of problems, even non-free?
UPD: thanks to Samuel Lelièvre's answer, we can solve the equation above in Sage. Unfortunately, it still can't solve an equation for two points in two dimensions. Suppose we want to find a solution for
$$|\mathbf{n}_1 + \mathbf{n}_2| = 1,$$
where
$$\mathbf{n}_i = \frac{(x_i - x_0; y_i - y_0)}{\sqrt{(x_i - x_0)^2 + (y_i - y_0)^2}},$$
or, by squaring the first equation, $1 + 2 \mathbf n_1 \mathbf n_2 = 0$,
$$ \sqrt{(x_1-x_0)^2 + (y_1-y_0)^2} \sqrt{(x_2-x_0)^2 + (y_2-y_0)^2} + 2 \left((x_1-x_0)(x_2-x_0) + (y_1-y_0)(y_2-y_0)\right) = 0$$
This is a curve on which the sum of unit vectors to two given points is equal to one. The answer is known to be a part of a circle, and it can be solved by Mathematica (both with numeric point coordinates and with symbolic ones). Again, it can't be solved by sagemath, unfortunately. So the question about a powerful enough system remains.
# variables
x0, y0 = var('x0 y0')
# parameters
x1, x2, y1, y2 = 0, 1, 0, 0 # var('x1, x2, y1, y2')
r1, r2 = var('r1, r2')
# can't solve
eq2 = 2 * ((x1-x0)*(x2-x0) + (y1-y0)*(y2-y0)) == - r1 * r2
solve([eq2, r1**2 - ((x1-x0)**2 + (y1-y0)**2), r2**2 - ((x2-x0)**2 + (y2-y0)**2)], x0, y0, to_poly_solve=True)
# Mathematica succeeds:
# solve 2 * ((x1-x0)*(x2-x0) + (y1-y0)*(y2-y0)) == - sqrt((x1-x0)**2 + (y1-y0)**2) * sqrt((x2-x0)**2 + (y2-y0)**2), x1=0, y1=0, x2=1, y2=0 for x0, y0
#
# maybe try without new variables for radicals?
eq3 = 2 * ((x1-x0)*(x2-x0) + (y1-y0)*(y2-y0)) + sqrt((x1-x0)**2 + (y1-y0)**2) * sqrt((x2-x0)**2 + (y2-y0)**2) == 0
solve(eq3, x0, y0, to_poly_solve=True)
# doesn't work again, empty set.

Comment: Arthur Cayley (1821-1895) made a very thorough study of these curves in [*On polyzomal curves, otherwise the curves* $\sqrt{U} + \sqrt{V} + \&\text{c.} = 0$](https://www.google.com/search?q=%22On+polyzomal+curves%2C+otherwise+the+curves%22+Cayley&filter=0), **Transactions of the Royal Society of Edinburgh** 25 (1869), pp. 1-110. [archive.org copy](https://archive.org/details/transactionsofro25royal/page/n21/mode/2up) Incidentally, Cayley uses the radical symbol with an extra horizontal bar for nonnegative square roots (see article 5, which begins at the bottom of p. 5).
Comment: @DaveL.Renfro this article is of great importance for my study. Tremendous thanks for the reference and the link!
Answer: Sage's solve has an optional parameter to_poly_solve.
It helps in this case:
sage: x = var('x')
sage: rad_pol = sqrt(x) + sqrt(1 - x) - 1
sage: solve(rad_pol, x)
[sqrt(x) == -sqrt(-x + 1) + 1]
sage: solve(rad_pol, x, to_poly_solve=True)
[x == 0, x == 1]

The documentation of solve can be accessed

from Sage

in text mode:
sage: solve?

rendered in html:
sage: browse_sage_doc(solve)

in the built documentation

online:
https://doc.sagemath.org/
in particular:
solve
offline:
file:///path_to_sage_doc/index.html
in particular
file:///path_to_sage_doc/sage/html/en/reference/calculus/sage/symbolic/expression.html?#sage.symbolic.expression.Expression.solve

Depending on how you installed Sage, typing sage.env.SAGE_DOC
in a Sage session might give you a path. If so, you can replace
/path_to_sage_doc with that path in the "offline" urls above.
Comment: Thank you very much! This really works, I upvote. My sage installation is very poor and I killed my system while struggling with OS package manager vs `pip` packages. However, sage works as a part of a Jupyter notebook, and I'm fine with that. Thanks for great links to docs!
Unfortunately, your method doesn't work for more advanced equations (see my update). Should directly using Maxima provide more options, or is it the same functionality?
Answer: The original equation is equivalent to a system with $n+1$ unknowns:
$$ \eqalign{
\sum a_i r_i & = 0, \cr
r_1^2 - f_1(x) & = 0, \cr
&... \cr
r_n^2 - f_n(x) & = 0,
}
$$
with additional requirements all $r_i \geq 0$.
I was able to solve such system with sagemath (UPD: only for the simplest case, not for the updated question). Please add answers/comments, if there is some more powerful method than this or if I missed something!
Comment: Now I understand that this system is not completely equivalent: one has to require that $r_i >= 0$ (this is not a big problem, because all original solutions will be a subset of the new ones). I also have to think about how this affects the Gröbner basis.


What is the sum of this modulo series?

Question: Given only a large integer upto $ 10^{18} $ , what can be an efficient way to calculate
 $$ \sum_{k=1}^{\left \lfloor \sqrt{N} \right \rfloor} \left ( N \ mod \  k^{2} \right ) $$
Note that for a local machine, computation can go upto $ 10^{6} $ iterations.
Comment: Possibly useful: [(Question 1629608)](https://math.stackexchange.com/questions/1629608/calculating-the-summation-of-n-bmod-i).
Comment: N is upto $10^{18}$. So this solution https://math.stackexchange.com/questions/1629608/calculating-the-summation-of-n-bmod-i  works in $O \left ( 10^{9}  \right )$ which is too large for a local machine.
Comment: The sequence has OEIS entry [A072516](https://oeis.org/A072516) but unfortunately no other formulae are listed.
Answer: It might be worth rewriting the sum with the modulo as the floor of integer division, $\displaystyle N\lfloor\sqrt{N}\rfloor-\sum_{k=1}^{\lfloor\sqrt{N}\rfloor}k^{2}\left\lfloor\frac{N}{k^{2}}\right\rfloor$. You could then attempt to partition the sum into subsets of $k$ such that $\displaystyle\left\lfloor\frac{N}{k^{2}}\right\rfloor$ is a certain integer, $1,2,3,\ldots$, and then sum those simpler sums individually. User alex.jordan has described a similar method in (Question 3618219).
Comment: @RishabhDeepSingh I am not claiming there is a closed form for the sum and I don't believe there is one. The method I have referenced gives a potential way to reduce the number of terms in the sum by simplifying terms with the same value of $\left\lfloor\frac{N}{k^2}\right\rfloor$ and so, potentially reducing the complexity of the calculation. Also, there should be no loss of precision with the rearrangement; it is an equivalence and all terms are integers.
Comment: @RishabhDeepSingh I'm not really sure what you mean. We should be able to calculate the terms $M$ and $\left\lfloor\sqrt{\frac{N}{M+1}}\right\rfloor$ exactly since they are integers. We don't need to know the fractional part of $\sqrt{\frac{N}{M+1}}$ since it gets truncated by the floor.
Comment: Actually, it's just a small part of a complex problem for a coding contest. You can find the actual question over https://www.codechef.com/APRIL20A/problems/PPDIV
Comment: But that sum has a closed-form. and this has some precision loss issue and no closed form.
Comment: The precision i was talking about in the value of $m = \sqrt[3]{n/4}$ and $k=\sqrt{\frac{n}{m+ 1}}$
Comment: for smaller numbers cant there is some error in the calculation of the $\lfloor \sqrt{\frac{n}{m+1}} \rfloor$
Comment: @Jam can you please tell where the term $k^2$ in the product will go in the referenced solution. I can't understand how we are going to partition the sum along with the variable $k^2$.
Comment: @AmaanIqbal I hadn't gone through the entire method or written it up into a code yet so there may be some snag I've not seen yet (my answer was intended as a possible suggestion). But the $k^2$ shouldn't be hard to deal with since when $\left\lfloor\frac{N}{k^2}\right\rfloor$ is held constant, $\displaystyle \sum_{a}^b k^2=\sum_{0}^b k^2-\sum_{0}^{a-1} k^2$ becomes a difference of [geometric series](https://en.wikipedia.org/wiki/Geometric_series) and can be given a closed form.
Comment: @Jam Thanks for the response! Just one doubt, how do we decide the range `a` to `b` here?
Comment: @AmaanIqbal I think it should be the same as in Alex's answer.
Comment: @AmaanIqbal Yes. I was using them as a placeholder to refer to any such subsequence of $k$.
Comment: @AmaanIqbal No problem. Out of interest, a lot of people seem to be asking about problems of the form $\sum \lfloor x\rfloor$. Has it appeared in an exam recently or something?

What is the sum of this modulo series?


How to change node save button text?

Question: I found a discussion with some methods for d6 here http://drupal.org/node/344802
on how to change the node "Save" button text to sg else.
Any tips for d7? I would prefer to use form api.
Answer: you could use string overrides module or use hook:
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'name_of_form') {
    $form['actions']['submit']['#value'] = 'Your button text';
  }
}

Comment: Thanks, I only want to change it for a content type so string override is no good. I tried the form alter code but no change. I checked the $form with dpm, but it has no submit array , only a #submit which looks like sg else.
Comment: This worked for me. The $form_id is unique to the submit form of that content type, so it should work.
Comment: for me it was an $form['ajax-submit']['#value'] = 'xyz', but I'm using the afb module to submit a node through a block form.
Answer: Here is an example: I have created a module called change_form_values and the form ID of my content type is content_type_test_node_form:
this work for me in Drupal 7:
function change_form_values_form_alter(&$form, &$form_state, $form_id) {
    //dsm($form_id); // to see form ID
    if ($form_id == "content_type_test_node_form") {
    $form['actions']['submit']['#value'] = 'New button text';
    }
}

this work for me in Drupal 6:
function change_form_values_form_alter(&$form, &$form_state, $form_id) {
    //dsm($form['form_id']['#id']);
    if ($form_id == "content_type_test_node_form") {
    $form['buttons']['submit']['#value'] = 'New button text';
    }
}

I hope information be useful.
Answer: I found the excellent Node buttons edit module for this and it works really our of the box using admin. Here is an excerpt about it from the module's project page:

This is a simple little module that allows one to change the text on the 'Save', 'Preview' and 'Delete' buttons on a node form.
Answer: For Drupal7 it's simple just:
$form['buttons'] = array(
    '#type' => 'submit',
    '#value' => t('Your desire text here'),
    );

Wihtout adicional functions...
Comment: Nah, by that you'ld overwrite the whole button and reset possible other values given originally (`#weight`, `#validate`, `#submit` ...). You'ld better go only for the `#value`, like written in the other answers above.
Comment: i tested with 3 form of my site and all of them are working fine... i guess what you said could be possible if your using some kind of callback function or ajax function related to the button....

How to change node save button text?


Nuget - packing a solution with multiple projects (targeting multiple frameworks)

Question: Say I have the following solution with multiple versions of the same code each targeting a different framework and I would like to generate a nuget package from it.
SharedLib.sln
  SharedLib.Net35.csproj
    packages.config
  SharedLib.Net40.csproj
    packages.config
  SharedLib.Phone.csproj
    packages.config
  SharedLib.SL4.csproj
    packages.config

The expected nupkg has the following structure
SharedLib.1.0.nupkg
  lib/net35/SharedLib.dll
  lib/net40/SharedLib.dll
  lib/sl4-wp/SharedLib.dll
  lib/sl4/SharedLib.dll

nuget.exe pack SharedLib.SL4.csproj will automatically determine that the target framework is SilverLight4 and place the binaries in lib/sl4
I know I can add a SharedLib.SL4.nuspec file with a <file> section to include binaries from the other projects but is there a way to make nuget automatically place the combined solution output into the proper structure (and also detect dependencies in packages.config from all projects?
Answer: No, there's currently no way to do this other than to write a custom build script that puts the files in the right place and then runs NuGet pack on them, or to take the .nuspec approach you described.
This is a feature we'd like to have, but haven't thought of a good way to do it. However, your post just gave me an idea.
Today, you can point nuget pack at a .csproj file.
We could consider an approach that allowed you to point it at a .sln file and if the project names follow some convention, we'd package all the projects into a single package.
If you really want this feature, consider logging an issue in the NuGet issue tracker. http://nuget.codeplex.com/workitem/list/basic
Comment: Running nuget pack on a sln would be great. I want to package a set of related assemblies in a single package to make managing them more easy than seperate packages. They are not dependent on each other.
Comment: The reason this is such a win is for build servers that are very convenient for building and publishing a package for a single proj, but become a nightmare when you need the above. To me, there's also some critical story missing that makes the whole feature redundant. Who *doesn't* need to package for each CLR?
Comment: I might just do that though I'm not completely done figuring out what it is I want :)

1. it would be nice to point nuget at a solution and have it figure everything out

2. it would be nice if the different framework versions inside the resulting package could have different dependencies. e.g. the WP version might need an extra package that supplies types that are not part of WP core.

I'll mark your answer as accepted for now and think a bit more on the issue.
Comment: Is this still not supported?


Is the rule for squaring differences a "degenerate" case of the law of cosines?

Question: Compare $(a-b)^2=a^2+b^2-2ab$ (the square of a difference) with $c^2=a^2+b^2-2ab\cos{C}$ (the law of cosines), and you will notice the similarity.
So, if one has a (degenerate) "triangle" with three sides $a,b,$ and $c$ for which $c=a-b$, does that mean that the measure of the angle opposite the side with length $c$ is zero degrees, since $\cos{0^{\circ}}=1$?
Answer: Yes (as long as $c$ is the longest side), as $\Bbb R$ is a model of Euclidean geometry, with $ab$ the dot product. If $a,\,b$ have the same sign, $C=0^\circ$; if they have different signs, $C=180^\circ$, but the "$ab$" in the cosine rule really means $|a||b|$, which in normal multiplication terms is $-ab$, so it works out.


Ubuntu "service" command

Question: I type in the following command on two separate machines both running Ubuntu:
service ssh status
Output of machine 1:
ssh start/running, process 25369
Output of machine 2:
● ssh.service - OpenBSD Secure Shell server
   Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2016-03-31 15:56:49 BST; 4min 1s ago
 Main PID: 2172 (sshd)
   CGroup: /system.slice/ssh.service
           ├─1825 sshd: (some username) [priv]
           ├─1843 sshd: (some username)@pts/0
           ├─1844 -bash
           ├─1868 su root
           ├─1869 bash
           ├─2172 /usr/sbin/sshd -D
           └─2176 systemctl status ssh.service

Mar 31 15:56:49 (computer's hostname) systemd[1]: Started OpenBSD Secure Shell server.
Mar 31 15:56:49 (computer's hostname) sshd[2172]: Server listening on 0.0.0.0 port 22.
Mar 31 15:56:49 (computer's hostname) sshd[2172]: Server listening on :: port 22.

I then type the following command:
service ssh restart

Output of machine 1:
ssh start/running, process 25369

No output whatsoever on machine 2.
I get similar results with all the services (not only with SSH).  How do I get machine 2 to output the same as machine 1 when dealing with the service command?
Comment: You don't. This is normal behavior.
Answer: The problem was with systemd...  So I removed it by running:
sudo apt-get install upstart-sysv
The "service" command is finally outputting the same as any other Linux distribution...  Without the unneeded extra garbage!
Comment: You removed it by installing something?
Comment: Yeah, I know.  Open source (communism) based operating systems are messed up like that.  I googled "ubuntu remove systemd"

Ubuntu "service" command


Attach the module "Insert" to ALL "Body" fields?

Question: I've just installed the Insert module. I have many many content types in my site and all of them contains the same "Body" field. It would take me much time to attach an Insert image-field to each one of them manually and I need a way to do that at once.
How will you achieve this goal? If you drop a module's name please also detail in steps where and what will you do to achieve it.
Answer: You may add this code snippet in the install file in your custom module and run update.php. It works fine, I've tested this code on my local site
<?php
/**
 * Add an image field to a node.
 */
function my_module_update_7001() {
  $field_name = 'field_insert_image';

  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'image',
    );
    field_create_field($field);
  }

  $content_types = node_type_get_types();
  $exclude = array('example');
  foreach ($content_types as $content_type) {
  if (!in_array($content_type->type, $exclude)) {
    $instance = field_info_instance('node', $field_name, $content_type->type);
    if (!$instance) {
      // Create the instance.
      $instance = array(
        'field_name' => $field_name,
        'entity_type' => 'node',
        'bundle' => $content_type->type,
        'label' => 'Image Insert',
        'description' => 'An image for the article.',
        'required' => TRUE,
        'settings' => array(
          'file_extensions' => 'png jpg jpeg',
          'file_directory' => '',
          'max_filesize' => '20 MB',
          'alt_field' => 1,
          'title_field' => 1,
          'max_resolution' => '300x200',
          'min_resolution' => '200x125',
          'default_image' => 0,
         ),
         'widget' => array(
          'type' => 'image_image',
          'module' => 'image',
          'active' => 1,
          'settings' => array(
            'insert' => 1,
            'insert_absolute' => 1,
            'insert_styles' => array_keys(insert_styles_list()),
          ),
         ),
         'display' => array(
          'default' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'full' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'teaser' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
       )
      );

      field_create_instance($instance);
    }
  }
 }
}

Comment: I guess it doesn't matter If I already attached "Insert" to two "Body" fields manually right? I would anyhow attach it to all other existing fields? (I've yet to learn PHP and thus wonder).
Comment: Yes, I add new field only if it doesn't exist in the content type already. You just need to change $field_name variable with your field name. And also you can exclude some content types by adding their names in the $exclude array. Please do not forget to backup your database before applying these changes.
Answer: Your requirements is not very clear. Insert module allows user to insert the image in the body field in a single click using the insert button.
The short answer to your question is NO short method. Even if you're using a shared field and the original field has been configured to use Insert button you still have to configure each field to enable the Insert button. It is possible to do this via Drupal API but you have to be familiar on field apis at least or via hook_update_N. As of my understanding of your requirements is you are looking for a fastest method to enable Insert for each content type. So yeah your only option is to enable it manually.
Answer: My suggestion for you is to get all content type (also you can exclude some of them that you don't want to add) then in one foreach with field_create_instance add your desire field to content type.
I provide some help code (I don't test it right now and just typing them) you can achieve what you with some think like below code.
(you can also get your field info with field_info_instances)
First register a menu, in callback of menu call a function, in function in foreach of your content types you want add field with field_create_instance.
  <?php

  function  autoaddinsert_menu(){
    $items =array();

    $items['admin/addautoinsert'] =array(
      'title' => 'Add isert field',
      'description' => 'add insert  field automatically to all content type',
      'page callback' => 'autoinsert_addfield',
      'access callback' > true,
    );
    return $items;
  }

  function autoinsert_addfield(){

    $ctypes=node_type_get_types(); //
    foreach($ctypes as $content_type){

    // Check if our field is not already created.
      $yourfieldname='field_yourinsert';// @todo put your  machine name of insert field here
      if (!field_info_field($yourfieldname)) {

      // Create the field base.
        $field = array(
          'field_name' => $yourfieldname,
          'type' => 'image',  //@todo put your field type here
        );
        field_create_field($field);

        // Create the field instance on the bundle.
        $instance = array(
          'field_name' => $yourfieldname,
          'entity_type' => $content_type->type,
          'label' => 'My Field Name', //@todo put your label here
          'bundle' => $content_type->type,
          // If you don't set the "required" property then the field wont be required by default.
          'required' => TRUE,

          'widget' => array(
            'type' => 'textfield',
          ),
        );
        field_create_instance($instance);
      }
    }
  }

Comment: The widget type is wrong
Comment: @ClemensTolboom This is just a clue to what he should do and is not exact solution


Not able to return objects in an ArrayList Java

Question: I believe it has to do with my constructor but I am not entirely sure.
public String toString() is supposed to iterate through the array and return the result.
This converts decimal to binary.
public class DNumber {

    ArrayList<Digit> binary = new ArrayList<Digit>();

    /**
     * Constructor for objects of class DNumber
     */
    public DNumber() {
        ArrayList<Digit> binary = new ArrayList<>();
        Digit num = new Digit(0);
        binary.add(0, num);
    }

    public DNumber(int val) {
        ArrayList<Digit> binary = new ArrayList<>();
        int num = val;
        while (num > 0) {
            Digit bin = new Digit(num % 2);
            num /= 2;
            binary.add(0, bin);
        }
    }

    /**
     * An example of a method - replace this comment with your own
     *
     * @param y a sample parameter for a method
     * @return the sum of x and y
     */
    public String toString() {
        ArrayList<Digit> binary = new ArrayList<>();
        String s = "";
        for (Digit d : binary) {
            s = s + d.toString();
        }

        return s;
    }
}

Comment: All your methods/constructors are creating *new* lists. None of your code uses your `binary` *field* at all - they just use new local variables. Remove the first line of each of your methods/constructors.
Comment: Can you mention what is actual output and your expected output?
Comment: If you change the `while` loop to a `do`/`while` loop with the same condition, you can replace the body of `DNumber()` with `this(0);`.
Comment: You are using four different `binary` arrays, try to use just the global one,
Answer: You are using different binary list for each operation, try this:
public class DNumber {

ArrayList<Digit> binary = new ArrayList<Digit>();

/**
 * Constructor for objects of class DNumber
 */
public DNumber() {
    Digit num = new Digit(0);
    binary.add(0, num);
}

public DNumber(int val) {
    int num = val;
    while (num > 0) {
        Digit bin = new Digit(num % 2);
        num /= 2;
        binary.add(0, bin);
    }
}

/**
 * An example of a method - replace this comment with your own
 *
 * @param y a sample parameter for a method
 * @return the sum of x and y
 */
public String toString() {
    String s = "";
    for (Digit d : binary) {
        s = s + d.toString();
    }

    return s;
}

}
Answer: In each of your methods you create a new ArrayList<Digit>. So, in the last one you are trying to iterate in an empty ArrayList.
Delete  all the ArrayList<Digit> binary = new ArrayList<>(); inside your methods:
public class DNumber {

    ArrayList<Digit> binary = new ArrayList<Digit>();

    /**
     * Constructor for objects of class DNumber
     */
    public DNumber() {
        Digit num = new Digit(0);
        binary.add(0, num);
    }

    public DNumber(int val) {
        int num = val;
        while (num > 0) {
            Digit bin = new Digit(num % 2);
            num /= 2;
            binary.add(0, bin);
        }
    }

    /**
     * An example of a method - replace this comment with your own
     *
     * @param y a sample parameter for a method
     * @return the sum of x and y
     */
    public String toString() {
        String s = "";
        for (Digit d : binary) {
            s = s + d.toString();
        }

        return s;
    }
}


XML resource names are changed in release builds after upgrading Gradle plugin

Question: After upgrading the Gradle plugin to 4.2.0 (before that, I didn't have this problem), it seems the names of XML resource files are changed when building a release build, for instance from res/xml/settings_master_switch_1.xml to res/cb1.xml.
This presents a problem with a library I wrote, since it takes the name of a resource given in xml, for instance
<com.smp.masterswitchpreference.MasterSwitchPreference
       ..
        app:ms_includedPrefScreen="@xml/settings_master_switch_1" />

and looks up the resource id with this function
fun resInt(resName: String?, type: String): Int? {
                resName ?: return null
                val f = File(resName).nameWithoutExtension
                return context.resources.getIdentifier(f, type, context.packageName)
            }

The consumer of this library can simply have
release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }

or even with minifyEnabled false to generate the problem.
The library with demo app can be found here https://github.com/svenoaks/MasterSwitchPreference
So I assume I must add some type of R8/Proguard or Gradle setting in consumer of this library to not change the name of the xml resource? What would this rule be?
I've tried both defining the resources to keep in res/raw/keep.xml of the consumer app -
<resources xmlns:tools="http://schemas.android.com/tools"
 tools:keep="@xml/settings_master_switch_1,@xml/settings_master_switch_2,@drawable/ic_baseline_cake_24.xml" />

and this rule in the proguard-rules.pro
-verbose
-keepattributes InnerClasses
-keep class **.R
-keep class **.R$* {
    <fields>;
}

without success, the plugin renames the XML resources anyway.
Answer: Generally one may want to keep class R:
-verbose
-keepattributes InnerClasses
-keep class **.R
-keep class **.R$* {
    <fields>;
}

But one can also annotate, in order to keep specific resources:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@xml/settings_master_switch_1" />

Comment: I tried both of those in the consumer app, and unfortunately neither of those work with the Gradle plugin 4.2.0, the resources are renamed anyway.
Answer: Add the following configuration in gradle.properties
//Turn off the resource compression that comes with the system
android.enableResourceOptimizations=false

Comment: `enableResourceOptimizations` will be removed in AGP 8.0, [source](https://github.com/godotengine/godot/issues/53749) (unfortunately I can't find anything more definitive). Also if anybody is interested, there is a [blog post by Jake Wharton about this flag](https://jakewharton.com/smaller-apks-with-resource-optimization/)
Answer: In my case all I needed to do was change the attr declaration from integer to string:
   <attr name="ms_includedPrefScreen" format="string"/>
        <attr name="ms_excludedPrefScreen" format="string"/>

and remove the "@" annotation from the consumer, so that a literal string with the correct name is passed in:
app:ms_includedPrefScreen="xml/settings_master_switch_1"


right-continuous extension of nondecreasing right-continuous function

Question: I'm having trouble with showing that the construction in my solution to the following problem is well defined:

Let $D\subset\mathbb{R}$ be dense. Let $f:D\to\mathbb{R}$ be a non-decreasing right-continuous function. Show that there is a unique right-continuous, non-decreasing extension $\hat{f}:\mathbb{R}\to\mathbb{R}$

Attempt: I defined $\hat{f}(x)=\lim_{y\to x+,y\in D}f(y)$. Non-decreasing is trivial and right-continuity is clear by $\mathbb{R}$ being complete. Let $g$ be another extension, then: $g(x)=\lim_{y\to x+,y\in D}f(y)=f(x)$ so this extension is unique. But I'm not able to show that my $\hat{f}$ is independent of the choice of the sequence.
Answer: If given another dense sequence y, take the union of that and the original sequence x to get another dense sequence z.
If this new sequence z doesn't also converge to the same function as x, then contradiction.
And if the second dense sequence y, which is a subsequence of the convergent new dense sequence z, doesn't converge to the same limit as z, also contradiction.


failed to get status code from returned jqXHR of $.post call

Question: I am using jQuery to post and insert a row of record to the end of table body by registering submit event listener. Here is fiddle: https://jsfiddle.net/8jew8kk7/4/
$("form").submit(function(event) {
  event.preventDefault()

  jx = $.post('data.asp', 'action=add&' + $(this).serialize())
  console.log("jx=" + jx.status)
  if (jx.status == 404) {
    alert("404 not found")
    return false
  }
  tdstring = "
" + $("input[name='pkeyEmployeeID']").val() + "	" + $("input[name='strFirstName']").val() + "	" + $("input[name='strLastName']").val() + "	" + $("input[name='dtmBirthDate']").val() + "	" + $("input[name='strHomePhone']").val() + "	"
  delstring = '<button type="button" name="action" value="del" onclick="del(this)" fid="' + $("input[name='pkeyEmployeeID']").val() + '">add</button>
'
  $(this).find('tbody').append($(tdstring + delstring).hide().fadeIn('normal'))
})

But jx.status always undefined while running. When execute x=$.post('data.asp').status in Chrome console I can get the code exactly  server returns. Is there any flaws with this snippet?
Comment: try changing input[name='pkeyEmployeeID' to input[name='pkeyEmployeeID'] first in the strings
Comment: @ABUdhay thanks for pointing out. I should add this.
Answer: Since you code runs asynchronously console.log("jx= " + jx.status) runs before the ajax request completes and thus there is no such thing as statusfor jx object and thus it returns undefined. In order to use it , run it inside the .always() function. Also you need to use selector like this $("input[name='pkeyEmployeeID']") instead of $("input[name='pkeyEmployeeID'")
jx.always(function(){
    alert( jx.status)
    if (jx.status == 404) {
      alert("404 not found")
      return false
    }

  })

JSFIDDLE
Answer: jQuery.post ( or $.post) method return a promise object. So if you want to get data from jqXHR, you have to get it from then(), always() or fail() method of promise.
jx = $.post('data.asp', 'action=add&' + $(this).serialize())
jx.always(function(data, textStatus, jqXHR){
    if(jqXHR.status == 200)
    //your code here
})

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.)
http://api.jquery.com/jQuery.ajax/#jqXHR

Demo: https://jsfiddle.net/8jew8kk7/14/


Simultaneous condition on all line elements of a tuple

Question: I have a tuple in the following format:
[(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, None),
 (None, None), (None, None), (None, datetime.datetime(2012, 9, 14, 16, 0))]

I want to iterate over the tuple, check if both components are null and if so remove them from the item — leaving only these:
[(None, datetime.datetime(2012, 9, 14, 15, 0)),
 (None, datetime.datetime(2012, 9, 14, 16, 0))]

What's the neatest way to perform the checks in a single loop at the same time?
Answer: output_list = filter(any, input_list)

Comment: You can use just `any` instead of `lambda t: any(t)`.
Comment: Nice answer, the others work too but this is what I was looking for
Comment: As an extra, what if I only wanted to get rows where all items are None?
Comment: `output_list = filter(lambda t: not any(t), input_list)`
Comment: Using a list comprehension, as shown in other answers, would work unchanged in both Python 2 & 3 -- assuming goal is to actually produce an output list. It might also execute faster.
Answer: Using list comprehension and tuple unpacking:
>>> lst = [(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, None),
... (None, None), (None, None), (None, datetime.datetime(2012, 9, 14, 16, 0))]
>>> [(a,b) for a,b in lst if a or b]
[(None, datetime.datetime(2012, 9, 14, 15, 0)),
 (None, datetime.datetime(2012, 9, 14, 16, 0))]

Answer: I would use a list comprehension and any()
left = [x for x in a if any(x)]
>> [(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, datetime.datetime(2012, 9, 14, 16, 0))]


What does the ~ symbol, placed above a vector, mean

Question: On the wikipedia page for the Poynting Vector, under the section 'time averaged Poynting vector', the ~ symbol is used above some of the vectors.  What does this mean?
Thank you.
Comment: I've seen overlines used for averages and overtildes (what you have) used for Fourier transforms before. I'm not interested in becoming familiar enough with Poynting vectors to try to answer this though.
Answer: I've not seen that decoration given any standardized meaning.
Based on the text description and how it's actually used there, I believe the following is what is meant.
The (time-varying) vector $\mathbf{E}$ is assumed to be sinusoidal function of $t$ -- it is a common trick to replace sinusoidal waves with complex exponentials: e.g.
$$ \cos x = \mathop{\text{Re}} \left( e^{ix} \right)$$
$$ \sin x = \mathop{\text{Im}}\left(e^{ix}\right) = \mathop{\text{Re}}\left( -i e^{ix} \right)$$
The (time-varying) vector $\tilde{\mathbf{E}}$ appears to be defined, along with the constant (with respect to time), complex vector $\mathbf{E}_c$ and real number $\omega$, by the two properties:

$\mathbf{E} = \text{Re}(\tilde{\mathbf{E}})$
$\mathbf{E} = \mathbf{E}_c e^{i \omega t}$
Answer: It usually stands for unit vector:
$$\tilde{v} = \frac{\vec{v}}{|\vec{v}|}.$$
The Poynting vector is a very useful concept in electromagnetism and it's usually denoted by $\vec{S}$.
Cheers!
Comment: Usually $\hat v$, not $\tilde v$ is used for that. And that doesn't look like what's being used on the linked wikipedia page.
Comment: You're right Hurkyl. I confused myself... Please, @user2646276, pay attention to Hurkyl's comment. Cheers!


How to compute $\int_0^a \sin(\tan^{-1}(b\sin\theta))\ d\theta$

Question: How to compute
$$\int_0^a \sin(\tan^{-1}(b\sin\theta))\ d\theta$$
I've tried to rewrite it as
$$\int_0^a\frac{b\sin\theta}{\sqrt{b^2\sin^2\theta+1}}d\theta$$
But I'm still stuck here.
Comment: A "little"... ?
Comment: Wolfram Alpha (http://www.wolframalpha.com/input/?i=integral+of+sin%28arctan%28b+sin+x%29%29+dx) gives:$$\left[-\dfrac{b\ln(\sqrt{-2b^2}\cos x+\sqrt{b^2(-\cos(2x))+b^2+2})}{\sqrt{-b^2}}\right]^a_0$$
Answer: Here one way to go about just using the regular techniques one may learn in a calc class.
The way you have it written: $$b\int_{0}^{a}\frac{\sin\theta}{\sqrt{b^{2}\sin^{2}\theta +1}}d\theta$$ is a good start.
Now, use the identity $\sin\theta = 1-\cos^{2}\theta$
$$b\int_{0}^{a}\frac{\sin\theta}{\sqrt{b^{2}(1-\cos^{2}\theta)+1}}d\theta$$
Let $u=\cos\theta, \;\ du=-\sin\theta d\theta$
$$-b\int\frac{1}{\sqrt{b^{2}(1-u^{2})}}du$$
Let $u=\sin(y)\frac{\sqrt{b^{2}+1}}{b}, \;\ du=\frac{\sqrt{b^{2}+1}}{b}\cos(y), \;\ y=\sin^{-1}\left(\frac{ub}{\sqrt{b^{2}+1}}\right)$
Making these subs now results in everything cancelling down to:
$$-b\int \frac{\sqrt{b^{2}+1}}{b}\cos(y)\cdot \frac{1}{\cos(y)\sqrt{b^{2}+1}}dy$$
$$=-\int dy$$
$$y=-\sin^{-1}\left(\frac{ub}{\sqrt{b^{2}+1}}\right)$$
Revert $u=\cos(\theta)$
$$-\sin^{-1}\left(\frac{b\cos(\theta)}{\sqrt{b^{2}+1}}\right)$$
Now, use the limits of integration to get:
$$\tan^{-1}(b)-\sin^{-1}\left(\frac{b\cos(a)}{\sqrt{b^{2}+1}}\right)$$
Comment: Thanks! This helps, but I believe you missed a $+1$ in the second step, as well as a negative in the third.
Comment: Yes, you are certainly correct. I fixed them Sorry 'bout that.
Comment: How did you get from the $\sqrt{b^{2}(1-u^{2})}$ to $\cos(y)\sqrt{b^{2}+1}$?
Comment: nevermind, I got it. Thanks!
Answer: The change of variables
$$
\cos\theta=\frac{b+1}{b}x
$$
gives
$$
\int\frac{b\sin\theta}{\sqrt{b^2\sin^2\theta+1}}d\theta=-\sqrt{b^2+1}\int\frac{dx}{\sqrt{1-x^2}}.
$$
Let's check it:
$$
\sin\theta\,d\theta=-\frac{b+1}{b}dx,
$$
$$
b^2\sin^2\theta+1=b^2(1-\cos^2\theta)+1=b^2(1-\frac{(b+1)^2}{b^2}x^2)+1=(b^2+1)(1-x^2).
$$
Comment: May you share how you achieved that?


Nginx wildcard DNS, com www, sem www e com subdomínio

Question: Eu tenho um servidor Ngnix com a seguinte configuração:
server {
    listen 80;
    server_name .dominio.com.br;
    root /home/dominio.com.br/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/dominio.com.br-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

Eu configurei o em meu domínio os DNS da seguinte forma:
Registro tipo A com nome @ apontando para o IP do meu servidor
Registro tipo CNAME com nome www apontando para @
Registro tipo CNAME com nome * apontando para @

Se eu entro usando o endereço dominio.com.br vai normal.
Se eu entro usando o endereço www.dominio.com.br ele redireciona para dominio.com.br sem o www (não quero que isso aconteça)
Se eu entro usando o endereço qualquercoisa.dominio.com.br ele acessa normal também sem redirecionar.
Se a pessoa entrar em qualquer um desses links informados acima tudo deve ser apontando para o mesmo aplicativo que esta na pasta /home/dominio.com.br/public
Se a pessoa entrar digitando somente dominio.com.br eu vou redirecionar para www.dominio.com.br
Por que o www está redirecionando para sem www? Podem me indicar onde estou errando ou o que estou deixando passar?
Answer: creio que utilizando da forma a seguir pode solucionar seu problema.
server_name  *.example.org;

Comment: Não funcionou não
Comment: posta como ta seu dns para ficar mais facil
Comment: DNS adicionado na edição da minha pergunta.
Comment: desculpa mas imgs estão bloqueadas aqui na empresa não consigo visualizar ... quando chegar em casa tentarei te ajudar


Solve the following equation in R : $x^{2x}=({2x})^x $

Question:
Solve the following equation in R :
  $x^{2x}=({2x})^x $

My try: by taking logarithm to both sides
$2x\ln{x} = x\ln {2x}$
$\iff \ln x^2 = \ln2x$
$\iff x^2=2x \to x=2$ (accepted)  $or x=0$ (rejected)
But when input $x=-2$ , it seems to be avalid solution!  ; so how can I get it too?
Comment: When you use the logarithm's laws you are assuming $x>0$.
Comment: Ángel Mario Gallegos , Ok , but how can I get the other solution x=-2?
Answer: By using the equality $\ln(a^b) = b\ln(a)$, you're promising that both sides of this equation make sense - so, that $a$ is in the domain of $\ln$, which would mean $a > 0$. Here's a trick to try: let's make sure that the thing inside the logarithm will be positive regardless.
$$x^{2x} = (2x)^x$$
$$(x^2)^x = ((2x)^2)^{x/2}$$
$$x\ln(x^2) = \frac{x}{2}\ln((2x)^2)$$
$$\ln(x^2) = \frac{1}{2}\ln((2x)^2)$$
$$2\ln(x^2) = \ln((2x)^2)$$
$$\ln(x^4) = \ln((2x)^2)$$
$$x^4 = (2x)^2$$
$$x^4 - 4x^2 = 0$$
The solutions of this polynomial equation are $0$, $2$, and $-2$. As you've observed, $0$ can be discarded, so the actual solutions are just $\pm 2$.
Comment: Fantastic solution,  thanks alot
Answer: To simply the approach done by Reese without the fancy get-around of avoiding the case $x < 0$. We know that if $x$ is negative, then $x$ must be a ratio $p/q$ with odd denominator $q$, since otherwise $(2x)^x$ is not real.
You already dealt with the case $x > 0$, because as the comment by Gallegos, your derivation applies.
For $x < 0$, we have $(2x)^x = x^{2x} = (x^2)^x$ is positive, because $x^2 > 0$. So, since $2x < 0$, $p$ is an even integer. This means that $(2x)^x = (-2x)^x$ and hence $(-2x)^x = (x^2)^x = ((-x)^2)^x$. Now, since both sides are non-zero, you can reciprocate each side to get $(-2x)^{-x} = ((-x)^2)^{-x}$, so $-x$ must be a solution to the original problem. And since the only positive solution is $x = 2$, the only negative solution is $x= -2$.
Comment: Good point. ...


load a php page with a cron job

Question: I am using a cron job to reload my httpd service after a subdomain is created. I have the problem that when the reload happens the page that registers the user throws a server error.
I was wondering if I could go around this by having another cron task.
So my logic would be:
httpd reload after a .conf file is created
then take the user back to the DocumentRoot of the main page.
So in usage it would be:
a user registers, then is automatically taken back to domain.com
Comment: You seem to be conflating two processes (user registration - happening in a web page, and apache restarts - happening via cron). The latter cannot influence the former without a lot of deep hackery. You're probably better off figuring out **why** you're throwing server errors and fixing that problem instead...
Comment: well i know why i ge the server error. The register page cannot finish its execution because the httpd reloads.
Answer: "load a php page..."
Does that mean you are trying to invoke this via HTTP?
That's a bad idea to begin with - it means that you've potentially exposed functionality which could be accessed by someone not intended to have access to it.

to reload my httpd service

So it's running with root privileges? That's a really bad idea.
From your description, you seem to be trying to provide a facility for users to create their own domains. It would be much more preferable to use a wildcard vhost definition, then use mod_rewrite to map the dynamically mapped path to a new directory.
But failing that the best way to do this would be to implement it as a setuid root script on the server (with authentication built-in as well as authentication on the web page) and call this from the web page.
....and if the process is started by a web request, then why use cron in the middle? Certainly you'll get privilege seperation if the cron job job is NOT accessing the php script via HTTP, but you're making things much harder than they need to be and introducing delays / load on the server you don't need.
Comment: I have a cron job using incrontab that reloads my httpd service when a user registers.  I have 2 servers mounted to my website server that house the user so depending on what user they are their DocumentRoot won't be the same.  That's the only thing that stopped me from using a wildcard vhost definitely.
Answer: Do a graceful restart on the apache, that will allow childs to finish the current request before reloading the config.
Comment: So this means if a user registers and creates the .conf file via the registration script that invokes the cron job to reload apache; the register script can finishes doing everything it needs to before apache gets reloaded?
Comment: exactly, it will allow the child to 'finish the process its doing now and leaves a note "please restart when you´re done"' - the normal restart would be a "kill everything _now_" (as you mentioned in "The register page cannot finish its execution")
Answer: This is the wrong way to solve this problem.
The right way involves using some kind of software "router".  I don't actually mean an IP router, I mean an URL rewriting type router.
So your application listens to anything on *.domain.com, and then hands it off to the right user's application instead of that tedious apache reloading nonsense.
I did something similar in Nginx recently.
server_name *.domain.com
if ($host ~* "(.*)?\.?domain\.com"){
                set $a $1;
                rewrite ^/?$ /sites/$a/index.html last;
}

Basically, for any subdomain under domain.com, it gets mapped to $DOCROOT/sites/$subdomain/index.html
As a result, to add a new subdomain, all I need to do is create a directory under sites/"subdomain", and it's instantly accessible.

load a php page with a cron job


Sum of product of combinations of a set

Question: I'm trying to get the following sum in terms of n, where the brackets represent nCr of combination theory.
$$
S = \sum_{x=0}^n\sum_{y=0}^{n-x}\sum_{z=0}^{n-x-y}
\begin{pmatrix}
n \\
x \\
\end{pmatrix}
\begin{pmatrix}
n-x \\
y \\
\end{pmatrix}
\begin{pmatrix}
n-x-y \\
z \\
\end{pmatrix}
$$
By simple combination logic, I'm expecting S to be 3^n. Any help is appreciated.
Comment: The sum would be $4^n$, wouldn't it?  This can be seen with repeated application of the binomial theorem.  Rearrange things as $\sum\limits_{x=0}^n\sum\limits_{y=0}^{n-x}\binom{n}{x}\binom{n-x}{y}\color{blue}{\sum\limits_{z=0}^{n-x-y}\binom{n-x-y}{z}}$ and simplify what I've colored blue to be $2^{n-x-y}$ as per the binomial theorem.  Then do the same for the next, $\sum\limits_{x=0}^n\binom{n}{x}\color{blue}{\sum\limits_{y=0}^{n-x}\binom{n-x}{y}2^{n-x-y}}$ and simplify what is blue to be $3^{n-x}$ again via binomial theorem.  One final application will give $4^n$
Comment: Thanks for pointing it out. I have made corrections.
Answer: JMoravitz is correct in his comment.

You can rewrite the summation as:$$\sum_{x+y+z+u=n}\frac{n!}{x!y!z!u!}$$where $x,y,z,u$ are nonnegative integers.
In this we can recognize the number of ways the set $\{1,\dots,n\}$ can be split up in $4$ covering disjoint and distinguishable subsets.
Approaching this differently we can say that for each of the elements of $\{1,\dots,n\}$ there are $4$ options, leading to $4^n$ possibilities.
Comment: You start with names $A,B,C,D$
for $4$ subsets of $\{1,\dots,n\}$. Then to be counted must be the possible *tuples* $(A,B,C,D)$ under the condition that the sets are disjoint and covering. The fact that I ask for tuples (so with an order) instead of e.g. sets $\{A,B,C,D\}$ corresponds with distinguishable.
Comment: The word "partition" is not on its place in your comment. Firstly because elements of partitions are not empty and secondly by partitions we are *not* dealing with tuples. E.g. $\{\{1,2\},\{3\},\{4\},\{5\}\}$ counts for only one partition of $\{1,2,3,4,5\}$. By tuples things change because $(\{1,2\},\{3\},\{4\},\{5\})\neq (\{3\},\{1,2\},\{4\},\{5\})$
Comment: Right, this leads us to the statement I intended to post : this is the number of functions from a set with $n$ elements to a set with 4 elements.
Comment: Yes, that is correct. For every element of the domain there are $4$ candidates as outcome, so there are $4^n$ functions. If the codomain is $\{1,2,3,4\}$ then the sets $A,B,C,D$ can be taken to be the preimages $f^{-1}(\{1\}),f^{-1}(\{2\}),f^{-1}(\{3\}),f^{-1}(\{4\})$.
Comment: What are "distinguishable subsets"?
Comment: OK, so this expression is the number of partitions of a set of size $n$ into 4 (possibly empty) subsets. I agree.
Comment: If this is in your view a proper answer to your question then do not hesitate to accept it.
Comment: Only Penguin can accept the answer. But yes, you deserve an upvote. ;)
Comment: @OlivierRoche Oh,...I wasn't aware of it that it was not the OP that I was talking to. Thank you for your upvote.
Comment: Isn't it that each of the elements `{1, ..., n}` have 3 options, not 4. Since `u = n - x - y - z`. If this is correct, the answer becomes `3^n`.
Comment: Try it out on $n=1$. There are $4$ options. One of the variables  $x,y,z,u$ takes value  $1$ and the others take value  $0$.

Sum of product of combinations of a set


Why does "Alice's Restaurant" sound like Blind Boy Fuller?

Question: Many Blind Boy Fuller songs have a similar riff, including

What's That Smells Like Fish
Rag, Mama, Rag
Truckin' My Blues Away
I Crave My Pig Meat
Get Your Yas Yas Out
Baby You Gotta' Change Your Mind

and Arlo Guthrie's Alice's Restaurant sounds a lot like all of them.  I have to imagine that Guthrie was aware of this.  I don't know much about blues; what's going on here?  Is Guthrie deliberately working in the style of BBF, or in the same style that BBF was working in?   Are the BBF songs all variations on some widely-used blues riff, and Guthrie used the same one?
Web search for <code>"blind boy fuller" "alice's restaurant"</code> finds a number of other people who have noticed the resemblance to What's That Smells Like Fish.
Answer: It's #2:  the BBF songs are all variations on some widely-used blues changes, and Guthrie used the same one. It's often called the "Five Chord Ragtime" progression because it's built around a five-chord sequence of fifths (I-VI7-II7-V7-I). Here it is in C:
C---A7---D7-G7-C---
C---A7---D7---G7---
C---C7---F---Ab7---
C---A7---D7-G7-C---
Not only was it common in early blues repertoire, it is all over Broadway and Tin Pan Alley as well.
My favorite version adds another fifth to the first and last strains:
C-E7-A7---D7-G7-C---
rwf

Why does “Alice's Restaurant” sound like Blind Boy Fuller?


Popups API - Drupal 6.x-2.0-beta0 - Popup is automatically closing

Question: I am trying to add the site contact form in popup using Popups API - Drupal 6.x-2.0-beta0  module. In popups_test.module popups/test page I am able to add the link contact like following
function _popups_test_popups() {
  popups_add_popups();
 $output .= '
'. l("Contact Us", 'contact',
               array( 'attributes' => array('id' => 'test-popup','class'=>'popups')));
return $output;
}

Everything is working fine.
The same thing I am trying to add in a block like following
<?php
popups_add_popups();
print l("Contact Us.", 'contact', array('attributes'=>array('class' => 'popups')));
?>

Using this the popup is opeing and facing following issue,
1. when I submit the contact form without enter any information the popup is disappearing.  Anyone came across the same issue? Any help will be appreciatable
Answer: I have did some analysys and changed the following code its started working
$settings['popups']['originalPath'] = $_GET['q'];

//Replaced with following code

$settings['popups']['originalPath'] = 'popups/test';

There is a function in popups.js which will check the end point of the form. Not sure exactly the cause of the issue.
 return done = (path === Popups.originalSettings.popups.originalPath);


Por que o uso de frames e iframes é considerado uma má prática?

Question: Bom, comecei a desenvolver WEB a pouco tempo, digamos 1 ano.. e aqui na empresa utilizamos muito frames e iframes... sei que na visão de HTML5 os frames estão obsoletos, mas ainda vejo muita gente defendendo o uso deles..

Gostaria muito de saber o por que deles serem motivo de tanto debate, quais seus benefícios e malefícios na hora de se desenvolver..
Se o frame está obsoleto, qual é o seu substituto na visão de HTML5?

Se para o HTML5 os frames estão obsoletos, deve ter uma resposta plausível do porque.
Comment: O psicólogo Abraham Maslow cunhou uma frase que descreve perfeitamente esta situação: 'Suponho que seja tentador, se a única ferramenta que você tem é um martelo, para tratar tudo como se fosse um prego.' Os que gostam de (e confiam nos) frames/iframes irão continuar defendendo o uso.
Comment: frames e iframes são dois conceitos bem diferentes, pena que nenhuma das respostas abordou bem o assunto, inclusive falo do iframe como solução moderna para substituir o frame aqui: http://pt.stackoverflow.com/a/15174/ -Não só o `iframe` tem seu lugar, como é uma alternativa moderna (tanto que ganhou novos poderes com o HTML5). O próprio SOpt e muitos outros sites usam da maneira correta.
Comment: A questão do tópico é: quais seus benefícios e malefícios?... e porque foi considerado obsoleto?
Comment: Relacionado: [Qual é a alternativa moderna aos framesets?](http://pt.stackoverflow.com/q/15151/7261)
Comment: @AndréLeria veja [a revisão](http://pt.stackoverflow.com/posts/29841/revisions) e entenderá o comentário.
Comment: @Bacco Boa observação. Atualizei minha resposta.
Answer: O principal motivo para frames e iframes serem má-prática é que eles não são acessíveis nem indexáveis por motores de busca.
Se um motor de busca começa a "ler" sua página e chega a um iFrame, ele pula esse conteúdo. Ele não consegue entrar na URL e indexar aquela outra página. Ele vai indexar separadamente, então se uma pessoa busca o termo no site de pesquisa, pode cair direto naquele frame e não na página inteira.
Se um leitor de tela passa lendo o conteúdo para o cego, ele também não vai conseguir ler o conteúdo de dentro do iFrame.
Frames não são usados desde que se usa includes ou masterpages. Como o frameset servia para facilitar a manutenção ao ter um mesmo arquivo de topo, menu e rodapé, não faz sentido continuar usando algo inacessível e não-indexável se a linguagem de programação já renderiza a página com toda informação necessária, pegando sempre de um mesmo arquivo.
Ainda assim, são usados no caso de barra do topo de portais ou vídeos do youtube, por exemplo, porque esses players dependem de oturos arquivos como javascript e CSS próprios. Outros casos usam javascript para fazer a chamada ao conteúdo, com ajax por exemplo, mas isso também não é indexável por robôs de busca, nem acessível ao cego (depois do refresh o leitor não repasssa a página toda), mas é mais fácil de manipular com CSS.
Quando faço um site simples, de HTML puro, acabo usando um pouco de PHP só para esses includes. É fácil, simples e toda hospedagem linux roda PHP. Também é fácil de rodar no PC, usando o xampp por exemplo.
Comment: um site simples de HTML puro pode ter includes simples de HTML :)  não precisa ter PHP, senão vai deixar de ser de HTML puro.
Answer: Quando os frames "brilhavam"
Frames foram muito usados em páginas estáticas, onde não é possível fazer include no servidor.
Por exemplo, num site em HTML puro, cabeçalho, rodapé e menu devem ser repetidos em cada página. Isso era um grande problema e o frame resolvia isso perfeitamente, além de economizar no tempo de carregamento.
Softwares como o Dreamweaver mitigavam esse problema ao permitir que gerássemos todas as páginas do site a partir de um template, alterando apenas o conteúdo de cada uma delas.
Hoje, onde qualquer servidor possui pelo menos PHP, é melhor usar algum CMS (Content Management System) ou então simples includes para construir a página e acrescentar automaticamente cada elemento necessário à ela.
Falta de padrão
Frames também são ruins porque quebram o modelo tradicional da web de conteúdo, ao exibir várias páginas independentes numa mesma tela.
Isso pode gerar problemas de usabilidade, principalmente porque pode não ser intuitivo para ele, ainda mais se ele costuma usa os botões voltar e avançar.
Os frames também são pouco intuitivos porque podem misturar conteúdo de domínios diferentes e nem sempre é claro para o usuário que um determinado frame pertence a um site diferente.
Complexidade no desenvolvimento
Em minha própria experiência trabalhando com sistemas bancários vejo que usar frames costuma gerar problemas em algum momento.
O frame dificulta o desenvolvimento em vários aspectos:

Muitas vezes é necessário que um frame comunique-se via Javascript com outro, isso pode causar problemas vários problemas, desde XSS até a mistura de versões e instâncias de bibliotecas Javascript (como jQuery) nos diferentes frames.
Frameworks component-based como JSF ou Struts podem ter comportamentos inesperados quando usados em frames diferentes. pois não são desenhados para isso.
Restrições de segurança nos navegadores geral falhas e comportamentos inesperados.
Redirecionamentos resultantes de ações no sistema não funcionam bem em frames, já que apenas o frame seria redirecionado. Muitas vezes é preciso criar código adicional e complexo para fazer um redirecionamento "global" da página.

Enfim, os cenários acima foram apenas alguns casos que consegui me lembrar.
Sobre indexação em buscadores
Os buscadores conseguiam identificar os diversos frames (se fossem estáticos) ou então pelo menos através de algum mapa do site.
Como já foi mencionado, havia um problema quando um visitante entrava no site direto em uma das páginas que não é o frameset principal.
Nesse caso, muitos sites usavam um Javascript para verificar se o frame principal estava lá e, em caso negativo, redirecionava o usuário para a raiz do site. Lembro-me de que isto costumava gerar vários problemas de usabilidade.
Exceção para iframes
Ao contrário dos frames tradicionais, os iframes possuem alguns casos de uso válidos, sendo o principal permitir a renderização independente de um local da página de forma segura, isto é, sem que o conteúdo daquele local possa interferir com  o restante da página.
Esta técnica é bastante usada em sistemas de propagandas (advertising) digitais, tal como o Google AdSense.
A vantagem do iframe é que ele não deixa o site principal mais lento e não permite que o site altere informações no banner de propaganda e vice-versa.
Na Atlassian, produtos como JIRA e Confluence quando usados na Nuvem não podem ter plugins instalados diretamente como na versão para servidor. Porém, a empresa desenvolveu a tecnologia chamada Atlassian Connect que consiste justamente na possibilidade de estender os produtos adicionando frames em locais estratégicos que recebem somente as informações selecionadas do contexto da página. O restante da comunicação é feito usando RESTful Web Services e Web Hooks.
Portanto, diria que a principal aplicação dos iframes hoje é integração entre diferentes aplicações web de forma segura e independente. Esta abordagem tende a crescer com as novidades do HTML5 que permitem criar um sandbox mais restritivo e, portanto, seguro para determinados usos.
Algumas bibliotecas também usam iframes para simular requisições AJAX quando o navegador não suporta certas funcionalidades. Por exemplo, o JQuery File Upload faz isto para submeter arquivos se o navegador não suporta a tecnologia mais moderna para fazer uploads assíncronos. Entretanto, este uso tende a desaparecer na medida em que os navegadores evoluem.
Answer: Eu não considero uma má prática e sim ferramentas que podem ser utilizadas em determinadas situações, assim como o div e outras tecnologias novas serão utilizadas conforme a necessidade.
Por exemplo, se eu preciso criar um uma intranet simples com poucos recursos e em pouco tempo e que independe de indexação por robôs e não tenho necessidade de utilização de leitor de tela, acredito que o uso de frames e iframes não seja uma má prática.
Ferramentas antigas não deixam de ser ferramentas, apenas se tornam mais uma opção de ferramenta em uma necessidade.
Comment: Acho que aí está a idéia da má pratica, o frame pode ser usado se ... e ... e ... sem problema. Mas se vc já adquiriu prática com outras altenativas elas atendem os casos que o frame não atende e também os que ele atende
Answer: lendo esses posts eu descobri exatamente o que procurava, e agora eu posso dizer que o uso do iframe em algumas situações é melhor. Por exemplo: Conteúdo não acessível/indexado pelos motores de busca, como a Marta citou.
Meu problema foi resolvido com o uso do iframe da seguinte maneira:
Tenho um site que exibe bloco de anúncios e registra a exibição quando a página é carregada. No momento, um cookie é gerado com o id do anúncio e somente é registrado após um tempo, que é determinado pelo tempo médio de visualização das páginas.
O problema é que os bots "bombardeiam" os sites diariamente e eu não conseguia filtrar quem era bot, ou visitante real. Eu até tinha uma média das exibições após várias análises, mas nunca era o real.
Quando modifiquei meu sistema, passei a exibir os banners através de um iframe que incluía o script que estava em uma página separada. Após isso, percebi que o número de exibições caiu drasticamente, passando a registrar as exibições corretamente.
Para mim, o uso do iframe foi perfeito.
Comment: +1 É um bom exemplo de que boa prática é balela. Temos várias ferramentas. Tem quem sabe usar a ferramenta certa pro caso certo, e tem os caras das boas práticas, que só usam marreta. Pra saber a certa, tem que conhecer quais as vantagens e desvantagens de cada uma. E "boa prática" não mostra nada disso, é apenas um sinônimo de "como eu nao sei o que eu tou fazendo, vou seguir os caras famosos".
Answer: Sempre foi errôneo afirmar que os mecanismos de busca não indexam iframes.
O problema é a forma como essa informação foi sendo passada de forma desleixada ao longo dos anos.
Como os framesets são realmente obsoletos, vou comentar somente sobre os iframes.
Sobre indexações, o fato é, um iframe, quando indexado, não traz informação de qual a janela parent. Então nos resultados da busca (google por exemplo), vai aparecer o link direto para a página do iframe. O usuário cai direto nessa página sendo que ela é apenas uma parte integrante de outra janela e pode possuir funcionalidades que dependem da página parent.
O problema era somente isso e foi anunciado recomendações e cautela no uso de iframes e SEO. Só isso. Então alguém passou a informação de forma muito descuidada (foruns, blogs, etc) resumindo que o iframe era má prática e ponto final. Aí estourou a porteira e não teve como conter a boiada.. rsr.. Um copia e repassa o que o outro posta e assim a coisa foi se espalhando.
O iFrame continua sendo útil e recebeu novas funcionalidades no HTML5. É um recurso muito útil para quem sabe usar e toma cautela com as desinformações que espalham pela internet.
No caso das indexações, para resolver o "problema" de abrir diretamente sem a página parent, com um simples JavaScript resolve-se verificando se existe a página parent. Se não existir, redireciona para a página parent e está tudo resolvido. Deve tomar cuidado em especificar o canonical, e outras tags que informam que é uma página que possui outro link para onde a indexação deve apontar. Assim evita ser penalizado pelos motores de busca. Mas esse é apenas um cuidado extra caso o SEO seja realmente importante para a página específica do iframe. Se não tem importância a questão do SEO, apenas ignore.
Answer:
Como já respondido aqui, existem vários problemas técnicos (como, por exemplo, acessibilidade).
Vou colocar aqui diversos possíveis substitutos para frames e iframes:

div: fazendo bom uso de CSS e manipulação do DOM, divs se tornam basicamente framesets mais flexíveis.
canvas: ideal no caso de framesets para multimídia.

Resumindo, os framesets eram opções boas na época em que não tínhamos tanta facilidade com JS e CSS. Hoje já temos soluções bem melhores se fizermos bom uso de todas as ferramentas à nossa disposição.
Answer: No Quesito desenvolvimento acessível, não é que o foco não consegue entrar no iframe, ele entra, porem tem um problema de comportamento que se difere entre navegadores. Fiz isso para resolver o problema.

Entrando no iframe e Saindo do iframe, são partes não visuais do código acessíveis por meio de leitores de tela, onde ao receberem o focus, seja por meio do uso da tecla tab ou Setas de navegação, o mesmo tem o focus direcionado para uma parte do conteúdo interna especifica dentro ou fora do iframe.
Se analisarmos, algumas páginas que dispõe do recurso de acessibilidade, não padronizam seus fluxos, por exemplo, o ideal é que o fluxo não sofra alteração independente da tecla que está sendo usada para navegar.


EditText.getText on a null object reference

Question: estou tentando adicionar registros no Firebase Realtime Database, através de um AlertDialog, porem os componentes EditText não deixam eu abstrair as informações dos componentes.
Segue abaixo o trecho do java..
fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            //Alerta para alterar informações do usuario.
            Snackbar.make(view, "Adicionando um novo registro", Snackbar.LENGTH_LONG)
                    .setAction("Registro", null).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            LayoutInflater inflater = (MainActivity.this).getLayoutInflater();
            builder.setTitle("Registro");
            builder.setView(inflater.inflate(R.layout.fab_registro,null));
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    EditText data , nome , idade , horaExame , procedimento ,qtsPeliculas ;
                    nome = findViewById(R.id.registro_nome);
                    data = findViewById(R.id.registro_data);
                    horaExame = findViewById(R.id.registro_hora);
                    idade = findViewById(R.id.registro_idade);
                    qtsPeliculas = findViewById(R.id.registro_peliculas);
                    procedimento = findViewById(R.id.registro_procedimento);
                    database = FirebaseDatabase.getInstance();
                    DatabaseReference myRef = database.getReference("Paciente");
                    String child = nome.getText().toString();

                    myRef.child(child).child("hora_exame").setValue("enrique");
                    myRef.child(child).child("procedimento").setValue("toráx");
                    myRef.child(child).child("peliculas").setValue("3");

                    myRef.child(child).child("data").setValue("23456");
                    myRef.child(child).child("idade").setValue("42");
                    myRef.child(child).child("nome").setValue("enriqeu");

                }
            });
            builder.setNegativeButton("Cancelar", null);
            builder.create();
            builder.show();
        }
    });

Esse é o Logcat do erro
Attempt to invoke virtual method 'void android.widget.EditText.getText(java.lang.CharSequence)' on a null object reference
    at com.martel.unimedradiologia_controledeestoque.MainActivity$1$1.onClick(MainActivity.java:63)
    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:164)

o xml do layout tá tudo certo, tanto o tipo quanto o id.
Answer: Cara, eu tô achando estranho o edittext sendo instanciado no clique do botão
(EditText nome... nome = findBiewById(...)). O convencional é fazer o instanciamento de cada view no onCreate.
Outra coisa estranha no bloco de código que você enviou é que não foi feito o casting (o correto seria: EditText nome = (EditText) findViewById(...)).
Reveja essas questões que provavelmente estão relacionadas com a causa deste problema.
Comment: Sim, esse trecho está dentro de onCreate. mesmo criando no início do onCreate (fora do botão) dá esse problema. e a respeito do casting não é obrigatório usar, porém tentei com ele tbm e não foi.
Comment: Essas views são do layout que está sendo inflado? Esse layout que está sendo inflado é o mesmo utilizado na MainAcitivity?
Comment: não, criei um layout XML só pro fab no caso
Comment: Teria como você tá postando o layout da MainActivity?
Comment: Nesse momento não, mas. postarei assim que der, posso adiantar que é apenas um ListView com o fab no canto.
Comment: Tranquilo.
Humm, então esse edittext está em um outro layout que não é invocado pela MainActivity? Ou ele está no layout do adapter no ListView?
Comment: ele é inflado no onClick do fab
Comment: Sim, o onclick do fab infla um AlertDialog com um layout personalizado, aí no método setPositiveButton que eu tento abstrair em string os valores dos componentes e enviar pro firebase.
Answer: Você estava tentando recuperar o objeto na sua MainActivity, porem esses objetos não foram inflados no XML da MainActivity você tem que usar a referencia da View inflada para recuperar os objetos referenciados pelo R.id..
Bastou criar uma variável da sua View customizada que estava passando para o AlertDialog e usar o findViewById desse referencia criada e não da MainActivity
fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            //Alerta para alterar informações do usuario.
            Snackbar.make(view, "Adicionando um novo registro", Snackbar.LENGTH_LONG)
                    .setAction("Registro", null).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            LayoutInflater inflater = (MainActivity.this).getLayoutInflater();
            builder.setTitle("Registro");
            View view = inflater.inflate(R.layout.fab_registro,null);
            builder.setView(view);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    EditText data , nome , idade , horaExame , procedimento ,qtsPeliculas ;
                    nome = view.findViewById<EditText>(R.id.registro_nome);
                    data = view.findViewById<EditText>(R.id.registro_data);
                    horaExame = view.findViewById<EditText>(R.id.registro_hora);
                    idade = view.findViewById<EditText>(R.id.registro_idade);
                    qtsPeliculas = view.findViewById<EditText>(R.id.registro_peliculas);
                    procedimento = view.findViewById<EditText>(R.id.registro_procedimento);
                    database = FirebaseDatabase.getInstance();
                    DatabaseReference myRef = database.getReference("Paciente");
                    String child = nome.getText().toString();

                    myRef.child(child).child("hora_exame").setValue("enrique");
                    myRef.child(child).child("procedimento").setValue("toráx");
                    myRef.child(child).child("peliculas").setValue("3");

                    myRef.child(child).child("data").setValue("23456");
                    myRef.child(child).child("idade").setValue("42");
                    myRef.child(child).child("nome").setValue("enriqeu");

                }
            });
            builder.setNegativeButton("Cancelar", null);
            builder.create();
            builder.show();
        }
    });

Comment: Se continuar dando esse erro, cheque suas IDs no XML layout/fab_registro.xml se estão todas lá


Are there arbitrarily long prime gaps in which each number has at least three distinct prime factors?

Question: Definition: Highly composite prime gap
The three composite numbers between the consecutive primes $643$ and $647$ each have at least three distinct prime factors. This is the first occurrence of prime gap of length $> 1$ where each composite number in the gap has at least $k = 3$ distinct prime factors. We call prime gap between $643$ and $647$ as the highly composite prime gap of order $3$. We have the highly composite prime gaps for $k = 3,4,5$ and $6$ as follows:

$k = 3; p = 643$
$k = 4; p = 51427$
$k = 5; p = 8083633$
$k = 6; p = 1077940147$
$k = 7; p = 75582271489$

Question 1: Are there infinitely many highly composite prime gaps of order $k \ge 3$?
Question 2: Given $k$ is there always a highly composite gap of order $k$?
An ordinary linear regression between $k$ and $\log p$ gives a surprisingly strong fit with $R^2 \approx 0.99915$. Although it is based on only six data points, this suggests a relationship of the form $p \sim ab^k$ forsome fixed $a$ and $b$.
Definition: Maximal highly composite gap
The maximal highly composite gap is defined as a prime gap which is longer than any previous gap and each composite in the gap has at least $3$ distinct prime factors.
Update: The longest such gap I have found is of $75$ consecutive composite between the primes $535473480007$ and $535473480083$.
Question 3: Are there arbitrarily long prime gaps in which each composite number in the gap has at least three distinct prime factors?
Update: Posted in MO since it is unanswered in MSE.
Comment: Note that for any two successive prime numbers, $p_a$ and $p_b$, the interval $(p_a^2,p_b^2)$ contains at least one semiprime, $p_ap_b$, which does not have at least three distinct prime factors. So arbitrarily long gaps (of the kind in the question) require arbitrarily large gaps between successive primes. Finding examples of such gaps will require working with very large numbers.
Comment: "Initial term of first run of exactly $n$ consecutive numbers with $3$ distinct prime factors" is tabulated at https://oeis.org/A185032 (but it's not quite what you want, still, the references may point to something).
Comment: I think you meant prime gap of length $\geq 3$ in the second sentence. Otherwise, the composite number between $29$ and $31$ has three distinct prime factors.
Comment: @arbashn Yes right. corrected
Answer: Yes, there are arbitrarily long sequences of integers each of which has at least $3$ prime factors, and the same is true for any $k$ in lieu of $3$.
Given arbitrary positive integers $k$ and $m$, choose integers $n_1,n_2,\ldots,n_m$ with the following properties:

Each $n_i$ has at least $k$ distinct prime factors;
The $n_i$ are pairwise relatively prime.

It is obvious that such a sequence of integers exists (just pick a batch of distinct primes for each $i$, and multiply them).
Now, using the Chinese Remainder Theorem we can find an integer $N$ such that for each $i$, $N \equiv -i \pmod{n_i}$, or in other words $N+i \equiv 0 \pmod{n_i}$. Therefore, the numbers $N+1, N+2, \ldots, N+m$ all have at least $k$ distinct prime factors.
EDIT: the question seems to further demand that the long stretch of "very composite" integers be bookended by actual primes. This proof does not guarantee that, and in fact I suspect this is very hard to guarantee.
Comment: Probably you could get as close as "one end is prime, the other end is either prime or semiprime", using sieve methods.  Beyond that does sound intractable by this approach.
Comment: Yes, it's not super clear but I see what you mean. No, I think it would be quite hard to adjust my proof to handle this. At the ends of a stretch of integers with at least 3 prime factors we will find integers with fewer than 3, but they may well have 2 and I don't see a way to avoid that.
Comment: By Dirichlet's theorem on prime progressions there could be a way to ensure that $N$ or $N+m+1$ is prime. But to force both of them to be primes, you basically need to make a prime gap and that is really much harder than CRT.
Comment: The exact question required the gap to be between two primes. Is there a way to adjust your proof to this?
(this does prove the opposite to what I tried to show in my answer though, which is why I deleted mine, thanks)
Comment: At least we can say that $N$ and $N+m+1$ _can't_ both be prime if $m$ is even...


Como exibir o id como contador de formulário

Question: Estou criando um contador de formulário e gostaria de saber se estou indo no caminho certo ?
Essa é minha query de select
<?php
error_reporting(-1);
ini_set('display_errors', 'On');

//Criar a conexao
$link = new mysqli ("localhost", "root", "", "peixaria");
if($link->connect_errno){
     echo"Nossas falhas local experiência ..";
     exit();
}

         $sql= "SELECT MAX(m.id_pedido)
                FROM mpedido as m WHERE id_pedido
                ORDER BY m.id_pedido DESC
                LIMIT 1";
        $resultado_id= mysqli_query($link,$sql);

?>

e essa é o código php que exibir o id como contador . mas tipo está dando um erro

Notice: Array to string conversion in
  C:\xampp\htdocs\Projetos\pedidos.php on line 61

  Comanda:
                    <?php

                while($row = mysqli_fetch_array($resultado_id)){
                echo ''.["id_pedido"].'';

                }

                ?>

Como eu poderia fazer um contador a partir do id
Comment: Me parece uma duplicata de: http://pt.stackoverflow.com/questions/178905/como-criar-um-campo-contador-em-php-a-partir-do-id-da-tabela
Comment: Pois é ninguém soube responder
Comment: Sinto que todas suas perguntas acabam sendo mal respondidas ou então nem respondidas são... sugiro que de uma lida no tópico [ask] e faca um [tour]
Comment: Na verdade ate onde vejo, todas suas perguntas poderiam se enquadrar na sinalização de "não esta claro o suficientemente"
Comment: Um sei como que é .
Comment: `echo ''.["id_pedido"].'';` você está tornando o `id_pedido` em um array quando coloca entre colchetes. Use `$row['id_pedido']` para mostrar o ID.
Comment: **Array to string conversion** quer dizer que você está mandando imprimir um array como se fosse uma string. Quando houver esse tipo de erro, troque o `echo` por `print_r` para 'debugar' a linha do erro.
Answer: O erro está em:
echo ''.["id_pedido"].'';

Isso não existe.
Quando se usa o código:
while($row = mysqli_fetch_array($resultado_id)){

}

Está dizendo que enquanto houver o linhas, você irá obter a array $row, ou seja deveria de se utilizar:
while($row = mysqli_fetch_array($resultado_id)){

 echo ''.$row["id_pedido"].'';

}

Mas... Isso não irá funcionar também. A razão disso é que não existe o índice id_pedido e o motivo de não existir é porque não há isso definido no SELECT.

Você não precisa usar o while() se o houver o LIMIT 1, se o limite é 1 ele irá executar apenas uma vez.

Correções possíveis:
Método 0. Use index numérico:
Parte do While:
$row = mysqli_fetch_array($resultado_id);
echo ''.$row[0].'';

Método 1. Dê nome aos bois:
Parte do Query:
$sql= "SELECT MAX(m.id_pedido) as ultimo FROM mpedido as m WHERE id_pedido ORDER BY m.id_pedido DESC LIMIT 1";

$resultado_id= mysqli_query($link,$sql);

Logo, agora o SELECT possui um resultado com o nome ultimo para o resultado do MAX(m.id_pedido), que é mais fácil.
Parte do While:
$row = mysqli_fetch_array($resultado_id);
echo ''.$row['ultimo'].'';

Comment: ele vai mostrar o id certo ,? mas tipo toda vez que eu abrir um novo formulário , ele vai exibir o id do formulário anterior e como faço pra dar um incremento +1 pra ele mostrar o id do formulário que está sendo preenchido ?
Comment: Use `$row['ultimo'] + 1`, irá acrescentar 1 ao número. Mas, existe um problema de lógica aí, se duas pessoas abrirem a página vão ver o mesmo número de próximo, sendo que se ambos enviarem somente um dele terá tal número.
Comment: Muito Obrigado .
Comment: Olá @Inkeliz , bem utilizei esse código ele tá mostrando o id anterior ao clicar no novo formulario como faço pra acrescentar um valor a mais assim ele mostra o id que será inserido no formulário .
Answer: Bem sei se entendi bem, mas acredito que você queira algo como:

//Criar a conexao
$link = new mysqli ("localhost", "root", "", "peixaria");
if($link->connect_errno){
 echo"Nossas falhas local experiência ..";
 exit();
}

$sql= "SELECT MAX(m.id_pedido) as ultimo_id FROM mpedido as m";
$resultado_id= mysqli_query($link,$sql);
?>

Como você utilizou o MAX(), ele irá retornar o maior valor do campo id_pedido, logo se este for um campo sequencial ele já irá retornar o valor desejado.
Já no php você deverá fazer assim
Comanda:
<?php
  while($row = mysqli_fetch_array($resultado_id)){
   echo ''.$row["ultimo_id"].'';
  }

?>
Quando você faz este while, recebe uma linha com a informação retornada, porém ela vem como array, logo você precisa acessar o índice que você criou no SQL, no caso "ultimo_id".
Espero que seja isso o que procura.
Comment: eu quero que ele mostre o ultimo_id e acrescente mais um nele assim na tela mostrará o id do formulário aberto e que será inserido .
Comment: Você poderá fazer assim no sql:     $sql= "SELECT MAX(m.id_pedido)+1 as ultimo_id FROM mpedido as m";
Comment: Muito Obrigado mano


Are unpaired samples always generated by independent random variables?

Question: I am confused by the terminology because the term "independent samples" is usually used as a synonym for "unpaired samples". Does this fact mean that unpaired samples are always generated by independent random variables (assuming we have a probability model for our data)?
In other words, let's assume that we have a probability model for our data, that is we have two random variables: $X \sim F_X$, $Y \sim F_Y$. These two random variables correspond to two populations. Next, we consider two i.i.d. random samples $(X_1, \ldots, X_n) \overset{\text{iid}}{\sim} F_X$, $(Y_1, \ldots, Y_m) \overset{\text{iid}}{\sim} F_Y$ where there is no one element of $(X_1,\ldots,X_n)$ such that we can "match" it with some element of $(Y_1, \ldots, Y_m)$. We call such samples unpaired samples (of random variables).
Is it true that $X_i$ and $Y_j$ are independent random variables, $\forall i,j$? Or, equivalently, is it true that $X$ and $Y$ are independent random variables?

P.S. It is well known that paired samples (often called dependent samples) can be generated either by dependent or by independent jointly distributed random variables $X$ and $Y$ (see examples 1 and 2 below). But my question above is about unpaired samples.
Example 1. We have $n$ random people and measure the same characteristic (for example, body weight) in two different moments of time, this will give us $n$ pairs of numbers $(x_1,y_1), \ldots, (x_n,y_n)$. Here we can treat these numbers as realization of two paired samples (of random variables) $(X_1,\ldots,X_n) \overset{\text{iid}}{\sim} F_X$ and $(Y_1,\ldots,Y_n)\overset{\text{iid}}{\sim} F_Y$, which were generated by two dependent jointly distributed random variables $X$ and $Y$.
Example 2. We have $n$ random people and measure two totally different, unrelated characteristics (for example, year of birth and gender), this gives us $n$ pairs of numbers $(x_1,y_1),…,(x_n,y_n)$. Here we can treat these numbers as realization of two paired samples (of random variables) $(X_1,\ldots,X_n) \overset{\text{iid}}{\sim} F_X$ and $(Y_1,\ldots,Y_n) \overset{\text{iid}}{\sim} F_Y$, which were generated by two independent jointly distributed random variables $X$ and $Y$.
If we have any doubts, we can use the chi-squared test of independence to find out if paired samples $(X_1,\ldots,X_n)$ and $(Y_1,\ldots,Y_n)$ are generated by dependent or independent jointly distributed random variables $X$ and $Y$.
Answer: Independence has a formal definition, i.e. $f_{X,Y}(x,y)=f_X(x)f_Y(y)$.
On the other hand, I do not think that the term 'unpaired samples' has a formal statistical definition, and, at the risk of sounding snobbish, it is not a term that I ever hear formally trained (bio)statisticians use. Non-statisticians I work with will use that term, and I encounter the phrase in medical journals; when I encounter it, I assume that the speaker who uses this term is referring to the manner in which the data were collected, i.e. that the measured variables were not matched when they were obtained. So, to me, the term only makes sense in the context of a study design.
However, if I take your question at face value, then I think the answer is 'no': if all you tell me is that $X$ and $Y$ are generated from marginal distributions $F_X$ and $F_Y$, respectively, and you don't tell me anything about the joint distribution of $X$ and $Y$, then I cannot tell you whether they are independent.
Stepping onto my soapbox
The 'unpaired t-test' is another misnomer and a term that I never hear statisticians use, despite the popularity of the term in the literature. Just call it a two-sample t-test.
Stepping off my soapbox
Comment: As you said, the marginal distributions don't tell you about the joint distribution. One can think on this in terms of copula theory.
Answer:
I am confused by the terminology because the term "independent samples" is usually used as a synonym for "unpaired samples". Does this fact mean that unpaired samples are always generated by independent random variables (assuming we have a probability model for our data)?

No, 'unpaired data' is not always independent.
The answer below gives is first an interpretation of how 'unpaired' relates to independence. After that, it gives two examples of how two samples can still be dependent, even when there is no pairing.
Unpairing data
Yes, you do have that a set of pairs of data lose their dependency when you switch the labeling.
The example below shows what happens when we remove the pairing of two correlated variables.
See that point at the top in the left graph, around $x,y = 2,2.5$, if you have unpaired data, then the x-coordinate that is matched with this $y = 2.5$ can suddenly be anything from the distribution of $x$ values.

An unpaired way of dependency
Independence between samples occurs if the outcomes of the two variables are unrelated. So if the probability distribution $f_Y(y)$ is not dependent on the $X_i$ and vice versa if the probability distribution $f_X(x)$ is not dependent on the $Y_i$.
Gathering samples pairwise, such that variables might have some relation, is one practical setting where variables might have a dependency. Due to being sampled within the same unit (e.g. same time, person, place, etc.) the probability distribution of the one element in the pair can be depending on the value of the other element in the pair.
But, there are other ways in which the sample $X$ could influences the density $f_Y(y)$, yet not in terms of a pairwise relationship (or generalized multiple comparisons beyond the number pair/two).
For instance, the parameters in $f_Y(y)$ could depend on $\sum X_i$.
Example consider two i.i.d. random samples of size $n$
$$\begin{array}{rcl}
(X_1, \ldots, X_n) & \overset{\text{iid}}{\sim} & N(0, 1) \\ (Y_1, \ldots, Y_n) & \overset{\text{iid}}{\sim} & N(\mu,\sigma^2) \end{array}\\
\text{with $\mu = \frac{1}{n}\sum_{i=1}^{n}{X_i}$ and $\sigma^2 = \frac{1}{n}\sum_{i=1}^{n}{(X_i-\mu)^2}$}
$$
Non-explicit paired data but related
It might also be that you have two variables that are not explicitly paired, and are not stated as 'paired data', but are dependent when they are combined together based on additional metadata. For example recordings of cloudiness and recordings of rainfall from two different datasets can be 'paired' based on the date and time.
I admit that this point is a bit semantic. But it is just to prevent people from taking data from different data sets, e.g. twitter messages from Donald Trump or Elon Musk, and daily positions of the stock exchange, and assume that there is no dependency if there is no explicit pairing (the pairing is not clear since the data has different dimensions, but you can still relate the data samples in some more complex way than pairing).
Comment: @Rodvi I have removed the passage. Regarding your last question: The independence between samples occurs if the outcomes of the two variables are unrelated. So if $F_Y$ is not dependent on the $X_i$ and $F_X$ not on the $Y_i$. Gathering samples pairwise, such that variables might have some relation (even when it is only remotely), is one practical setting where variables might have a dependency. Another way is when the sample $X$ influences $F_Y$ not in terms of a pairwise relationship, but if the entire sample influences $F_Y$. For instance, the parameters in $F_Y$ could depend on $\sum X_i$.
Comment: @Rodvi I have incorporated it into my question and changed my answer from 'yes' to 'no'.
Comment: You quoted one line from my original post, so I want you to clarify a bit. I also said that "... there is no one element of $(X_1,\ldots,X_n)$ such that we can 'match' it with some element of $(Y_1, \ldots, Y_m)$". Perhaps this is a poor wording, so I will try to rephrase it below.
Comment: Consider two random samples $(X_1, \ldots, X_n) \overset{\text{iid}}{\sim} F_X$, $(Y_1, \ldots, Y_m) \overset{\text{iid}}{\sim} F_Y$ which satisfy the following requirement - for any possible their realizations $(x_1,\ldots,x_n), \,(y_1,\ldots,y_m)$ we will not be able to find at least one element from $(x_1,\ldots,x_n)$ which can be somehow matched (or be paired) with some element from $(y_1,\ldots,y_m)$. *I think we call such realizations $(x_1,\ldots,x_n)$ and $(y_1, \ldots,y_m)$ unpaired/independent samples (or unpaired/independent data).*
Comment: So, using this extra information (i.e. not only information that $(X_1, \ldots, X_n) \overset{\text{iid}}{\sim} F_X$, $(Y_1, \ldots, Y_m) \overset{\text{iid}}{\sim} F_Y$), can we say that the random variables $X_i$ and $Y_i$ are statistically dependent or independent?
Comment: Well, if I understood properly, in the last case we will get unpaired samples $(x_1,\ldots,x_n)$ and $(y_1,\ldots,y_m)$ that were generated by statistically dependent random variables $X$ and $Y$ ($F_Y$ depend on $\sum X_i$). This is an interesting example, thanks.