memory leak? RHEL 5.5. RSS show ok, almost no free memory left, swap used heavily

Question: i encounter a very instresting problem, and it seems that some physical may disapper quietly. i am very puzzled, so if anyone could give some help, I would be very appreciated.
here is my top show:

sort by memory usage

Cpu(s):  0.8%us,  1.0%sy,  0.0%ni, 81.1%id, 14.2%wa,  0.0%hi,  2.9%si,  0.0%st
Mem:   4041160k total,  3947524k used,    93636k free,      736k buffers
Swap:  4096536k total,  2064148k used,  2032388k free,    41348k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
15168 root      20   0 3127m 290m 1908 S 108.2  7.4  43376:10 STServer-1
18303 root      20   0 99.7m  12m  912 S  0.0  0.3   0:00.86 sshd
 7129 root      20   0 17160 7800  520 S  0.5  0.2   5:37.52 thttpd
 2583 root      10 -10  4536 2488 1672 S  0.0  0.1   1:19.33 iscsid
 4360 root      20   0 15660 2308  464 S  0.0  0.1  15:42.71 lbtcpd.out
 4361 root      20   0  186m 1976  964 S  0.5  0.0  82:00.36 lbsvr.out
 3932 root      20   0  100m 1948  836 S  0.0  0.0  30:31.38 snmpd
18604 root      20   0 66212 1184  820 S  0.0  0.0   0:00.06 bash
18305 root      20   0 66112 1136  764 S  0.0  0.0   0:00.03 bash
18428 root      20   0 12924 1076  708 R  1.0  0.0   0:21.10 top
15318 root      20   0 99.7m 1020  996 S  0.0  0.0   0:01.15 sshd
15320 root      20   0 66228  996  788 S  0.0  0.0   0:00.80 bash
 1719 root      20   0 90216  980  884 S  0.0  0.0   0:02.29 sshd
15492 root      20   0 66216  972  780 S  0.0  0.0   0:00.20 bash
15382 root      20   0 90300  964  892 S  0.0  0.0   0:00.57 sshd
 1688 root      20   0 90068  960  852 S  0.0  0.0   0:00.57 sshd
 2345 root      20   0 90068  928  852 S  0.0  0.0   0:00.50 sshd
16175 root      20   0 90216  924  884 S  0.0  0.0   0:00.64 sshd
 2377 root      20   0 90068  908  852 S  0.0  0.0   0:00.44 sshd
 2725 root      20   0 90216  896  884 S  0.0  0.0   0:05.27 sshd
 3929 root      20   0  182m  896  816 S  0.0  0.0   0:43.61 systemInfoSubAg
15986 root      20   0 66216  884  772 S  0.0  0.0   0:00.03 bash

and here is my free shows:

[root@ric ~]# free -m
             total       used       free     shared    buffers     cached
Mem:          3946       3846        100          0          0         48
-/+ buffers/cache:       3796        149
Swap:         4000       2037       1963

here is my iostat shows:

[root@ric ~]# iostat -x -d -m 2
Linux 2.6.37 (ric)         08/16/2011

Device:         rrqm/s   wrqm/s   r/s   w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await  svctm  %util
sda              93.24   222.57 95.44 64.40     4.10     1.12    66.96     1.37   25.46   2.78  44.44
sda1              0.00     0.00  0.00  0.00     0.00     0.00    40.80     0.00    4.00   3.10   0.00
sda2              0.00     0.00  0.00  0.00     0.00     0.00    22.35     0.00   22.52  14.80   0.00
sda4              0.00     0.00  0.00  0.00     0.00     0.00     2.00     0.00   33.00  33.00   0.00
sda5             92.73     7.49 53.39 45.79     0.57     0.21    16.08     0.72   34.67   3.19  31.67
sda6              0.50   215.08 42.06 18.61     3.53     0.91   150.14     0.65   55.27   6.36  38.58

Device:         rrqm/s   wrqm/s   r/s   w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await  svctm  %util
sda             596.02   139.30 248.26 153.73     3.38     1.14    23.02   147.54  482.67   2.49  99.90
sda1              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda2              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda4              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda5            596.02   129.35 244.28 150.25     3.30     1.09    22.79   146.51  488.14   2.53  99.90  this is swap partition
sda6              0.00     9.95  3.98  3.48     0.08     0.05    35.20     1.03  193.60  75.20  56.12

some number got from /proc/meminfo
<code>MemTotal:        4041160 kB
MemFree:          130288 kB
Buffers:             820 kB
Cached:            40940 kB
SwapCached:        82632 kB
SwapTotal:       4096536 kB
SwapFree:        2005408 kB
</code>
uname -a shows:
Linux ric 2.6.37 #4 SMP Fri Jan 14 10:23:46 CST 2011 x86_64 x86_64 x86_64 GNU/Linux
we can find that the swap fs is heavily used. And it consumes much IO resouce. but when we take the RSS colume in top into account, we find the sum of all processes RES is not too much.
so my question is: is this a kernel level leak? or there is something wrong with STServer-1 process? (STServer uses momery pool to cache file data that was swapped out due to no use for a few days).
any comment is welcome. thanks!
udpate 1, slabtop shows

 Active / Total Objects (% used)    : 487002 / 537888 (90.5%)
 Active / Total Slabs (% used)      : 39828 / 39873 (99.9%)
 Active / Total Caches (% used)     : 102 / 168 (60.7%)
 Active / Total Size (% used)       : 145605.37K / 154169.46K (94.4%)
 Minimum / Average / Maximum Object : 0.02K / 0.29K / 4096.00K

  OBJS ACTIVE  USE OBJ SIZE  SLABS OBJ/SLAB CACHE SIZE NAME
133920 133862  99%    0.02K    930      144      3720K avtab_node
 98896  94881  95%    0.03K    883      112      3532K size-32
 74052  73528  99%    1.00K  18513        4     74052K size-1024
 72112  70917  98%    0.44K   9014        8     36056K skbuff_fclone_cache
...

 update 2, add pmap -x 15168 (STServer-1) results

0000000000881000   45116   17872   17272 rw---    [ anon ]
00000000403a1000       4       0       0 -----    [ anon ]
00000000403a2000    8192       8       8 rw---    [ anon ]
...
00000000510aa000       4       0       0 -----    [ anon ]
00000000510ab000    8192       0       0 rw---    [ anon ]
... up to 32 8192

00007f8f2c000000    9832    4004    3964 rw---    [ anon ]
00007f8f2c99a000   55704       0       0 -----    [ anon ]
00007f8f34000000   11992    5068    5032 rw---    [ anon ]
00007f8f34bb6000   53544       0       0 -----    [ anon ]
00007f8f38000000    9768    4208    4164 rw---    [ anon ]
00007f8f3898a000   55768       0       0 -----    [ anon ]
00007f8f3c000000   13064    4080    4024 rw---    [ anon ]
00007f8f3ccc2000   52472       0       0 -----    [ anon ]
00007f8f40000000   11244    3700    3688 rw---    [ anon ]
00007f8f40afb000   54292       0       0 -----    [ anon ]
00007f8f44000000   11824    7884    7808 rw---    [ anon ]
00007f8f44b8c000   53712       0       0 -----    [ anon ]
00007f8f4c000000   19500    6848    6764 rw---    [ anon ]
00007f8f4d30b000   46036       0       0 -----    [ anon ]
00007f8f54000000   18344    6660    6576 rw---    [ anon ]
00007f8f551ea000   47192       0       0 -----    [ anon ]
00007f8f58774000 1434160       0       0 rw---    [ anon ] memory pool
00007f8fb0000000   64628   32532   30692 rw---    [ anon ]
00007f8fb7dfe000    1028    1016    1016 rw---    [ anon ]
00007f8fb8000000  131072   69512   65300 rw---    [ anon ]
00007f8fc0000000   65536   52952   50220 rw---    [ anon ]
00007f8fc40a8000    3328    1024    1024 rw---    [ anon ]
00007f8fc4aa5000    1028    1028    1028 rw---    [ anon ]
00007f8fc4d12000    1028    1020    1020 rw---    [ anon ]
00007f8fc4f15000    2640     988     936 rw---    [ anon ]
00007f8fc53b6000    2816     924     848 rw---    [ anon ]
00007f8fc5bf6000  102440       0       0 rw---    [ anon ]

total kB         3202160  348944  327480

it seems that the kernel swap the old memory (not used for a few days) to swap partition, but the private memory is not too much. if this program leaks memory, then where is it? in swap? in RSS?
update 3, kill STServer-1
I try to kill the STServer-1 process. the use free -m to check the physical memory. but there is still not too much left. about 400MB left. no cache, no buffer yet.
I write a small program to allocate memory, it can only request 400M in the physical memory, after that, swap will be heavily used again.
so should I say that there is a kernel memory leak?
update 4, it happened again!
here is the grep ^VmPea /proc/*/status | sort -n -k+2 | tail shows:

/proc/3841/status:VmPeak:         155176 kB
/proc/3166/status:VmPeak:         156408 kB
/proc/3821/status:VmPeak:         169172 kB
/proc/3794/status:VmPeak:         181380 kB
/proc/3168/status:VmPeak:         210880 kB
/proc/3504/status:VmPeak:         242268 kB
/proc/332/status:VmPeak:          254184 kB
/proc/5055/status:VmPeak:         258064 kB
/proc/3350/status:VmPeak:         336932 kB
/proc/28352/status:VmPeak:       2712956 kB

top shows:

Tasks: 225 total,   1 running, 224 sleeping,   0 stopped,   0 zombie
Cpu(s):  1.9%us,  1.3%sy,  0.0%ni, 51.9%id, 43.6%wa,  0.0%hi,  1.3%si,  0.0%st
Mem:   4041160k total,  3951284k used,    89876k free,     1132k buffers
Swap:  4096536k total,   645624k used,  3450912k free,   382088k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
28352 root      20   0 2585m 1.6g 2320 D 52.2 42.7 267:37.28 STServer-1
 3821 snort     20   0  165m 8320 3476 S 10.2  0.2   1797:20 snort
21043 root      20   0 17160 7924  520 S  0.0  0.2   1:50.55 thttpd
 2586 root      10 -10  4536 2488 1672 S  0.0  0.1   0:28.59 iscsid

iostat shows:

Device:         rrqm/s   wrqm/s   r/s   w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await  svctm  %util
sda              72.50     0.00 351.00  2.50    12.25     0.01    71.02   174.22  213.93   2.83 100.20
sda1              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda2              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda4              0.00     0.00  0.00  0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
sda5             64.00     0.00 50.00  0.00     0.43     0.00    17.76    76.06   59.44  20.04 100.20  swap partition
sda6              8.50     0.00 301.00  2.50    11.81     0.01    79.79    98.16  239.39   3.30 100.20

any idea??
Comment: What is STServer-1 and why is it there? Isn't that strange that the process which should help you with "the memory problem" is the one that causes the memory problem?!
Comment: Post us the output of `slabtop` if that memory leak happens again.
Comment: STServer-1 is our app daemon server. if it is the evil, then why its RSS is only 290m ? that's very strange.
Comment: yeah STServer-1 is doing some serious work on this server. its not just hogging the memory its doing some serious calculations.
can you log this process? check your configuration.
Comment: yes, it is a working process to handle some data distribution. we are now testing its stablity by hundreds of concurrent tcp connection. this is the reason that it consumed much cpu time. the question is: as the RSS of it is small, where is the left physical memory? (less physical memory left causes too much swap)
Comment: May the memory be allocated to the high network usage? So its basically the kernel that is the culprit?
Comment: are there some tools to show the memory that was hold by the kernel?
Comment: might be offtopic: i found it neccessary to free the cached memory every then and there: echo 1 > /proc/sys/vm/drop_caches
Comment: Please provide the output of slabtop sorted by cache size ('c') in slabtop when running. Also, please can you check the size/usage of any tmpfs filesystems you have running.
Answer: Check the VmPeak out of /proc:
<code>$ grep ^VmPea /proc/*/status | sort -n -k+2 | tail
/proc/32253/status:VmPeak:         86104 kB
/proc/5425/status:VmPeak:          86104 kB
/proc/9830/status:VmPeak:          86200 kB
/proc/8729/status:VmPeak:          86248 kB
/proc/399/status:VmPeak:           86472 kB
/proc/19084/status:VmPeak:         87148 kB
/proc/13092/status:VmPeak:         88272 kB
/proc/3065/status:VmPeak:         387968 kB
/proc/26432/status:VmPeak:        483480 kB
/proc/31679/status:VmPeak:        611780 kB
</code>
This should show which pid has tried to consume the most VM resources and should point at the source of the usage.  If you don't see the massive amount of memory in this list then you need to look at the rest of the numbers in /proc/meminfo.
Comment: I had restarted the computer to recheck if this would be happened again.
Answer: Top doesnt show system memory and you maybe using too much memory if you havent tuned network buffers for your use case.
Comment: yes, but after I killed the app process, there still is no physical memory available yet. I can only alloc about 400M around before the system touches the swap.


when I try to paste jar files in lib folder (in eclipse) it gives the following error :

Question: when I try to paste jar files in lib folder (in eclipse) it gives the following error : cannot paste the clipboard contents into the selected elements.
Answer: You cannot paste a .jar file directly until and unless jar files are extracted. Instead do this,
Project -> properties -> Java build path -> libraries -> add external jars
Answer: Firstly do not paste the jars from a ZIP folder. Extract it and then copy and try pasting. It won't give cannot copy clipboard contents into selected elements then.
Answer: Try moving all the JAR contents outside the zip folder that you have just downloaded and then copy all the contents to the specified folder of your eclipse project


Gravar JS no banco de dados com $_POST

Question: Olá.
Tenho um script PHP que executa um INSERT em um tabela do meu banco de dados.
A array $_POST[txt_mensagem] mostrada no código deveria aceitar conteúdos JS, mas ela fica vazia após o submit. Ele deveria aceitar por exemplo um simples alert('ola')
Pesquisei no manual do PHP como aceitar uma cadeia de caracteres inseguras no POST mas não encontrei nada a respeito.
Agradeço antecipadamente a atenção de todos.
<?php
session_start();
include("dados_conexao.php");

if ($_POST)
{
    echo 'valor: ' . $_POST['txt_mensagem'];
    try { // tenta fazer a conexão e executar o INSERT
        $conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha); //istancia a classe PDO
        $comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('$_POST[txt_de]', '$_POST[txt_para]', '$_POST[txt_mensagem]');";
        echo $comandoSQL;
        $grava = $conecta->prepare($comandoSQL); //testa o comando SQL
        $grava->execute(array());
    } catch(PDOException $e) { // casso retorne erro
        echo('Deu erro: ' . $e->getMessage());
    }
}?>

Formulário

<form method="POST" >
   Para:
   <input type="text" name="de">

            Para:
   <input type="text" name="para">

   Mensagem:
   <input type="text" name="mensagem">

   <button type="submit"> Enviar </button>
</form>
Comment: Como é o formulário que envia os dados para esse código?
Comment: Editado, coloquei o HTML na pubicação! obg.
Comment: Faz assim e veja o que retorna: `echo 'valor: ' . $_POST['txt_mensagem'].''; exit;`
Answer: Em primeiro lugar, para detectar se o formulário foi postado, use:
if ($_SERVER['REQUEST_METHOD'] === 'POST'){

O nome do seu campo no formulário é mensagem e não txt_mensagem, por isso a linha echo 'valor: ' . $_POST['txt_mensagem']; não funciona.
Na montagem da QUERY, além dos nomes errados, arrays em uma string devem ser incorporados entre parênteses, e também faltam as aspas nos nomes dos campos...
Substitua:
$comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('$_POST[txt_de]', '$_POST[txt_para]', '$_POST[txt_mensagem]');";

Por:
$comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('{$_POST['de']}', '{$_POST['para']}', '{$_POST['mensagem']}');";

Seu código PHP revisado:
<?php
session_start();
include("dados_conexao.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
     $_POST['de'] = addslashes($_POST['de']);
     $_POST['para'] = addslashes($_POST['para']);
     $_POST['mensagem'] = addslashes($_POST['mensagem']);
    echo 'valor: ' . $_POST['mensagem'];
    try { // tenta fazer a conexão e executar o INSERT
        $conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha); //istancia a classe PDO

        $comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('{$_POST['de']}', '{$_POST['para']}', '{$_POST['mensagem']}');";

        echo $comandoSQL;

        $grava = $conecta->prepare($comandoSQL); //testa o comando SQL
        $grava->execute(array());
    } catch(PDOException $e) { // casso retorne erro
        echo('Deu erro: ' . $e->getMessage());
    }
}
?>

Qualquer dúvida ou erro, referente a essa pergunta, só comentar aqui abaixo.
Comment: Deu certo a resposta acima?
Comment: Caro Allan, agradeço o seu tempo e dedicação em analisar e revisar meu código. Eu implementei da forma que propôs e a página realiza normalmente os INSERTs no banco, porém, o que eu necessito é que a página aceite comandos JS.

Se eu gravo o texto "Olá Mundo", tudo funciona bem, mas se tento gravar "" a página não aceita esta cadeia de caracteres. Grato!
Comment: Tente usar com aspas duplas, pois as aspas simples já estão sendo utilizadas no conteúdo:
Comment: Ou então pode tratar o POST antes com addslashes. Cria uma linha para cada post logo depois do primeiro IF, exemplo: $_POST['de'] = addslashes($_POST['de']);
Comment: Atualizei a resposta. Testa e informa se está funcionando.

Gravar JS no banco de dados com $_POST


How to get the value of a macro with a string containing the macro name?

Question: Is it possible to get the value of a macro with a string containing the name of the #define? Or is it impossible to access a macro through its name after compiling the code?
To point out what I'm after:
#define NAME "VALUE"
char string[5];

// I want the content of string to be changeable to access any define
strncpy(string, "NAME", 4);
fprintf(stderr, "%s\n", string);

I want to have the output: VALUE
EDIT
Due to MOHAMED's reply I found this solution:
#define NAME "VALUE"
char string[5];

strncpy(string, "NAME", 4);

if(strncmp(string, "NAME", 4) == 0) {
    fprintf(stderr, "%s\n", NAME);
}

Comment: Sure: `strncpy(string, NAME, 4);`
Comment: macro's operate solely on text replacement
Comment: @H2CO3 Not so sure: string has only room for 5 chars and copying only 4 results in "VALU"...
Comment: @Jens Right, that should be `char str[6]; strcpy(str, NAME);`... (`strncpy()` is **not** safe anyway...)
Answer: use the macro name directly
strncpy(string, NAME, 4);

You can not edit the content of the string defined by the macro
the macro is evaluated in the compilation phase. the compilator generate a second code (called preprocessor code). this code is generated by the compilator in which the compilator replace the macro by its content.
so if your first code is
#define NAME "VALUE"
char string[5];

strncpy(string, NAME, 4);
fprintf(stderr, "%s\n", string);

the code generated by the compilator will be
char string[5];

strncpy(string, "VALUE", 4);
fprintf(stderr, "%s\n", string);

you can see the preprocessor code with:
gcc -E file.c

Comment: See the added program comment
Comment: You can not edit the content of the string defined by the macro. answer updated
Comment: What is the point of copying 4 characters when "VALUE" is longer?
Answer: No, you can't do that.  Macros are replaced by their replacement text during the preprocessing phase, before the C compiler itself sees the code.


Clone a node programmatically

Question: I am modifying the node content on hook_form_alter() as follows.
  $node = \Drupal\node\Entity\Node::load($nid);
  if ($node) {
    $node->field_p_frontip = $availableip[0];
    $node->save();
  }

I need to clone the node and save it in the  hook_form_alter() submission. How could I do this?
UPDATE

In D6 the node was cloned using the function clone_node_save which uses the node id to clone as clone_node_save($nid,false);, what is the corresponding function in D8 ??
Comment: Question has been updated for clarity, but I can't add an answer to a question on hold. In Drupal 8, any entity can be cloned using `EntityInterface::createDuplicate()`. So in the case of your node object: `$cloned_node = $node->createDuplicate()`. Calling `$cloned_node->save()` will save a new node with a different ID.
Comment: Thanks @jhedstrom :) . Here **$node** is the node id right ?
Comment: Thanks man , it worked :)) . I dont know why its put on hold . CRAP
Comment: I've added this comment as a proper answer now that this is not on hold.
Answer: In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned_node = $node->createDuplicate(). Calling $cloned_node->save() will save a new node with a different ID.
Comment: @innovativekundan indeed. After calling `$cloned_node->save()`, you would simply call `$cloned_node->id()` to get the new node ID.
Comment: Hi @jhedstrom, is there any way to get the nid of recently cloned node ?
Answer:

$nid = 17; // Example node id
$node = Node::load($nid);

if (is_object($node)) {
  $clonednode = $node->createDuplicate();
  // Loop over entity fields and duplicate nested paragraphs.
  foreach ($clonednode->getFields() as $field) {
    if ($field->getFieldDefinition()->getType() == 'entity_reference_revisions') {
      if ($field->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type') == "paragraph") {
        $paragraphs = [];
        foreach ($field as $item) {
          $paragraphs[] = $item->entity->createDuplicate();
        }
        $fieldname = $field->getFieldDefinition()->getName();
        $clonednode->$fieldname =  $paragraphs;
      }
    }
  }

  $clonednode->changed->value = time();

  // Append cloned in the title.
  $clonednode->set('title', 'Cloned - ' . $node->getTitle());

  // Cloned node should be unpublished.
  $clonednode->set('status', 0);

  $clonednode->save();
}

Clone a node programmatically


limit $\lim_{x\to 0^{+}}\sin (e^{\frac{1}{x^2}})$

Question: $$\lim_{x\to 0^{+}}\sin (e^{\frac{1}{x^2}})$$
At first I wanted to write that $$\lim_{x\to 0^{+}}\sin (e^{\frac{1}{x^2}})=\lim_{x\to 0^{+}} e^{\frac{1}{x^2}}=\infty$$ but then I remembered that $sin$ is bounded.
Next I look at $$\lim_{x\to 0^{+}}\sin (e^{\frac{1}{x^2}})\cdot \frac{e^{\frac{1}{x^2}}}{e^{\frac{1}{x^2}}}=\lim_{x\to 0^{+}}\frac{\sin (e^{\frac{1}{x^2}})}{e^{\frac{1}{x^2}}}\cdot {e^{\frac{1}{x^2}}}=1\cdot\infty =\infty$$
But it seems from the graph of the function that the limits are $\{-1,1\}$
Comment: $\lim_{x\to 0^{+}}\sin (e^{\frac{1}{x^2}}) \ne\lim_{x\to 0^{+}} e^{\frac{1}{x^2}}$ because $e^{\frac{1}{x^2}}$ tends to infinity and not zero. I do not think this limit exists.
Comment: Yes but how can I show that the limits are -1 and 1?
Answer: The limit doesn't exist. You can see it doesn't by finding sequences $\{x_n\}$ of positive numbers that converge to zero but such that $\sin (e^{1/x_n^2})$ converges to different numbers.
For instance, let
$$
x_n=\frac1{\sqrt{\log n\pi}}.
$$
Then
$$
\sin e^{1/x_n^2}=\sin e^{\log n\pi}=\sin n\pi=0
$$
for all $n$. Or you can take
$$
x_n=\frac{1}{\sqrt{\log \frac{(4n+1)\pi}2}},
$$
in which case
$$
\sin e^{1/x_n^2}=1
$$
for all $n$.
More generally, given any $r\in[-1,1]$ let $t$ such that $\sin t=r$. Then form
$$
x_n=\frac{1}{\sqrt{\log (t+2n\pi)}},
$$
and we get a sequence with $x_n\to0$ and
$$
\sin e^{1/x_n^2}=\sin t=r
$$
for all $n$. In other words, the function $\sin e^{1/x^2}$ takes all values from $[-1,1]$ in any interval of the form $(0,\varepsilon)$ for any $\varepsilon>0$.


Successfully parsed SimpleXMLElement comparison to 'false' returning 'true'

Question: I got a very awkward and specific issue with a simplexml evaluation.
The code:
$simplexml = simplexml_load_string($xmlstring);
var_dump($simplexml);
var_dump($simplexml == false); //this comparison

var_dump($simplexml) returns the actual structure of my simplexml but the comparison returns 'true' for this specific simplexml, which I can't show the structure because of my contract.
I'm sure that's very specifc issue 'cause I tried other XML strings and the comparison returns 'false'.
$simplexml = simplexml_load_string('test');
var_dump($simplexml); //returns the actual structure
var_dump($simplexml == false); //returns false

I solved the problem using the '===' operator, but I'm not satisfied with just making it work. I want to understand why the '==' operator returns true.
I read about the two operators and the SimpleXMLElement and on my sight it should return 'false' for both operators.
What are the possible reasons for a comparison between a succesfully parsed SimpleXMLElement and the boolean 'false' to return 'true'?
Answer: I this this is a better way to do it using boolean casting (bool)
$simplexml = simplexml_load_string('test');
var_dump($simplexml); //returns the actual structure
var_dump((bool) $simplexml); // Retuns true
var_dump((bool) $simplexml == false); //returns false
var_dump((bool) $simplexml === false); //returns false

Demo : http://codepad.viper-7.com/xZtuNG
=== compares values and type… except with objects, where === is only true if both operands are actually the same object! For objects, == compares both value (of every attribute) and type, which is what === does for every other type.
EDIT 1
See Latest Bug on Something similar https://bugs.php.net/bug.php?id=54547
Comment: My XML has too many levels until the text nodes and that made the parent SimpleXMLElement be considered empty, so the conversion would still return `false` causing the comparison to return `true`. Thanks for your answer
Answer: var_dump($simplexml == false); //returns false

This is expected behavior and it is explained by data comparison via "loose" data typing.  In PHP, NULL, zero, and boolean FALSE are considered "Falsy" values; everything else is considered "Truthy."  Inside the parentheses, PHP performs an evaluation of the expression.  In this case, PHP evaluates a comparison of the named variable OBJECT and the boolean FALSE.  They are not the same, so the return value from the comparison is FALSE and this is what *var_dump()* prints.
You can use this to your advantage in the if() statement.  Example:
$simplexml = SimpleXML_Load_String('test');
if ($simplexml) { /* process the object */ }
else { /* process the failure to load the XML */ }

Answer: Have a look here:
http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
It says that SimpleXML objects created from empty tags evaluate to false. Maybe that's what's going on?
Comment: That's exactly what's going on. I made the tests again and it all made sense now. I just didn't know that a parent tag with no text value that has children tags with/without text values is considered empty. Thanks
Comment: Probably that happens because I got too many levels until the text nodes.


optimizing two variable function.

Question: I want to optimize the following objective function subjected to the constraint as given below:
$$ min \hspace{2mm} ||x||_1+j$$
$$s.t. \hspace{2mm} ||Ax-\frac{1}{j}(b_1+b_2+\ldots +b_k)||_2 \leq \epsilon \\
1\leq j \leq k\\$$
$\text{where}, \\
A=m \times n \hspace{2mm} \text{matrix and is known.}\\
x=n \times 1 \hspace{2mm} \text{vector}\\
b_i, i=1,2, \ldots k \hspace{2mm} \hspace{2mm} \text{all} \hspace{2mm} m \times 1 \hspace{2mm} \text{vector and are known.}\\
j=\text{total numbers of $b_i$}$
where, the $k$ is fixed integer value and $j$ is in between $1$ and $k$. Can anyone please suggest me how can I proceed this further. I want average of $j$ $b_i'\text{s}, i=1,2 \ldots k$ and $x$ which minimizes the given objective function. Any general method to solve the given optimization problem?
Comment: Your formulation is unclear in that $n$ appears as a constant (the number of columns of $A$ and the length of $x$) and as a variable.  Should we assume that $A$ has $n_{\max}$ columns and that you're looking for a solution in which only the first $n$ entries in $x$ are allowed to be nonzero?
Comment: Thanks for your comment. I have updated the question. Please have a look and $x$ has $s \ll n$ non-zero entries.
Comment: I'm still a bit confused here.  You want to minimize over $x$ and $j$, with $n$ and $k$ fixed, right?  Shouldn't the term inside the norm be $(1/j)(b_{1}+\ldots+b_{j})$?
Answer: For each fixed $j$, this is a straight forward problem that can be solved by iterative soft threshholding (ISTA), FISTA, ADMM, IRLS, etc.
Unless the $b_{i}$ vectors have some special property that you haven't told us about, there's no reason to believe that you do better than solving the problem for $j=1$, $2$, $\ldots$, $k$ and then pick the best objective value you found.

optimizing two variable function.


How can I get data from my class sent to my shopping cart

Question: I am building a shopping cart for my app using Provider. I can now push data to my cart from my cart model using a list index. However, I'd like to connect information from a class that I've created to the shopping cart instead. I want users to be able to push on each individual product, read about the fine details, then choose to add to cart there. Then be able to return to the list of products displayed in a lovingly crafted GridView.
Here is my cart model:
class CartModel extends ChangeNotifier {
  // list of items on sale
  final List _shopItems = [
    // [ title, productPrice ]
    ["Brazil", "15.00", "lib/assets/Brazil.png"],
    ["Colombia", "15.00", "lib/assets/Colombia.png"],
    ["Ethiopia", "15.00", "lib/assets/Ethiopia.png"],
    ["Indonesia", "15.00", "lib/assets/Indonesia.png"],
  ];

  // list of cart items
  final List _cartItems = [];

  get cartItems => _cartItems;

  get shopItems => _shopItems;

  // add item to cart
  void addItemToCart(int index) {
    _cartItems.add(_shopItems[index]);
    notifyListeners();
  }

  // remove item from cart
  void removeItemFromCart(int index) {
    _cartItems.removeAt(index);
    notifyListeners();
  }

  // calculate total price
  String calculateTotal() {
    double totalPrice = 0;
    for (int i = 0; i < cartItems.length; i++) {
      totalPrice += double.parse(cartItems[i][1]);
    }
    return totalPrice.toStringAsFixed(2);
  }
}

Here is my cart screen:
Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: ListView.builder(
                    itemCount: value.cartItems.length,
                    padding: const EdgeInsets.all(12),
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.grey[200],
                              borderRadius: BorderRadius.circular(8)),
                          child: ListTile(
                            leading: Image.asset(
                              value.cartItems[index][2],
                              height: 36,
                            ),
                            title: Text(
                              value.cartItems[index][0],
                              style: const TextStyle(fontSize: 18),
                            ),
                            subtitle: Text(
                              '\$' + value.cartItems[index][1],
                              style: const TextStyle(fontSize: 12),
                            ),
                            trailing: IconButton(
                              icon: const Icon(Icons.cancel),
                              onPressed: () =>
                                  Provider.of<CartModel>(context, listen: false)
                                      .removeItemFromCart(index),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),

              // total amount + pay now

              Padding(
                padding: const EdgeInsets.all(36.0),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colors.green,
                  ),
                  padding: const EdgeInsets.all(24),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Total Price',
                            style: TextStyle(color: Colors.green[200]),
                          ),

                          const SizedBox(height: 8),
                          // total price
                          Text(
                            '\$${value.calculateTotal()}',
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),

                      // pay now
                      Container(
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.green.shade200),
                          borderRadius: BorderRadius.circular(28),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: Row(
                          children: const [
                            Text(
                              'Pay Now',
                              style: TextStyle(color: Colors.white),
                            ),
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 16,
                              color: Colors.white,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          );
        },
      ),
    );
  }
}

Here is the class that I'd like to plug into the cart model:
class CoffeeItem {
  const CoffeeItem(
      {required this.id,
      required this.title,
      required this.image,
      required this.description,
      required this.image2,
      required this.quantity,
      required this.productPrice,
      required this.unit});

  final int id;
  final String title;
  final String image;
  final String description;
  final String image2;
  final int productPrice;
  final int quantity;
  final String unit;

  Map toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'price': productPrice,
      'image2': image2,
      'image': image,
      'quantity': quantity,
      'unit': unit,
    };
  }
}

And here is the screen where you push the 'add to cart' button, labled here as 'one-time purchase'
class BeanScreen extends StatefulWidget {
  const BeanScreen(this.coffeeItem, {Key? key}) : super(key: key);

  final CoffeeItem coffeeItem;

  @override
  State<BeanScreen> createState() => _BeanScreen();
}

class _BeanScreen extends State<BeanScreen> {
  /*  DBHelper? dbHelper = DBHelper();

  @override
  void initState() {
    super.initState();
    context.read<CartProvider>().getData();
  }
 */
  @override
  Widget build(BuildContext context) {
    /*  final cart = Provider.of<CartProvider>(context);
    void saveData(int index) {
      dbHelper!
          .insert(
        Cart(
          id: widget.coffeeItem.id,
          productId: index.toString(),
          productName: widget.coffeeItem.title,
          initialPrice: widget.coffeeItem.productPrice,
          productPrice: widget.coffeeItem.productPrice,
          quantity: ValueNotifier(1),
          unitTag: widget.coffeeItem.unit,
          image: widget.coffeeItem.image,
        ),
      )
          .then((value) {
        cart.addTotalPrice(widget.coffeeItem.productPrice.toDouble());
        cart.addCounter();
        const snackBar = SnackBar(
          backgroundColor: Color.fromARGB(255, 113, 52, 255),
          content: Text('Item is added to cart'),
          duration: Duration(seconds: 1),
        );

        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      }).onError((error, stackTrace) {
        print(error.toString());
        const snackBar = SnackBar(
            backgroundColor: Color.fromARGB(255, 219, 56, 110),
            content: Text('Item is all sold out!'),
            duration: Duration(seconds: 1));

        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      });
    } */

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueGrey,
        title: const Text('Good Vibes Coffee Co.'),
        centerTitle: true,
        actions: [
          InkWell(
            onTap: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const CartPage()));
            },
            child: Center(
              child: Badge(
                showBadge: true,
                /* badgeContent: Consumer<CartProvider>(
                  builder: (context, value, child) {
                    return Text(value.getCounter().toString(),
                        style: const TextStyle(color: Colors.white));
                  },
                ), */
                animationType: BadgeAnimationType.fade,
                animationDuration: const Duration(milliseconds: 300),
                child: const Icon(Icons.shopping_bag_outlined),
              ),
            ),
          ),
          const SizedBox(width: 20.0)
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Consumer<CartModel>(builder: (context, value, child) {
              return ListView.builder(
                  itemCount: 1,
                  itemBuilder: (context, coffeeItem) {
                    return Column(
                      children: [
                        Card(
                          color: const Color.fromARGB(255, 255, 249, 193),
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              ClipRRect(
                                borderRadius: const BorderRadius.all(
                                  Radius.circular(10),
                                ),
                                child: Image(
                                  image: AssetImage(widget.coffeeItem.image2),
                                ),
                              ),
                              Center(
                                child: Text(
                                  widget.coffeeItem.title,
                                  textAlign: TextAlign.center,
                                  style: const TextStyle(
                                    fontSize: 30,
                                    fontWeight: FontWeight.w900,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Row(
                          children: [
                            SizedBox(
                                width: MediaQuery.of(context).size.width,
                                child: Text(widget.coffeeItem.description,
                                    overflow: TextOverflow.visible,
                                    textAlign: TextAlign.center,
                                    style: const TextStyle(fontSize: 18))),
                          ],
                        ),
                        Row(
                          children: const [
                            SizedBox(
                              height: 50,
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            const SizedBox(width: 40),
                            Consumer<CartModel>(
                              builder: (context, value, child) {
                                return ElevatedButton(
                                  style: ButtonStyle(
                                      backgroundColor:
                                          MaterialStateProperty.all(
                                              const Color.fromARGB(
                                                  255, 36, 194, 141))),
                                  onPressed: () {
                                    Provider.of<CartModel>(context,
                                            listen: false)
                                        .addItemToCart(coffeeItem);
                                  },
                                  child: const Text('One-Time Purchase'),
                                );
                              },
                            ),
                            const SizedBox(width: 75),
                            ElevatedButton(
                                style: ButtonStyle(
                                    backgroundColor: MaterialStateProperty.all(
                                        const Color.fromARGB(
                                            255, 36, 194, 141))),
                                onPressed: () {
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: ((context) =>
                                            const Subscribe()),
                                      ));
                                },
                                child: const Text('Subscribe')),
                          ],
                        ),
                        Row(
                          children: const [
                            SizedBox(width: 80),
                            Text('\$15.00/12oz'),
                            SizedBox(width: 120),
                            Text('\$15.00/16oz')
                          ],
                        ),
                        Row(children: const [
                          SizedBox(height: 30),
                        ]),
                      ],
                    );
                  });
            }),
          ),
        ],
      ),
    );
  }
}

I have tried just using coffeeItem.title etc. in the list of strings, but apparently, you can't do that. I've also tried to just point my CartModel to CoffeeItem, then tell all of my functions to reach out to that place, but it doesn't like that either.
Answer: You can get your provider cart data ,i hope it will help to you
final po = Provider.of<CartModel>(context, listen: false);
List<CoffeeItem> cofeelist = [];
Map<String, CoffeeItem > _cart = po. _cartItems();
cofeelist = _cart.values.toList();

Comment: This is beautiful. Where do I put this?
Comment: You can put inside start of widget Buildcontext


How to make a deterministic finite state machine that accepts only a string of certain number of 0s?

Question: How to make a deterministic finite state machine that accepts only a string of certain number of 0s? for example, a machine that accepts only 00000 (5 zeros, not 4 or 6 zeros)
Comment: What specifically about this question is giving you trouble?
Comment: @Welbog I have tried to draw the above machine with 6 states: \n    a>0>b>0>c>0>d>0>e>0>f  ( f is the final state, and input 1 take them back to state a). But i think there should be a easier and shorter way.
Answer: It's impossible to build a DFA of less than n+1 states to count n consecutive zeros because the states of your automaton represent its only memory. You need to count to 5 (starting from 0) for example for accepting '00000', and that means 6 states:


Como habilitar CORS para acesso de página web de um domínio diferente, no Asp.Net MVC

Question: Estou desenvolvendo uma aplicação que esta se comunicando com o Checkout do Pag Seguro através da url Web Server https://ws.sandbox.pagseguro.uol.com.br que esta funcionando perfeitamente, após a realização do pagamento o PagSeguro fornece a possibilidade de indicar uma página em minha aplicação para receber o status da transação.
Só que estou desenvolvendo em localhost e o endereço gerado pelo IIS não é um endereço válido para o Sandbox do PagSeguro http://localhost:12345/
Na documentação do Pagseguro pede para utilizar o recurso CORS abaixo
Response.AppendHeader("Access-Control-Allow-Origin", "https://sandbox.pagseguro.uol.com.br");
A pergunta como e onde insiro no código de minha aplicação esta configuração Response.AppendHeader ?
Answer: Para isso você deve instalar um pacote de extensão que faz esse tratamento do CORS.
No console do NUGET digite o seguinte comando:
Install-Package Microsoft.AspNet.WebApi.Cors

Em seu arquivo WebApiConfig coloque o código config.EnableCors(); :
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Configurando o CORS
            config.EnableCors();

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Em sua controller coloque o seguinte atributo:
 [EnableCors(origins: "https://sandbox.pagseguro.uol.com.br", headers: "*", methods: "*")]

ou para futuras chamadas, considerando chamadas de todas origens:
[EnableCors(origins: "*", headers: "*", methods: "*")]

Comment: Realizei todos os procedimentos acima citado e coloquei também no PagSeguro a URL de retorno da minha aplicação " http://localhost/Anuncios/RetornoPagamento " e não funciona, o que estou fazendo de errado.
Comment: Inserir a linha EnableCors aqui ... [EnableCors(origins: "https://sandbox.pagseguro.uol.com.br", headers: "*", methods: "*")]
    public class AnunciosController : Controller{   ...   }
Comment: O erro persiste como "cross-origin"?


Calculo com Javascript dá erro

Question: Galera, o meu programa faz uma série de cálculos, no entanto há um que não funciona e não já não tenho mais ideias de como o resolver.
Os cáclculos são estes:
 function calculaResultado(x){
        console.log(x);
        a = document.getElementById('avInicial' + x).value;
        b = document.getElementById('meta' + x).value;
        c = document.getElementById('avFinal' + x).value;

        let resultado = ((c*100)/b);

        if(b === c){
            resultado = 100; //100%
        } else if (a > c) {
            resultado = 0; // 0%
        }
        else {
            resultado = parseInt(resultado);
        }

        document.getElementById('resultado' + x).value =  resultado;

        calculaMediaFinal();
        ContaObjetivos();
        ContaConcluidos();
        Totalmente();
    }

    function calculaMediaFinal() {
      let soma = 0;
      let contador = 0;
      for (var i = 1; i <= 12; i++) {
        if (document.getElementById('resultado' + i).value) {
          soma += parseInt(document.getElementById('resultado' + i).value, 10);
          contador++;
        }
      }
      var media = soma / contador;
      var inputCuboMedia = document.getElementById('ConcretizaObj');
      inputCuboMedia.value = parseInt(media, 10);
    }

    function ContaObjetivos(){
        let contador = 0;
        for (var i = 1; i <= 12; i++){
            if (document.getElementById('resultado' + i).value) {
          contador++;
        }
    }var inputCount = document.getElementById('ObjDefinidos');
    inputCount.value = parseInt(contador,10);
    }

    function ContaConcluidos(){
        let contador = 0;
        for (var i = 1; i <= 12; i++){
            if ((document.getElementById('resultado' + i).value) == 100) {
          contador++;
            }
        }
        var inputAting = document.getElementById('ObjAtingidos');
        inputAting.value = parseInt(contador,10);
    }

    function Totalmente(){
         def = document.getElementById('ObjDefinidos');
         atin = document.getElementById('ObjAtingidos');

        var valor = atin / def;
        var inputdivisao = document.getElementById('TotalAlcancados');
        inputdivisao.value = parseFloat(valor, 10);
    }

A função que não funciona é a última: resultado é:

Podem ver se descobrem o motivo desse NaN?
Answer: Faltou acrescentar .value ao selecionar os elementos:
def = document.getElementById('ObjDefinidos').value;
atin = document.getElementById('ObjAtingidos').value;

Da forma que está, apenas está selecionando os elementos em si, e não seus valores.
Comment: Muito obrigado pela ajuda, funcionou :)

Calculo com Javascript dá erro


Sample space for 4 consecutive coin flips vs 4 coins flipped at once

Question: I am trying to firm up my understanding of sample space. I am playing with the idea of two random processes, where one realization of each process is
(A): flip a coin 4 times, record the results
(B): flip 4 coins simultaneously, record the results.
The wording suggests that the number of elements in the sample space for experiment (A) is $2^4$ because order of the sequence matters and sample space would look like $\{(TTTT), (HTTT), (THTT) ....\}$
For (B), there is no order, because the coins are flipped simultaneously, so you have no way of imposing an order. So the number of elements in the sample space is 5? $\{ \{T,T,T,T\}, \{H,T,T,T\}, \{H,H,T,T\}, \{H,H,H,T\}, \{H,H,H,H\} \}$
Are these correct interpretations of sample space?
Thanks
Answer: The question is whether the coins are truly identical, or not. If there is any way we can tell the coins apart (scratches, year of minting, weight, asymmetries from being in circulation, spectroscopy of absorption, spectrometry of isotope composition, etc.) they are not identical. For real world coins, it is always possible to tell them apart, so the counting rule in experiment (A) is correct. (Order doesn't matter, here, but identity does. You used order as a surrogate for identity in part A.)
However, it is certainly possible for you to partition the sample space into the five categories you suggested in (B), then assign the appropriate probability to each of the five partitions based on the relative frequencies of the finding each state, which is obtained by analyzing the part (A) results in detail.  In fact, we have a name for that: the binomial distribution, where $n$ is the number of coins but $m$ is the number of heads $(m=\{0,\dots,n+1\}$ has $n+1$ possible outcomes) and each outcome is weighted by its binomial frequency $\binom{n}{m}$ multiplied by the simple (case B) probability of $m$ heads and $n-m$ tails.
But what if they are truly identical? I hear you cry. Truly, truly, truly! As in, nothing we use, nothing we can manipulate, nothing we can identify, not even quantum mechanics, could not tell them apart? Well, then (B) is correct. This is called Bose-Einstein statistics, and yes, it does describe the statistics of photons, among other things.
But real world coins are not that way, and if you insist on counting them using experiment (B) methods, you will be shocked to see that each of the five cases is not represented 1/5 of the time. Experiment B cannot explain that, and the only way you could do it is if you went back to our experiment (A) counting methods and used the binomial distribution.
Comment: Ah interesting, I had not thought about the possibility of probability being equal in case (B), but your answer about transforming the sample space from (A) to (B) helps sort things out for me.


How to return packed array to localparam in Verilog

Question: I have a Verilog localparam and a function declared as:
localparam [7:0] someParam[0:15] = someFunc(8'h10);

function [7:0][15:0] someFunc();
  input [7:0] some_input;

  someFunc[0]  = 8'h00;
  ...
  ...
endfunction

The error I get is: cannot assign packed to unpacked. Any solutions?
Thanks.
Answer: Verilog doesn't support multi-dimensional parameter arrays as stated in:

IEEE1364-1995 § 3.10 Parameters
IEEE1364-2001 § 3.11.1 Module parameters
IEEE1364-2005 § 4.10.1 Module parameters

There is a ways to do it with SystemVerilog. Multi-dimensional declarations are not supported, however a parameter type can be typdef which can be multi-dimensional. The same is true for the return type of a function. See IEEE1800-2012 § 6.20.1 Parameter declaration syntax and § 6.18 User-defined types.
Example:
typedef logic [7:0] someType [16];
localparam someType someParam = someFunc(8'h10);

function someType someFunc (input [7:0] some_input);
  someFunc[0]  = 8'h00;
  // ...
endfunction

Similarly, Verilog does not support double packed arrays (ex [7:0][15:0] someFunc).

IEEE1364-1995 § 10.3.1 Defining a function
IEEE1364-2001 § 10.3.1 Function declarations
IEEE1364-2005 § 10.4.1 Function declarations

SystemVerilog does support double packed arrays. So another solution is:
localparam [15:0][7:0] someParam = someFunc(8'h10);

function [15:0][7:0] someFunc (input [7:0] some_input);
  someFunc[0]  = 8'h00;
  // ...
endfunction

Note: you want [15:0][7:0] which is 16 arrays of 8-bits, not [7:0][15:0] which is 8 arrays of 16-bits.


The probability of a sequence of conditional probabilities with a strict ordering

Question: Let's assume that we are observing a sequence of choices by an individual. Each choice situation is indexed by $t = 1,..., T$ and ordered such that a choice made in $t = 1$ precedes a choice made in $t = 2$. Furthermore, we cannot observe a choice in $t = 2$ unless a particular choice was made in $t = 1$. As an observer, I am interested in calculating the probability of observing a particular sequence of choices made by an individual.
The problem can be structured as a decision tree like this:

It is obvious from the structure of the problem that observing a choice in $t = 2$ is conditional on choosing $S_1$ and that observing a choice in $t = 3$ is conditional on choosing $S_1$ and $S_2$ in $t = 1$ and $t = 2$ respectively. To solve this I thought of using Bayes' theorem, which states that the conditional probability of $A$ given $B$ is:
$$
P(A|B) = \frac{P(B|A)P(A)}{P(B)}
$$
To put this in the context of the current problem, let $A$ be the probability of observing a choice in $t$ and $B$ be the probability that you chose $S$ in $t-1$. Now, $P(B|A) = 1$ because the probability that you chose $S$ in $t-1$ conditional on us observing a choice in period $t$ is known with certainty given the strict ordering on $t$. This means that $P(A|B)$, i.e. the probability of observing a choice conditional on choosing $S$ in the previous period, reduces to the ratio $P(A)/P(B)$. However, there is no guarantee that $P(A) < P(B)$ which means that $P(A|B)$ is no longer bound by the unit interval. Now this creates obvious problems.
Let us look at a numerical example to illustrate the practical implications of this. In $t=1$ the probability of choosing $S$ is .57, in $t=2$ it's 0.34 and in $t=3$ it is .73. The probabilities of the others vary, which can happen, but they are specifically chosen extreme here to illustrate the problem.

Now, applying Bayes' theorem above, I get the following:

Where $P(A|B)$ in period $t-1$ is $P(B)$ in period $t$. Finally, the probability of observing the sequence of choices is the product over the conditional probabilities. However, given the likelihood of getting $P(A|B) > 1$, I am concerned that this may not be the correct application of the theorem or even if it is possible in sequence like this. In practice, the sequence of observed choices can be very long.
Answer: You're incorrect when you state that "there is no guarantee that () < ()". I think the problem boils down to using Bayes' rule, when you really just need conditional probability.
When you mention (), it's important to remember that it is the overall probability of being in the state  at a given time, t. That is, it's the probability of being in , out of all states at time t, even those that didn't originate from . Why? Because () isn't conditional on anything. We don't know anything about what preceded it. (It could have been , or it could have been ~.) Intuitively, I can only reach state  after reaching state  (by the strict ordering). So, the overall probability for  will be less than or equal to the overall probability for .
As an example, when I know that an event strictly precedes another, we can calculate that using conditional probability. For example, Let's say I have a state, , which is sometimes followed by a state . There's no way to reach , except through . Let's further state that  is always preceded by some state, C. C happens at t=0,  at t=1, and  at t=2. C -> B -> A
C occurs as the first step, so there's no conditional probability, we just have (C). Then, () = (|C)*(C). Now, by definition, (|C)*(C) = ( & C). But because we know C already happened if we reached , ( & C) = (). We follow a similar process to find () = (|)*(). You'll note that when we chain these together, we get () = (|)*(|C)*(C). We can continue this chaining for higher values of t.
Comment: Correct. Again, and just to be clear, this only works in this scenario because _C_ always precedes _B_. P(B|C)*P(C) = P(B&C) is just the definition of conditional probability. P(B&C) = P(B) follows from _C_ being a necessary condition for _B_.
Comment: So, if, for example, the probability of state C is $P(C) = 0.6$ and state B is $P(B) = 0.4$, then $P(B|C)*P(C) = P(B&C) = P(B) = 0.4$?
Answer: Interesting problem. You have made small mistakes in defining probabilities. For example:

To put this in the context of the current problem, let $A$ be the probability of observing a choice in $t$ and $B$ be the probability that.....

$A$ and $B$ are events not probabilities. So first lets define events that you are interested in.
Most importantly, we need to make a distinction between the event of choosing a certain action and observing a certain action. In your example you seem to have blurred this distinction. Event $A$ is observing that a particular choice is made but in calculation you are using the probability of the event of choosing that action.
Based on your question, there are in total $2\times3\times3=18$ sequences that are possible. Let's call this set $E$ of possible events. However, the observer can only see $4$ possible events. $3$ events are the ones that have $S_1$ and $S_2$ and are therefore observable, and the fourth event is the invisible sequence. We call this set $V \cup {0}$, where we define ${0}$ as the fourth event described above.
Depending on what is the probability distribution at each time point, you can calculate the probability of any event in set $V$.
Whether you need bayes theorem or not depends on the data you have. Some of the relationships that hold true are following:
$$Pr(S_1|e \in V)=Pr(S_2|e \in V)=Pr(S_1,S_2|e \in V)=1$$
So, $$Pr(e \in V | S_1)= \frac{Pr(S_1|e \in V)\cdot Pr(e \in V)}{Pr(S_1)}$$
Now it is easy to show that $Pr(e \in V) \leq Pr(S_1)$. This is because $$Pr(e \in V) < Pr(V) = Pr(S_1)\cdot Pr(S_2)$$.


Restyling a div element in HTML

Question: I am trying to restyle a div element so that any number is underlined with the click of a button. I am only using javascript not JQuery.
This is partially working but I cannot get past it . At the moment my code will only underscore a unique number and also it will not underscore numbers with more than one digit
My div contains text that reads as follows;
Here there is text that contains numbers such as     number 8 and number 9  or number 18
A button below this should allow the user to click and underscore all numbers in the text

Answer: You need to make a copy of i because, there is no block scope in EC5. Var i is escaping the loop. Meaning it will only underscore the last index of the loop
You can either use a IIFE closure to capture i state
(function (i){
    //assign underscore
})(i)

Or you can try with
for (let i=0; i<=1000; i++){ //assign underscore }

Do notice not all browsers have the let keyword implemented. It is a EC6 feature
Answer: The main problem with your approach, is that after replacing single digit - you're changing the text, so you cannot find number anymore (number is already corrupted with tags).
The standard way is to use regexp, like this:

var v = document.getElementById('txt').innerText;
v = v.replace(/([\d]+)/g, '$1');
document.getElementById('txt').innerHTML = v;

test 1 with 12 some 123 numbers

Comment: Thank you , I like this approach
Answer: Rather than looping over the numbers, you can do it all at once with a regular expression

var myText = document.getElementById('myText');
var text = myText.innerHTML;
myText.innerHTML = text.replace(/(\d+)/g, '$1');

This is some 713 text with 8 a few numbers 99 in it.

The (\d+) matches one more more digits as a capturing group, and the $1 in the replacement string uses the text captured in the group, surrounding it by the underline tags.

Note — the  tag is deprecated, and better practice is to mark something indicating what it is, not how you want it to look, so I would mark it as a number then use a CSS style to make things that are numbers be underlined:
text.replace(/(\d+)/g, '$1'); // JS
.number { text-decoration: underline; }                   // CSS

Comment: Ah! Lashane posted essentially the same thing as I was writing.

Restyling a div element in HTML


Integeroverflow when trying large values - factorization algorithm

Question: I tried to implement Fermat's factorization method (see https://en.wikipedia.org/wiki/Fermat%27s_factorization_method), here's the code:
import math
def is_square(apositiveint):
  x = apositiveint // 2
  seen = set([x])
  while x * x != apositiveint:
    x = (x + (apositiveint // x)) // 2
    if x in seen: return False
    seen.add(x)
  return True

def fermat(n):
    a = math.ceil(math.sqrt(int(n)))
    b2 = a*a - n
    while not is_square(b2):
        a = a+1
        b2 = a*a - n
    return (a-math.sqrt(b2))

So my goal is to factorize the integer n. To do so I define two other variables:
a is defined as the rounded up squareroot of n and b is the difference between  a squared and the number I want to factorize.
The while-loop says, if b2 isn't a square, increment a and define b2 to be the difference between the square of the new a and the number I want to factorize. If b2 is a square then a-squareroot of b2 will be a factor.
The problem works fine when I call the function like this print(fermat(133)) which gives me the answer 7 since it is the lowest prime factor and then I just have to divide 133 by 7 to get 19. So far so good.
But I want to use this code to break an Rsa cryptosystem where I have to factor
n = 507204827540547635003188460612372848602900324231921153214257357007181658245923199433998982097775501221867848469443624920597607769543938674944505236183262115817470130367565835690961161034764686003873284004530093885216278169686899261491680377671371989819332490227245364291020052993400797298847667351869225677060848581769823704347697557065010283805595504356259635995676212493990051132738242918342267376701

But since n is so large I get an overflow error, ofcourse, where it says "int too large to convert to float".
This error made me do some research and I found from decimal import Decimal. Since I am pretty new to programming, I tried to implement it everywhere in the function fermat(n) like this:
def fermat(n):
        a = Decimal(math.ceil(math.sqrt(int(n))))
        b2 = Decimal(a*a - n)
        while not is_square(b2):
            a = Decimal(a+1)
            b2 = Decimal(a*a - n)
        return (Decimal(a-math.sqrt(b2)))

But, after that, I still had the exact same problem. I don't really understand what "Decimal" is supposed to do, evern after reading about it though. Any idea what I could do to make this code work with large n?
I'm sure I have forgot to share some, which I think, important information. But can't remember what at the moment. I will update later if it something I have forgotten. Hope someone can help me, thanks :)
Comment: math.ceil()  returns a float and you have a long int as an input, so it does not fit.
Answer: You will need to redefine your maximum for your computation to run. Look at
import sys
sys.maxsize

and you will see that number is much smaller than your value for n. In your case, I recommend not using math library, and use your own implementation.
The math.ceil() returns a float and it doesn't fit your long integer.


Case/when, ajuda

Question: Dei uma procurada e não consegui achar uma logica pra utilizar nesse caso.
as colunas da tabela são:
COD_DO_USUARIO_ONE | COD_DO_USUARIO_TWO | TEXTO
basicamente estou tentando montar um codigo que consiga identificar quem foi o primeiro a enviar uma certa mensagem no chat particular de um fórum ...
pensei no seguinte Código(que está funcionando)
case
    when lower(texto) like '%oi, tudo bem?%' THEN 'user1'
    else 'user2'
    end AS usuario_forum

Isso me retorna o COD de quem enviou a mensagem, porém, problema é o seguinte:
1 - o texto pode ter sido disparado tanto pele user_one como pelo user_two, então como foi saber quem foi o primeiro a falar?
exemplo:
user 1 - oi, tudo bem?
user 2 - tudo
logica 2
user 1 - oi
user 2 - oi, tudo bem?
Como a logica do primeiro cod estava incorreta pense modifiquei e ficou da seguinte forma:
case
when lower(texto) like '%oi, tudo bem?%' = COD_DO_USUARIO_ONE THEN 'user1'
else 'user2'
end AS usuario_forum

não funciona pois o código do usuário não é igual o texto mencionado, então não consigo igualar os 2
tentei um IF no select, porém não deu certo pelo mesmo motivo.
Alguém tem alguma ideia de como eu posso criar trazer essa coluna com os dados certos?
Comment: Isto que você colocou não tem o menor sentido. O que você quer comparar com COD_DO_USUARIO_ENVIO? Talvez você tenha pensado em encadear dois case/when?
Comment: então, sei que a logica esta errada, não consigo igualar o COD_DO_USUARIO_ONE com o TEXTO ... mas como faço pra saber queme enviou a mensagem ? se foi o user 1 ou o user 2?
Comment: Creio que você só vai conseguir identificar quem primeiro enviou tal texto se sua tabela também incluir um timestamp do envio e supondo que COD_DO_USUARIO_ONE foi quem enviou e COD_DO_USUARIO_TWO foi quem recebeu.
Comment: Não necessariamente, imagina a seguinte texto like "oi, tudo bem" ... agora a seguinte conversa: user_one: oi  user_two: oi, tudo bem? quem enviou foi o two
Comment: Mas a ideia foi boa, no que eu quero deve vim o grosso de tudo, na guerra alguns soldados sempre saem feridos rsrs se tiver alguma outra ideia, ultimo caso vou usar essa que vc disse mesmo.
Answer: Pelo que entendi, seria algo assim:
DECLARE @TABELA_TEMP TABLE
(
    COD_DO_USUARIO INT
    , TEXTO VARCHAR(MAX)
    , DATA_ENVIO DATETIME
)

INSERT INTO @TABELA_TEMP VALUES (1, 'mensagem 1', '2019-02-13 18:12')
INSERT INTO @TABELA_TEMP VALUES (1, 'mensagem 2', '2019-02-13 18:11')
INSERT INTO @TABELA_TEMP VALUES (2, 'mensagem 1', '2019-02-13 18:11')
INSERT INTO @TABELA_TEMP VALUES (2, 'mensagem 2', '2019-02-13 18:16')
INSERT INTO @TABELA_TEMP VALUES (3, 'mensagem 1', '2019-02-13 18:15')
INSERT INTO @TABELA_TEMP VALUES (3, 'mensagem 2', '2019-02-13 18:10')

SELECT TOP 1 MAX(DATA_ENVIO) DATA_ENVIO, COD_DO_USUARIO FROM @TABELA_TEMP WHERE TEXTO = 'mensagem 2' GROUP BY COD_DO_USUARIO ORDER BY DATA_ENVIO DESC

Case/when, ajuda


python regex: match last instance of character followed by certain parttern

Question: I want to edit my code below to catch all strings which END with "_C[any letter/ any number/ or nothing]"
Here is my list
 name_list = ['chrome_PM',
             'chrome_P',
             'chromerocker_C',
             'chromebike_P1',
             'chromecar_CMale',
             'chromeone_C1254',
             'Lukate_Aids_Consumer_P']

for name in name_list:
    counts_tail = re.compile('_C[\da-zA-Z_]*$')
    if counts_tail.search(name):
        print name

output:
chromerocker_C
chromecar_CMale
chromeone_C1254
Lukate_Aids_Consumer_P

expected output:
chromerocker_C
chromecar_CMale
chromeone_C1254

'Lukate_Aids_Consumer_P' should not be included because it doesnt END with '_C', how can I edit my code to handle this bug?
Thanks
Comment: I can't reproduce your code. I get [`chromecar_CMale` and `chromeone_C1254`](http://ideone.com/I5PJd8) only with your current code.
Comment: a pythonic way : matching = [s for s in name_list if "_C" in s]
Comment: What python are you using? I ran your script in python 2.7.6 and the output was only these two:

    `chromecar_CMale`
    `chromeone_C1254`
Comment: strange, I'm using python 2.7
Comment: Sorry guys, I was using an older regex, try it now, it should work.
Answer: You just need to remove the _ from the last character class.
counts_tail = re.compile('_C[\da-zA-Z_]*$')
                                     ^
                                     |

So the correct form would be,
 name_list = ['chrome_PM',
             'chrome_P',
             'chromerocker_C',
             'chromebike_P1',
             'chromecar_CMale',
             'chromeone_C1254',
             'Lukate_Aids_Consumer_P']

for name in name_list:
    counts_tail = re.compile('_C[\da-zA-Z]*$')
    if counts_tail.search(name):
        print name

Because of the _ present inside the character class, it matches _Consumer_P substring in Lukate_Aids_Consumer_P.
Answer: Code
name_list = ['chrome_PM',
             'chrome_P',
             'chromerocker_C',
             'chromebike_P1',
             'chromecar_CMale',
             'chromeone_C1254',
             'Lukate_Aids_Consumer_P']

for name in name_list:
    counts_tail = re.compile('_C(\d|[a-zA-Z])*$') # Added *
                                                  # Unnecessary use of + in both \d and [a-zA-Z] (thanks to @Ashwani Dausodia)
    if counts_tail.search(name):
        print name

Output
chromerocker_C
chromecar_CMale
chromeone_C1254

Comment: For the love of all that is holy, please don't write regex like `(x+)*`.
Comment: @Wazzy, thanks this works but I have edited my original regex, I accidentally posted an older version. Could you try with the new version. thanks!
Comment: Unnecessary use of `+` in both `\d` and `[a-zA-Z]`.
Answer: You find that last occurrence of _ is followed by C or not:
for name in name_list:
    index = name.rfind('_')
    if(name[index+1] == 'C'):
       print name

Remember you can use this only if your string does not contain characters other than digits, letters and _. Otherwise you can use this regex:
'_C(\d|[a-zA-Z])*$'

It means _C followed by zero or more occurrence of \d|[a-zA-Z] (digit or letter) followed by $ (end of line.)
Answer: Use re.compile('_C[^\W_]*$')
You could have simply used re.compile('_C\w*$') but \w includes _ too which is not required. So best way is to use re.compile('_C[^\W_]*$') which excludes everything other than letters, numbers and _.
Demo:
>>> name_list = ['chrome_PM',
         'chrome_P',
         'chromerocker_C',
         'chromebike_P1',
         'chromecar_CMale',
         'chromeone_C1254',
         'Lukate_Aids_Consumer_P']

>>> for name in name_list:
...     counts_tail = re.compile('_C[^\W_]*$')
...     if counts_tail.search(name):
...         print name
...
chromerocker_C
chromecar_CMale
chromeone_C1254

Answer:  name_list = ['chrome_PM',
         'chrome_P',
         'chromerocker_C',
         'chromebike_P1',
         'chromecar_CMale',
         'chromeone_C1254',
         'Lukate_Aids_Consumer_P']

for name in name_list:
    counts_tail = re.compile('_C[\da-zA-Z]*$')
    if counts_tail.search(name):
        print name


Optimizing MySQL SELECT from huge table

Question: I'm doing regular
SELECT * FROM sensor_data_1sec LIMIT 491160, 30

from this table: http://test.dev.brown.sk/sensor_data_1sec.zip
It tooks about 0.06s. I think it is too much. MySQL server is on my PC with Intel Core i7, 8 GB RAM, Windows 7.
Take a look on phpMyAdmin:

Of course it took much little time when it is cached. But is it possible to make it faster uncached?
Comment: The query in your question isn't the same as in the screenshot, you have an extra `WHERE` that doesn't belong.
Comment: What is there in your query to optimize? It has no join conditions, no WHERE test.
Comment: phpMyAdmin says it took 0.0269s, not 0.06s. You seem to have missed a digit. So it's twice as fast as you thought.
Comment: it was another select
Comment: Why did you paste an image if it's not relevant to the question?
Answer: Six hundredths (or two hundredths) of a second is fine. The basic rule is that a user shouldn't be kept waiting for too long and I generally put that at half a second.
Is there something you may have acheived in that 0.06s that you're bothered about, had you known it was going to be that slow? :-)
As an aside, it's unwise to assume a particular order in a result set from a query with no ordering clause. It's also usually preferred to explicitly select columns rather than using *.
Comment: You were right before you edited, phpMyAdmin says 2 hundredths, not 6 hundredths.
Comment: @Barmar, I assumed the php admin was for comparison, OP explicitly states 0.06. However, it doesn't matter whether it's 0.02 or 0.06, it's still blindingly fast. I'll edit to make that clear, thanks.
Comment: I agree with that, +1.
Answer: It's slow because off the deep scan.
An large offset in the LIMIT is bad very bad, if you run an EXPLAIN you will see it needs a temporary table to handle this. And this temporary is proberly disk based because it needs the memory off 491190 records. So you are killing the MySQL performance now.

Optimizing MySQL SELECT from huge table


Internationalization -- impact on other modules?

Question: I installed the internationalization module because the site I'm developing is in a different language, but I can no longer index the site in Drupal's search engine, and Tagadelic isn't working either. I'm assuming all of these issues are somehow related but I'm actually not entirely sure... is there anything specific I need to do when I install the internationalization module to ensure other modules keep working are compatible with other languages?
Comment: Please define "not working". Does tagadelic give you errors? If so, care to post these errors here?
Answer: The i18n modules can have a huge effect on a site, as they integrate with a large number of modules. Many modules for example deal with taxonomy terms and displaying them, so they all need to be compatible with i18n.
The main problem is that many content elements (like menus, taxonomies, ..) are not designed to be translatable or even just language aware. So the i18n project needs to alter a lot of things and build data structures and API's on top of those provided by core.
Also, there have been a number of API changes unfortunately, so it's possible that the modules you mentioned have a broken i18n integration due to that.
You need to provide more details on what exactly isn't working to get more help than this. You can also try to check the issue queue of the broken modules to see if there already is an issue for this and if not, open one.
Answer: With i18n each module might have it's own sort of i18n config that you might have to set.  Some modules you have add i18n settings via config variables in settings.php, some have settings that you have to set for each language that you have installed. Views you might have to include filters for language, or current user's selected language and what not, there can be a ton of configuration depending on what your requirements are. Check out the README of each module and more times than not if it's a widely used module it'll have some section telling you what to do when you're using i18n.
I wish there was a simple answer to this but as it stands it's just a case by case basis per module. The best thing you can do is include i18n from the very beginning when you start building your site, instead of building your site then enabling i18n later. I say this because now you have to deal with all of the configuration and optional development associated with i18n along with fixing errors and maintaining the site, which can be a hassle to juggle.


convergence of sequence.

Question: Let $l^p=\displaystyle \bigg\{\langle x_k\rangle \in \mathbb R^n | \sum^{\infty}_{k=1} |x_k|^p <\infty \bigg\}$
Let $e^k, k\in \mathbb N$ be given by:
\begin{align*}
e^1&=\langle 1, 0, 0,\ldots,0\ldots\rangle \\
e^2&=\langle 0, 1, 0,\ldots,0\ldots\rangle \\
\vdots & \\
e^n&=\langle 0,\ldots,0,1,0,\ldots \rangle
\end{align*}
Show that for all $x\in l^p$
$\displaystyle x=\sum^{\infty }_{k=1} x_k e^k$
If $\displaystyle x=\sum^{\infty }_{k=1} x_k e^k$, I have to show that $\displaystyle x=\lim_{n \to \infty }\sum^{n}_{k=1} x_k e^k$.
Let write $S_n$ as $S_n=\sum^{n}_{k=1} x_k e^k=\langle x_1, x_2,\ldots,x_n,0,\ldots\rangle$
I have to show that $(\forall\epsilon >0)($ there is $n_0\in N)(\forall n\geq n_0)(||x-S_n||_p <\epsilon)$, where $\displaystyle \|x-S_n\|_p=\sqrt[p]{\sum^{\infty}_{k=1}|x_k-S^{k}_{n}|^p}$.
Comment: Maybe something like this:

$x=$,
$S_n=$,
$x-S_n=<0,0,...,0,x_{n+1},x_{n+2},...>$

Since $x\in l^p$, it means that $\sum^{\infty}_{k=1}|x_k|^p$ converges, so there is $n_0\in N$ such that $\forall n\geq n_0$ $\sum^{\infty}_{k=n+1}|x_k|^p<\epsilon ^p$, so $\sqrt[p]{\sum^{\infty}_{k=n+1}|x_k|^p}<\epsilon$ ?
Comment: Yes, that's exactly it!  (You may want to proofread your $\LaTeX$, by the way.  And most people prefer to use angle brackets `\langle \rangle` as delimiters: $\langle x_1, x_2, \dots \rangle$ instead of $$.  See how it looks nicer?)
Comment: OK :) I'm a beginner in Latex, I will improve it with the time. Thanks :)
Answer: Define $\displaystyle \ell^p = \bigg\{ \langle x_n \rangle \in \mathbb R : \sum_{k = 1}^\infty \vert x_k \vert^p < \infty \bigg\}$ and $e_k := \{0, \ldots, 0, \underbrace{1}_{k^{\text{th}} \text{coordinate}}, 0, \ldots\}$.
We want to show that $x = \displaystyle \sum_{k = 1}^\infty x_k \cdot e_k = \lim_{n \to \infty} \sum_{k = 1}^n x_k \cdot e_k$ where $x = \langle x_k \rangle \in \ell^p$.
Let $\varepsilon > 0$. Since $x \in \ell^p$, then $\displaystyle \sum_{k = 1}^\infty \vert x_k \vert^p < \infty$ which means that the tail end goes to zero, that is, there exists $N$ such that if $n > N$, then $\displaystyle \sum_{k = n}^\infty \vert x_k \vert^p < \varepsilon^p$.
If $n > N$, then
\begin{align*}
\bigg \|\sum_{k = 1}^{n - 1} x_k \cdot e_k - x \bigg \| &= \| \langle x_1, x_2, \ldots, x_{n - 1}, 0, 0, \ldots \rangle - \langle x_1, x_2, \ldots \rangle \| \\
&= \| \langle x_n, x_{n + 1}, \ldots \rangle \| \\
&= \bigg(\sum_{k = n}^\infty \vert x_k \vert^p\bigg)^{1/p} \\
&< \varepsilon.
\end{align*}
Conclude that $\displaystyle \sum_{k = 1}^\infty x_k \cdot e_k = \lim_{n \to \infty} \sum_{k = 1}^\infty x_k \cdot e_k = x$ as desired.

convergence of sequence.


How to run php file in javascript without using ajax?

Question: I want to run a php file in javascript when the user refreshes or leaves the page. I'm using a window.onbeforeunload function so if I use ajax, the php file would run without the page reloading. That means the php file would run even when a modal pops up and I don't want that. So I want the php file to run when the user refreshes or leaves the page.
<code>window.onbeforeunload = function (e) {
          $.ajax({
                  type: 'POST',
                  url: 'myfile.php',
                  success: function(response){

                  }
                });
        }
</code>
Answer: Vanilla Javascript have no access to filesystem, you can't run php from it.
Using ajax just allows you to get text content from specified url, same result you can get, when put this url in your browser.
Comment: This is inaccurate. Ajax works both ways...sending and receiving. Also if it is  POST you can't create that in address bar yourself
Comment: @charlietfl of course,  thanks for your addition, i not meant example in the question


How to convert date/time from timezone to another timezone in migration process

Question: I'm using format_date process plugin to import data from external API to drupal 8 node.
The date/time in API is "Asia/Jerusalem" time - 2017-06-24 20:52:55
The date/time from the API is saved in drupal node as it was a UTC 2017-06-24T20:52:55
When the node is displayed (I have "Asia/Jerusalem" timezone defined for me) it shows 2017-06-24 23:52:55
This is the configuration file I used
source:
  fields:
    -
      name: status_updated
      label: 'Status updated'
      selector: status_updated
destination:
  plugin: 'entity:node'
process:
  field_ext_status_updated:
    plugin: format_date
    from_format: 'Y-m-d H:i:s'
    to_format: 'Y-m-d\TH:i:s'
    #timezone: 'Asia/Jerusalem'
    settings:
     validate_format: false
    source: status_updated

I need either to convert the source date first from "Asia/Jerusalem" to "UTC" and then pass it to format_date or change the configuration file in way that it will save the date as 2017-06-24T17:52:55so for users with timezone "Asia/Jerusalem" it will show the correct date/time 2017-06-24 20:52:55
How can I achieve it?
removing the comment for timezone: 'Asia/Jerusalem' not helped
Answer: Timezone conversion is not yet supported - the issue where it's being developed is https://www.drupal.org/node/2883892.
Comment: Thank you. The issue helped me to write my own process plugin based on format date plugin until it will be supported in core.
Answer: Timezone conversion is now supported, with from_timezone and to_timezone format_date plugin parameters.
See updated status of the issue posted by @Mike_Ryan:
https://www.drupal.org/node/2883892
So, above configuration should become:
field_ext_status_updated:
  plugin: format_date
  from_format: 'Y-m-d H:i:s'
  to_format: 'Y-m-d\TH:i:s'
  from_timezone: 'Asia/Jerusalem'
  to_timezone: 'UTC'
  settings:
    validate_format: false
  source: status_updated


Datepicker in Angular Material (Angular 5)

Question: I Am Using Datepicker of Angular Material i want to add some basic custom css class to the datepicker and modify the existing classes of datepicker i had  added classes on google chrome developer tools and it reflects changes but when i add on my component css file it does not reflect changes.For Example i am using datepicker in RegisterComponent if i apply custom css class to datepicker in RegisterComponent.css file it does not reflect changes.Please Help me how can i acheive this to style my datepicker.I am using Angular 5.
Comment: There's a fairly complex guide to using 'Material' exactly by the guidelines, and even more complex guides for Angular specific solutions. If you just want to get the job done short term, chances are you just want to use the `!important` tag in your css definitions.
Answer: Root Cause for this behaviour is because of ViewEncapsulation of angular component, By default all components will be of Emulated. In order to resolve this you can use following approaches depends on your requirement

Change viewEncapsulation value to ViewEncapsultion.None in component metadata, in above case it will metadata of RegisterComponent, But drawback every global styles will bleed in to this components styles
override the class in global style file instead of components style after basic setup of angular material is done such as theming, For Example if its angular cli project use global style.css scaffolded by angular cli
Answer: Writing something similar according to your need in your component css file will do the trick.
<code> /deep/.mat-datepicker-toggle {
    background: url("/assets/icons/calendar.svg") no-repeat !important;
    position: absolute !important;
  }
</code>


Weighted binary cross entropy - create loss function

Question: I'm attempting to create a loss function to control penalization under certain situations.

Basically, I want to penalize when the truth is $1$ but the prediction is $0$.
However, as far as my research went, since my output comes from a sigmoid activation unit, the range can be from $0 \rightarrow 1$. So I thought, I should have a linear formula for it. So first, I came up with this:
$$
{\rm loss} = \Big(atp + a\big((t-1)(p-1)\big)\Big) - (a - 1)\text{ and }a = -1
$$
where: $a$ is alpha, $t$ is the target / truth, and $p$ is the prediction.
So, formally:
$$
{\rm loss} = \Big( \alpha\times{\rm target}\times{\rm prediction} + \alpha \times \big(({\rm target}-1) \times ({\rm prediction}-1)\big)\Big) - (\alpha - 1)  \\
\text{ and }  \\
\alpha = -1
$$
This loss formula creates the table below:

However, I'm stuck! How do I add a variable that will get the effect of penalization that I want?
Answer: It seems like the tensorflow documentation on weighted cross entropy with logits is a good resource, if its a classification case use the above. Any other case makes sure you have the weighted mask and multiple that value in the lost. Since the gradient have the same dimensionality with the output, the math for elementwise multiplication will work out.
To be a little more specific the loss function looks like this:
$$
{\rm loss} = \Big(atp + a\big((t−1)(p−1)\big)\Big)−(a−1)
$$
but since we have the true label either $0$ or $1$, we can divide the loss function into two cases where gt is $0$ or $1$; that looks something like the binary cross entropy function. And the website linked above does exactly something like that where the loss function is penalizing the case where gt label is $1$ but the prediction is $0$. That penalty can be greater or smaller than $1$.
Comment: Welcome to our site.  Because it is not clear how your post answers the question, could you include some explanation of that?
Comment: If you have an answer to the question, please edit the post instead of answering in the comments (you may want to read https://stats.stackexchange.com/tour if you haven't already)
Comment: oh my bad, I did not answer the question at all.

to be a little more specific the loss function looks like this
loss=[atp+a∗((t−1)∗(p−1))]−(a−1)

but since we have the true label either 0 or 1 we can divide the loss function into two case where gt is 0 or one, that looks something like binary cross entropy function. And the website linked above does exactly something like that where the loss function is penalizing the case where gt label is 1 but the prediction is 0. That penalty can be greater or smaller than 1


check if swf file is being played on our own server

Question: I'm creating games creating flash cc(as3). I just create game files and give it to other department and they upload it. I don't have any knowledge on php. My problem is if the file is uploaded to the website, it can be downloaded. My question is if it is possible to restrict it from downloading the file. If not, then restrict the file from being played on their own. I've came across a file which can be played on their server but if I download it and try to run on my desktop, it won't play. How to achieve something like that? I try to connect to server from the swf file before it can be played. If the file get proper key then only the file will play. But to do so I need user permission. Can it be done without user permission? Any help would be appreciated.
Answer: You can check the "running from" location of your SWF by using loaderInfo and its .url method:
This example code below should give you a hint (uses Switch/Case instead of If/Else).
var domainURL : String = loaderInfo.url.split("/")[2]; //get URL from Browser's address bar

switch (domainURL)
{
    //# IF domainURL text is equal to test Case text
    case "www.yourdomain.com":
    case "www.yourotherdomain.com": //If you have more than one Case to test

    start_Game(); //Allow playing.
    break;

    //# ElSE
    default:
    show_Forbiden(); //Forbid playing.
    break;
}

////// Example supporting functions

function start_Game() : void
{
    //Logic for starting the game
}

function show_Forbiden() : void
{
    //Logic for forbidden (ie: display a warning message)
}

Comment: _"Put this into the root class"_ comes with no explanation of why it should be trusted to solve the issue. To a (possible) timeline coder saying _"root class"_ could mean nothing. I hope you don't mind the edit but hopefully it makes a more useful Answer to other future readers.
Comment: is it possible to restrict swf file from decompile without using third party software ?
Comment: @VC.One thanks. I always appreciate that kind of stuff.
Comment: @TheGunners no. SWF with its abccode/bytecode (compiled ActionScript) is an open format, and you will need an external tool to protect your script (I use http://www.kindi.com/ ) and another huge load of work to protect graphic resources.


Adding textboxes to a panel without space between them

Question: I have a panel and a button that adds text boxes to the panel in the following configuration:
|   textbox1 |
| textbox2   |
etc.
The vertical width of each textbox is 27 so what I do is keep track of a y-coordinate and add 30 to it every time I make a new textbox, and put the textbox at that y coordinate. The problem is that after a few textboxes a scrollbar appears, and when I add a new textbox, the origin is taken to be at the top left corner of the visible portion of the panel, not the top left corner of the complete panel. This results in a lot of space between some textboxes. Can anyone help me fix this? Thank you.
Comment: Show some code on how you are adding these TextBoxes.
Answer: I would use a FlowLayoutPanel instead.  Then you could just add your textboxes by doing flowLayoutPanel1.Controls.Add(mytextbox1);
The other option is explained in this post.
Another example is Setting position of a control doesn't seem to work when scroll is 'moved'
Comment: Looks like you beat me too it :P
Answer: Hmm... Even if it seems strange to me that origin "shifts", try aftrr that you added last TextBox add your Delta from its Bounds.Bottom which will generate Top of next TextBox to add.
Hope this helps.
Answer: Have you considered using a Flowlayout Panel?
http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.aspx


SQL Scripted Restore Using With Move - With File & With

Question: I am trying to script a restore of one of our databases and I need to know the correct syntax for using the with file and with move commands
So far I have:
<code>   RESTORE DATABASE Test
   FROM DISK = 'E:\Test_db_BASELINE.BAK'
   WITH FILE = 1
   WITH MOVE 'Test_dat' TO 'C:\MSSQL\v2_Data\Test_Data.MDF',
        MOVE 'Test_log' TO 'C:\MSSQL\v2_Data\Test_Log.LDF', REPLACE
</code>
I get syntax error any ideas?
to put into context I am trying to execute the below to automate a restore where the bak file has a timestamped naming convention:
<code>      --==CHECK IF DB EXISTS IF IT DOES DROP IT

 USE [master]
 IF EXISTS(SELECT * FROM sys.databases where name='SlotLookup')
 DROP DATABASE [SlotLookup]

 --==START THE RESTORE PROCESS
 DECLARE @FileName varchar(255), @PathToBackup varchar(255), @RestoreFilePath varchar(1000)

 DECLARE @Files TABLE (subdirectory varchar(255), depth int, [file] int)

 SET NOCOUNT ON

--==SET THE FILEPATH
 SET @PathToBackup = 'path'

 --insert into our memory table using dirtree and a single file level
 INSERT INTO @Files
 EXEC master.dbo.xp_DirTree @PathToBackup,1,1

 SELECT TOP 1
    @FileName = [subdirectory]
 FROM
    @Files
 WHERE
    -- get where it is a file
    [file] = 1
 AND
 --==FIND THE LOGICAL NAME OF THE BAK FILE FROM THE CHRONILOGICALLY ORDERED LIST
    subdirectory LIKE '%.bak'
 ORDER BY
    -- order descending so newest file will be first by naming convention
    subdirectory DESC

IF LEFT(REVERSE(@PathToBackup), 1) != '\'
BEGIN
    SET @PathToBackup = @PathToBackup + '\'
END

SET @RestoreFilePath = @PathToBackup + @FileName

SELECT @RestoreFilePath

--===BEGIN THE RESTORE TO THE DESIGNATED SERVER
RESTORE DATABASE [SlotLookup]
FROM DISK = @RestoreFilePath
FILE = 1
WITH MOVE 'SlotLookup' TO 'path\SlotLookup.mdf',
MOVE 'SlotLookup_log' TO 'path\SlotLookup_log.ldf'
</code>
get syntax error
Msg 156, Level 15, State 1, Line 48
Incorrect syntax near the keyword 'FILE'.
Msg 319, Level 15, State 1, Line 49
Comment: What is the error message?
Comment: the error message is:  get syntax error Msg 156, Level 15, State 1, Line 48 Incorrect syntax near the keyword 'FILE'. Msg 319, Level 15, State 1, Line 49
Answer: The syntax of a restore backup script with move is like this following:
<code>RESTORE DATABASE [AdventureWorksCopy] FROM DISK = 'c:\mssql\backup\[...]\Backup.bak'
WITH CHECKSUM,
MOVE 'AdventureWorks_Data' TO 'c:\mssql\data\[...]\AdventureWorksCopy_Data.mdf',
MOVE 'AdventureWorks_Log' TO 'c:\mssql\log\[...]\AdventureWorksCopy_Log.ldf',
RECOVERY, REPLACE, STATS = 10;
</code>
What syntax error do you get?
Please include it in the questions


Métodos isUserAMonkey() e isUserAGoat()

Question: Qual a real função dos métodos isUserAMonkey() e isUserAGoat() no  Android SDK? Em que situação elas devem ser usadas?
Comment: http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat
Answer: O primeiro é usado para verificar se o usuário é real ou apenas um mecanismo de testes, onde pode querer ter uma ação diferente. É o que diz em uma pergunta no SO.
Aparentemente o segundo é apenas piada ou algo que pode eventualmente ser usado com easter egg ativo. Isso pode ser conferido em uma pergunta no SO. Então a utilidade real é zero.
Outras piadas.
Comment: Google sendo Google. Olha isso: android.os.Handler#runWithScissors em https://android.googlesource.com/platform/frameworks/base/+/lollipop-release/core/java/android/os/Handler.java#runWithScissors
Comment: `GRAVITY_DEATH_STAR_I`, kkkkkkkkkkkk

Métodos isUserAMonkey() e isUserAGoat()


contextual menus on drupal

Question: I have some questions about Drupal menus. I am interested to have a Contextual Menu in sense that its links change depending where the user is.
I have a Taxonomy Menu and I would like to show in the menu only the term links to the level where the user was. For instance,

Product

cat1
cat2

cat2.1
cat2.2

cat3

If I have the taxonomy shown above, if I click on product the menu should list only cat1, cat2 and cat3 but if I click cat2 menu should list only cat2.1 and cat2.2
How can do this on Drupal?
Thanks in advance!
Comment: If you're going to list `cat1, cat2, cat3` by visiting `Product` taxonomy term page, you need to define the path for `product/catX` and `product/catX/catXx/` as well. You can do that with Pathauto - here is [an example](http://drupal.stackexchange.com/a/82157/16739) of Pathauto settings + integration with views.
Answer: If you mean literally only show that level, you can do this with Menu Block module using the Make the starting level follow the active menu item option.
If you mean that only that level should be expanded, you can do it like this: go to edit your Taxonomy Menu vocabulary. Under Taxonomy menu -> Structure options, uncheck Auto expand menu items.
But I'm not sure if Taxonomy Menu can be used with Menu Block like this.

contextual menus on drupal


Series, proving the $n$-th element

Question: I'm trying to show that the relationship between two successive elements in the series $$1, 2, 4, 8...$$ can be described a $ a_{n} = a_{n-1} + a_{n-1}$.
I'm interested in the number of combinations that give an even amount of tails when a coin is flipped $n$ times.
If I flip a coin $1$ time, it's either going to be heads or tails. So I have $1$ combination where the amount of tails is even (which is when I get heads because $0$ is even).
For $2$ flips I have $2$ combinations which matches an even amount of tails:
HH, HT, TH, TT
And for 3 flips I have $4$ combinations which gives me an even amount of tails:
HHH, HHT, HTH, THH, TTH, THT, HTT, TTT
This series takes the shape of $1, 2, 4, 8, 16...$ and so on, where each element is the previous element multiplied by $2$.
What I'm trying to do is simply put words on why this relationship works the way it does. In other words, how can I be $100\%$ sure that there are twice as many combinations with an even amount of tails for 100 flips when compared to $99$ flips.
Help is appreciated!
Answer: Well, you have the right idea : for $n$ flips, there are $2^n$ combinations.
For instance, for 3 flips you get HHH, HHT, HTH, THH, TTH, THT, HTT, TTT - that is $2^3 = 8$.
In your case, you only want those who gives you an even number of tails, which is half the previous number : $\frac{2^3}{2} = 2² = 4$, because the distribution is homogenous. Indeed, there is 50% chance of getting tails, and 50% chance of getting heads when you toss the coin, assuming it is perfectly balanced, no one cheats, etc.
So, you have a geometric progression that goes like this :
$$a_{n+1} = 2a_n$$ with $a_0 = 0$. (if you flip 0 times the coin, well...)
Answer: When you flip a coin $n$ times, each flip can have two outcomes - $H$ or $T$. Since each flip is independent of the rest, the number of outcomes possible are
$$2\times2\times\cdots\times2=2^n$$
Now, exactly half of these outcomes must have an even number of tails. This can be understood as follows.
For the first flip, you can get a $H$ or a $T$ with equal probability. Clearly, half ($1$) of the number of possible outcomes ($2$) have an even number of tails.
Suppose after the $k^{th}$ flip, you have exactly half of outcomes with an even number of tails.
For the $(k+1)^{th}$ flip, there is an equal probability of getting a $H$ or a $T$. Thus, for every outcome, we would get two outcomes, each corresponding to an even and odd number of tails. Hence, the number of outcomes having an even number of tails after the $(k+1)^{th}$ flip will be half the total number of outcomes.
So, using mathematical induction, we can say that after $n$ flips, the number of outcomes having an even number of tails will be
$$\frac{2^n}2=2^{n-1}$$
Now, if
$$a_n=2^{n-1}$$
It is clear that
$$a_{n+1}=2^n=2.2^{n-1}=2^{n-1}+2^{n-1}=a_n+a_n$$
Comment: how exactly did you get that
$a_{n+1} = 2^n$
?
Comment: @user3067688 $a_n=2^{n-1}$. Replace $n$ with $n+1$. You get $a_{n+1}=2^n$
Comment: Okay thanks, could you elaborate a little bit more on this part?
"Hence, the number of outcomes having an even number of tails after the (k+1)th(k+1)th flip will be half the total number of outcomes."

There are 4 cases right?
Comment: @user3067688 Yes, there are four cases. After the $k^{th}$ flip, supposing the hypothesis is true, we have $2^{k-1}$ outcomes with an even number of tails, and $2^{k-1}$ outcomes with an odd number of tails. For each of these $2^k$ outcomes, we get $2$ outcomes after the $k^{th}$ flip. From the first set of $2^{k-1}$ outcomes, now exactly half will have an even number of tails, i.e., $2^{k-2}$. Likewise for the second set. Thus, the total number of outcomes after the $(k+1)^{th}$ flip will be $2.2^{k-2}=2^{k-1}$

Series, proving the $n$-th element