Ajuda com While em c++

Question: Fiquei curioso com o seguinte código em c++.
int main(int argc, char** argv) {
    float n1,n2,n3,n4;
    int i = 1;
    char nomeAluno;

    printf("Digite seu nome: ");
    scanf("%s", &nomeAluno);
    while(i<5){
        printf("Digite sua %dº nota: ", i);
        scanf("%f", &n1);

        i++;
    }
    printf("%.1f \n", n1);
    printf("%.1f \n", n2);
    printf("%.1f \n", n3);
    printf("%.1f \n", n4);
    return 0;
}

Tenho a seguinte dúvida, eu não sei se é possível, mas se for como eu consigo fazer com que dentro do while a próxima digitação da nota caia dentro do n2? Porque dessa forma que eu fiz ele fica armazenando só no n1(Claro que por conta do loop).
Comment: A declaração `char nomeAluno;` define a variável que conterá **um** único caractere (neste caso o formato é %c) e não uma string. Para uma string, que em C é um array de caracteres com o caractere terminador '\0', use `char nomeAluno[40];` e na função scanf não coloque o &. Aliás em C++ você deveria utilizar a classe string. Quanto às notas você colocou a leitura dentro de um loop e portanto a cada nova leitura você sobrescreve o que foi lido na leitura anterior. Ou faça leituras separadas para cada uma das notas ou utilize um array de notas (`float nota[4];`).
Comment: Não me atentei a essa diferença entre usar %c e %s, sobre o & não sabia que era melhor usar um string. Vou estudar mais de qualquer forma e sou grato pelos conselhos. :)
Answer: Você pode usar vetores. Para declara-los, é simples, basta digitar a variável e logo em seguida entre chaves [] a quantidade de posições que vai receber a variável float n[4], aqui eu declarei uma array do tipo float de 4 posições (lembrando que C++ os valores de um vetor iniciam com 0).
Um exemplo prático de como ficaria o seu código:
int i = 0;
float n[4];
while(i<4){
    printf("Digite sua %dº nota: ", i+1);
    scanf("%f", &n[i]);

    i++;
}
printf("%.1f \n", n[0]);
printf("%.1f \n", n[1]);
printf("%.1f \n", n[2]);
printf("%.1f \n", n[3]);
return 0;
}

Observe que eu declaro int i = 0, e que no printf, eu adiciono i + 1 para imprimir da forma que tem que ser mostrada para o usuário, este valor alterará apenas na impressão, e não somará na variável i.

Para ver mais sobre, recomendo estes dois links:
http://linguagemc.com.br/vetores-ou-arrays-em-linguagem-c/
https://www.inf.pucrs.br/~pinho/LaproI/Vetores/Vetores.htm
Comment: Muito obrigado, vou utilizar vetores então. E grato pelos links. :D
Comment: De nada amigo, teve uma errata, em `while()` eu coloquei `while(i<5)`, na verdade é `while(i<4)` e leia-se `enquanto i for menor que 4`, pois temos apenas 4 posições para serem preenchidas, e a variável `i` inicia com `0`, agora está correto. Lembrando que é perigoso em um programa dar valores a um vetor maior que ele mesmo, você está alterando a memória que pode estar sendo usada por outra instancia, variável, etc.

Ajuda com While em c++


Como traduzir as mensagens de erro do validation summary errors asp .net?

Question: Não acho um arquivo que me traga as strings de mensagem de erro para serem traduzidas, as de annotation estão bem, somente essas que trazem erros mais complexos, como

Passwords must have at least one digit ('0'-'9').
Comment: Poderia explicar melhor essa parte: **as de annotation estão bem, somente essas que trazem erros mais complexos**?
De onde veio esse erro?
Comment: não há nenhum erro, preciso apenas traduzir as mensagens de erro para portugues, as do tipo '[Required]' e '[StringLength(10)]' consegui traduzir por exemplo, outras não pois não achei aonde estão
Comment: No caso estamos falando somente de Data Annotations?
Answer: Há um pacote NuGet que faz isso. Os detalhes estão aqui.
Ou você pode reimplementar o PasswordValidator do ASP.NET Identity.

EDIT
O ASP.NET Identity possui seu próprio pacote de resources para o Português. Apenas instale este pacote e veja as opções de globalização do seu web.config que deve funcionar.
Comment: instalei o pacote, parece que devia funcionar, mas a mensagem ainda está em ingles, é relacionado a esse arquivo aqui [link](https://github.com/aspnet/Identity/blob/85012bd0ac83548f7eab31f0585dae3836935d9d/src/Microsoft.AspNet.Identity/Resources.resx), vejo que existe uma dll com esse nome dentro do pacote pt-br, mas ele não está carregando o mesmo @cigano
Comment: Editei a resposta. Agora acho que deve estar dentro do que procura.


When nginx reports about limiting requests, what do theese numbers mean?

Question: When you setup nginx with limit_req directive, it logs excessive requests like
2019/10/30 17:41:36 [error] 10775#10775: *195997 limiting requests, excess: 10.210 by zone "zone_name" ...

I wonder, what means 10.210 here?
I suppose, that 10 is a burst size, defined in limit_req as burst=10, but what is 210 here?
Comment: IDK but maybe it's the burst size to three decimal places?
Answer: https://dzone.com/articles/nginx-rate-limiting states this is:

Number of requests per millisecond over the configured rate that this request represents.
Comment: This should read `requests per second` (not millisecond).
Comment: Sure? NGINX internally calculates it down to miliseconds as the docu says: https://www.nginx.com/blog/rate-limiting-nginx/

"[...]NGINX actually tracks requests at millisecond granularity[...]"


get data from 2 mysql tables with php

Question: I have 2 tables, contacts and contacts_group. contacts has (id, name, lastname, email,), contacts_group has (id, owner, mail, group_name). How can i select this together with php.
Comment: Much more information is needed. What MySQL API are you using in PHP (MySQLi, PDO)? How are those tables related? What kind of data do you intend to display?
Comment: Questions asking for code must **demonstrate a minimal understanding of the problem being solved**. Include attempted solutions, why they didn't work, and the *expected* results. See also: [Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)
Answer: You should have a foreign key in contacts which refers to id in contacts_group, then you can do something like this:
SELECT * FROM contacts_group cg JOIN contacts c ON c.id_group = cg.id

You should read about relationships in MySQL ;)
Answer: Hans, you could use two different queries:
$contactsquery = "SELECT * FROM contacts";
$contacts_group_query = "SELECT * FROM contacts_group";

Of course you would need a DB Connection on top:
define("DB_SERVER","localhost");
define("DB_USER","chatApp");
define("DB_PASS","ibmpass");
define("DB_NAME","chatApp");

$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

And to perform them you would use
$result_1 = mysqli_query($connection, $contactsquery);
$result_2 = mysqli_query($connection, $contacts_group_query);

Or you could create a foreign key on the contacts_group to keep track of the contacts, and then join them in code as:
SELECT * FROM contacts_group cg JOIN contacts c ON c.id_group = cg.id

But I would highly recommend you to read this basic introduction to PHP & Queries before getting deeper, as you will have many doubts about it.

get data from 2 mysql tables with php


PHP Captcha can't find the TTF file

Question: I need to add a captcha to my site but for some reason I get this error (from the log file):
Warning: imagettfbbox(): Could not find/open font in /home/eric/www/captcha.php on line 24
Warning: imagettftext(): Could not find/open font in /home/eric/www/captcha.php on line 27

Here's my code:
function generate($width,$height,$characters='6') {
    $code = '';
    $availableChar = '23456789bcdfghjkmnpqrstvwxyz';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($availableChar, mt_rand(0, strlen($availableChar)-1), 1);
        $i++;
    }
    $image = imagecreate($width, $height);
    $text = imagecolorallocate($image, 20, 40, 100);
    $things = imagecolorallocate($image, 100, 120, 180);
    for( $i=0; $i<($width*$height)/3; $i++ ) {
        imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $things);
    }
    for( $i=0; $i<($width*$height)/150; $i++ ) {
        imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $things);
    }
    $textbox = imagettfbbox($height, 0, 'monofont.ttf', $code);
    imagettftext($image, $height, 0, (($width - $textbox[4])/2), (($height - $textbox[5])/2), $text, 'monofont.ttf' , $code);
    imagejpeg($image);
    imagedestroy($image);
    return $code;
}

header('Content-Type: image/jpeg');
$code = generate(100, 40, 5);
echo $_SESSION['security_code'] = $code;

and the file in my folder:
-rwxr-xr-x 1 tech4wilco tech4wilco 41036 1999-07-13 23:30 monofont.ttf
-rw-r--r-- 1 tech4wilco tech4wilco  1030 2011-10-17 15:43 captcha.php

I did some digging and what I found is the font needs to be there and as you can see it's in the same folder as the PHP file, Am I not understanding something?
Comment: You don't do any error checking. All of those functions (like imagejpeg) return booleans or other info that indicates their succes. Catch those results and narrow down where it goed wrong.
Comment: It might have to do with the GD library you're using. From the PHP docs, "Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path." Perhaps it was looking for monofont.ttf.ttf?
Answer: It's probably looking in the wrong directory.  Try changing monofont.ttf to ./monofont.ttf.
Answer: Its not in the same folder as the PHP file, since you are runing Test.php and not Captcha.php.
Try putting it on the same folder as test.php or using the correct path to get to it.
Comment: sorry my bad, I renamed the file afterwards.
Answer: monofont.ttf file is not there in the directory.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/faq#reputation) you will be able to [comment on any post](http://stackoverflow.com/privileges/comment).
Comment: this answer is for above question

PHP Captcha can't find the TTF file


MySQL reinstall questions

Question: For some reason my /var/run/ dir on debian6 had it's chown and chmod changed. Problem is from what? Outcome is that mysql fails. I'm guessing the easiest way to fix is to reinstall MySQL. (Previously this LAMP was running fine.)
However, I have established databases and tables and don't want to lose them. Since mysql is not running I can't backup (correct?).
I just want to confirm that:
1). if I reinstall, I won't loose my databases.
2). apt-get install mysql-server mysql-client is the correct command to use.
Thanks.
EDIT:
/var/log/syslog output when running /etc/init.d/mysql start:
mysqld_safe: Starting mysqld daemon with databases from /var/lib/mysql
mysqld: 130109 10:44:10 [Note] Plugin 'FEDERATED' is disabled.
mysqld: #007/usr/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
mysqld: 130109 10:44:10 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
mysqld: 130109 10:44:10 InnoDB: The InnoDB memory heap is disabled
mysqld: 130109 10:44:10 InnoDB: Mutexes and rw_locks use GCC atomic builtins
mysqld: 130109 10:44:10 InnoDB: Compressed tables use zlib 18.104.22.168
mysqld: 130109 10:44:10 InnoDB: Using Linux native AIO
mysqld: 130109 10:44:10 InnoDB: Initializing buffer pool, size = 128.0M
mysqld: 130109 10:44:10 InnoDB: Completed initialization of buffer pool
mysqld: 130109 10:44:10  InnoDB: Operating system error number 13 in a file operation.
mysqld: InnoDB: The error means mysqld does not have the access rights to
mysqld: InnoDB: the directory.
mysqld: InnoDB: File name ./ibdata1
mysqld: InnoDB: File operation call: 'create'.
mysqld: InnoDB: Cannot continue operation.
mysqld_safe: mysqld from pid file /var/run/mysqld/mysqld.pid ended
/etc/init.d/mysql[4531]: 0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
/etc/init.d/mysql[4531]: #007/usr/bin/mysqladmin: connect to server at 'localhost' failed
/etc/init.d/mysql[4531]: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
/etc/init.d/mysql[4531]: Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
/etc/init.d/mysql[4531]:

Comment: Agreed, much better to fix and find what changed the permissions. You can change the ownership back again using chown/chmod commands. When you do `ls -la /var/run` what has the ownership been changed to?
Comment: What is the error message when you try to start mysql? It will be much better to fix it than to re-install.
Comment: changed to a user and www-data. I tried changing back to root:root. Even opened up /var/run/mysqld/ to 777 to no avail.
Answer: it would be good to find out what really has happened; you can take a look at any other computer with the same OS and mysql installed and use chmod and chown to restore the expected rights and ownership.
quick look at a random debian server tells me:
root@serv:/var/run# ls -la /var/run/mysqld/*
total 12
drwxr-xr-x  2 mysql root  4096 Oct 24 13:29 .
drwxr-xr-x 14 root  root  4096 Jan  9 01:28 ..
-rw-rw----  1 mysql mysql    5 Oct 24 13:29 mysqld.pid
srwxrwxrwx  1 mysql mysql    0 Oct 24 13:29 mysqld.sock

so try first:
chown mysql:mysql /var/run/mysqld/*
chown mysql:root /var/run/mysqld

and appropriate chmods if needed
if you decide to re-install - be on the safe side:

try to shut down cleanly mysql - if needed using regular kill and waiting
copy all the data files [not just few - eg not just the directory of one database; it might not be enough for innodb]
copy all the config files

only then try to uninstall + reinstall
Comment: The issue was permissions. I did have another install to compare to, and kept going back to /var/log/syslog and seeing where the errors where thrown. In addition to /var/run, there were permission issues in /var/lib/mysql.

chown mysql:mysql -R /var/lib/mysql
chmod 660 -R /var/lib/mysql
Answer: A plain reinstall as you propose is guaranteed not to help in this case, as none of the scripts which effect these permissions would be changed by a straight reinstall.  Some things to note:  /var/run is now a tmpfs mounted at runtime.  The permissions are set when it is mounted.  from /etc/init.d/mountkernfs.sh:
domount tmpfs "" /var/run varrun -omode=0755,nosuid$RUN_OPT

So you should have /var/run as root:root and chmod 0775.
Another thing to note is that /var/run is empty at every boot.  Any changes you make to /var/run will be gone during a reboot.
When the mysql init runs, it will make sure /var/run/mysqld exists. If it doesn't, it will be re-created with the correct permissions.  from /etc/init.d/mysql:
test -e /var/run/mysqld || install -m 755 -o mysql -g root -d /var/run/mysqld

So if you haven't yet rebooted, you could try /etc/init.d/mysql stop && rm -r /var/run/mysqld && /etc/init.d/mysql start.
If you have rebooted, then something else is wrong.  Perhaps you have an old version of the mysql init script (this can happen if you modified it, then upgraded, the upgrade would not (by default) overwrite your changes to the init script.  You can check if you have an old version of the mysql init script by asking dpkg what the current packaged md5 of the script is:
# dpkg -s mysql-server-5.1 | grep init.d
/etc/init.d/mysql ea6d050ac82ed69d01970f9b95ab9b9d

then compare that to the md5sum on your filesystem:
# md5sum /etc/init.d/mysql
ea6d050ac82ed69d01970f9b95ab9b9d  /etc/init.d/mysql

Comment: Thanks Stew. Last time I looked at the website, all was ok. Now (literally months later, I'm getting these issues).
mysql-server-5.5
`/etc/init.d/mysql 7ecd4a6dfd5fbc57f44d79b1e5223f2c`
`7ecd4a6dfd5fbc57f44d79b1e5223f2c  /etc/init.d/mysql`
Comment: 5.5 isn't in debian 6.  Did you get this from the unreleased testing/unstable repositories? or from some third party like bpo? (I'd recommend against any of these, btw).  In any case, everything I said above should still hold true.
Comment: I have added these to many of my servers running D6 and have had no issues for well over a year (18 months probably):
`deb http://dotdeb.mirror.borgnet.us/ stable all`

`deb-src http://dotdeb.mirror.borgnet.us/ stable all`
Comment: no issues, until today, i guess…
Answer: I would avoid changing any permissions on the /var/run directory at the moment, but only change the /var/run/mysqld path.
You must make sure the mysql user can access and write to the mysqld directory.  The first command assigns the correct group and the second command allows that group to write to that path.
sudo chgrp mysql /var/run/mysqld/
sudo chmod g+w /var/run/mysqld/
Comment: mysql will create the directory if it doesn't already exist, and those are the wrong group/permissions.  better to just remove `/var/run/mysqld` and `service mysql restart`
Comment: I removed mysqld  dir and ran `service mysql restart` and it did recreate the dir with mysql:root and 755. Still failing a restart.

MySQL reinstall questions


Formula to change output of an index match formula based on the cell adjacent to the indexed one?

Question: I'm taking raw data from one spreadsheet and moving it into another sheet for a report. The raw data kind of looks like this:

site
parameter
value
qualifier

a
chlorine
14 mg/L
U

b
chlorine
19 mg/L
J

a
pH
6.8

b
pH
7.1

And the table I'm making currently looks like this:

parameter
site a
site b

chlorine(mg/L)
14
19

pH
6.8
7.1

I used the following function to do this:

=INDEX(data!$C$2:$C$100,MATCH(1,(B$1=data!$A$2:$A$100)*($A2=data!$B$2:$B$100),0))

So I'm searching through the raw data to find where the parameter and the site are specific values, and it yields the value where both are true.
My issue is that now I want to go through again and find every value where the qualifier in the original data is U (this means nondetect so the value given is essentially a guess), and change it so that that cell is blank in the final table. So I want my final table to look like this, because in my example raw data, site a's chlorine value had a U qualifier:

parameter
site a
site b

chlorine(mg/L)
--
19

pH
6.8
7.1

The only way I can think to do it right now would have me repeating the formula I already have a bunch of times in a really big nested function using IFs and XLOOKUP. I want to avoid this if possible because that makes it much harder to notice errors. I'm wondering if I can somehow use the "OR" function for this, but I don't know how to call adjacent cells in excel syntax, if that's possible. I don't want to actually return what's in the qualifier column, so I can't use OFFSET, either.
Answer: Perhaps this will work for you using XLOOKUP()

• Formula used in cell G2
=XLOOKUP(
    1,
    (
        TEXTBEFORE(
            $F2,
            "(",
            ,
            ,
            ,
            $F2
        ) = $B$2:$B$5
    ) *
        (
            TEXTAFTER(
                G$1,
                " "
            ) = $A$2:$A$5
        ) * ($D$2:$D$5 <> "U"),
    $C$2:$C$5,
    "--"
)

Formula needs to fill down and fill right!

If you want to return an array then you could try this:
=MAKEARRAY(ROWS(F2:F3),COLUMNS(G1:H1),LAMBDA(α,φ,
 XLOOKUP(1,(TEXTBEFORE(INDEX(F2:F3,α),"(",,,,INDEX(F2:F3,α))=B2:B5)*
 (TEXTAFTER(INDEX(G1:H1,φ)," ")=A2:A5)*(D2:D5<>"U"),C2:C5,"--")))

Comment: I think that would definitely work, but my actual dataset is really large and I was hoping to avoid having to make more than one table. I ended up using this formula: =if(INDEX(data!$D$2:$D$100,MATCH(1,(B$1=data!$A$2:$A$100)*($A2=data!$B$2:$B$100),0))="U","--",INDEX(data!$C$2:$C$100,MATCH(1,(B$1=data!$A$2:$A$100)*($A2=data!$B$2:$B$100),0)). It's a little more complicated than I would like but not nearly as bad as I thought it would be. So the original function now returns the qualifier column and the if function switches it back to the value column if its not a U value. Thank you though!
Comment: Many ways to reach `Rome` not sure how your initial formula will work since you have the parameter in the `Table1` as `chlorine` while in `Table2` it is `chlorine(mg/L)` so there is no formula to parse those delimiters. Weird. Need to investigate more!
Answer: Tidying up your labels (I think they must be tidier than in the tables you posted since your working formula isn't doing any "parsing", e.g. for mg/L) you could use a single FILTER() function:

The formula in C9 (copied down and across) is
=FILTER($C$2:$C$5,($B$2:$B$5=$B9)*($A$2:$A$5=C$8)*($D$2:$D$5<>"U"),"--")

Comment: Yes, my actual table looks different. i typed this one out quickly rather than copy-pasting some of the actual data because I'm paranoid about sharing data from work. Thank you for the idea to use filter, the concept of using * to use multiple parameters is new to me, so I'm still pretty ignorant about which functions can use them. Thanks!


Polygons with convergent area

Question: Suppose that there is an equilateral triangle of area 10, call this $A_0$, we then trisect each side of this triangle, then cut off the corners, giving the polygon $A_1$, what is the area of this polygon, we then do this again to get $A_2$ (trisect sides, and cut corners), what is the area of this polygon? What is the area of $A_\infty$.
With this problem, I initially tried to generalise side length for $A_n$, then used the area of a polygon formula to find the area, I was wondering if anyone could come up with any other ideas, or alternatively do it the same way I did, to compare answers. Best of luck!
Comment: You have continuously asked this very question HERE, I believe 3 times in a row---->https://math.stackexchange.com/questions/2665051/convergent-area?noredirect=1#comment5504953_2665051
Comment: With different accounts, not to mention.
Answer: The answer for $A_n$ as n goes to infinity is $0$
Note that
$$A_0 = 10$$
$$A_1 = 10(2/3)$$
$$A_2= 10(2/3)^2$$
$$A_3= 10(2/3)^3$$ $$.$$ $$.$$ $$.$$
$$A_n= 10(2/3)^{n}$$
$$ A_{\infty } =lim _{n\to \infty} 10(2/3)^n = 0 $$
Comment: So you are not cutting away all the corners of the new triangles each time? My answer was based on my assumption that you do the cutting on remaining little triangles as you did with the original one.
Comment: Yes that was the idea

Polygons with convergent area


Formatando String em Python para ter aparência de endereço MAC

Question: Preciso transformar um MAC em string e deixar dois pontos a cada 2 caracteres, seria possível?
import re

mac = "b5b4-7422-37bc"
novo = re.sub(r"[^a-zA-Z0-9]","",mac)

b0be762931b3 #ele retorna esse mac.

Tendo a seguinte string: b0be762931b3
Eu gostaria que ela ficasse assim: b0:be:76:29:31:b3.
Answer: Se estiver usando Python >= 3.8 pode fazer assim:
mac = "b5b4-7422-37bc"
print(bytes.fromhex(mac.replace('-', '')).hex(':'))

Afinal, o MAC Address está representado em hexadecimal, portanto bytes.fromhex consegue convertê-lo para bytes sem problemas (depois de remover os hífens, claro).
Em seguida, o ḿetodo hex converte os bytes de volta para hexadecimal, mas usando o : como separador. O detalhe é que o resultado terá letras minúsculas, independente do valor original (ou seja, se a string for 'B5B4-7422-37BC', o resultado ainda será b5:b4:74:22:37:bc.
Mas como já dito, isso só funciona a partir do Python 3.8, pois em versões anteriores o método hex não aceita o separador como parâmetro.

Para versões anteriores ao 3.8 você pode usar as soluções das outras respostas, mas apenas para deixar registrado mais algumas alternativas:
mac = "b5b4-7422-37bc"
macbytes = bytes.fromhex(mac.replace('-', ''))
formatado = ':'.join(f'{b:02x}' for b in macbytes)
print(formatado)

Esta solução também cria um objeto bytes, mas formata cada byte para hexadecimal antes de passar para join. Para tal, é usado uma f-string, que está disponível a partir do Python 3.6 - em versões anteriores pode trocar para format:
formatado = ':'.join('{:02x}'.format(b) for b in macbytes)

Lembrando ainda que esta opção resulta em letras minúsculas. Para letras maiúsculas, troque o formato para 02X.

Outro jeito:
mac = "b5b4-7422-37bc"

mac = mac.replace('-', '')
formatado = ':'.join(mac[i:i + 2] for i in range(0, len(mac), 2))
print(formatado)

É similar a uma das respostas, mas usando slices para pegar pedaços da string (sempre de 2 em 2 caracteres), e no final juntando tudo com join, usando o : como separador. Mas ao contrário do que foi feito lá, eu não usei os colchetes em volta da expressão, pois isso cria uma lista desnecessariamente (claro que para uma string pequena como essa é um overhead imperceptível, mas enfim).

E já que você usou regex, também daria para ser assim:
import re
mac = "b5b4-7422-37bc"

formatado = ':'.join(m[0] for m in re.finditer('[a-f0-9]{2}', mac, re.I))
print(formatado)

Como o MAC Address está representado em hexadecimal, só vai ter letras de "a" até "f", então não preciso colocar até o "z" na regex. Também usei a opção re.I para que ela seja case insensitive (pegue tanto maiúsculas quanto minúsculas).
E usei o quantificador {2} para pegar exatamente dois caracteres. Ou seja, finditer retornará as letras e números, agrupados de 2 em 2 (e repare que nem precisa de replace ou sub para remover os hífens, pois estes serão ignorados pela regex - ou seja, em vez de usar a regex para remover os hífens, eu uso para capturar os caracteres que preciso).
No join eu pego o grupo zero de cada match, que contém os caracteres que foram capturados.
Outra alternativa com regex é:
import re
mac = "b5b4-7422-37bc"

formatado = ':'.join(re.findall('[a-f0-9]{2}', mac, re.I))
print(formatado)

A diferença é que findall retorna uma lista (ou seja, primeiro ela constrói uma lista com todos os trechos que deram match, e depois passa-a para join), enquanto finditer retorna um iterator (ou seja, ele não constrói uma lista, e em vez disso ele vai obtendo cada match de uma vez, passando-os para join à medida em que são encontrados).
Answer: Tirando proveito do tamanho conhecido:
str = "abcd456f89d1"
novo = str[0:2] + ":" + str[2:4] + ":" + str[4:6] + ":" + str[6:8] + ":" + str[8:10] + ":" + str[10:12]
print(novo)

Saída:
ab:cd:45:6f:89:d1

E esta segunda maneira é bem explícita em refletir a intenção do programador (quebrar a string em pares de caracteres e concatená-los intercalando com :), desde que seja uma string sem formatação prévia, composta inteiramente por dígitos hexadecimais.
Também acho limpo que a solução se baseie somente em manipular substrings da string inicial, sem conversão de tipo:
import functools
str = "abcd456f89d1"
pares = [str[i:i+2] for i in range(0, len(str), 2)]
novo = functools.reduce(lambda a, b: a + ":" + b, pares)
print(novo)

Saída:
ab:cd:45:6f:89:d1

Comment: O primeiro exemplo está otimo, já sabe qual o formato do valor na "entrada", então não tem o porque fazer coisas mirabolantes, o slice resolve perfeitamente.
Comment: A que me agradou foi essa: `novo = str[0:2] + ":" + str[2:4] + ":" + str[4:6] + ":" + str[6:8] + ":" + str[8:10] + ":" + str[10:12]` - não por ser oneliner, mais pelo fato de acessar diretamente pelas posições conhecidas.
Comment: Essa que o @Bacco e o @GuilhermeNascimento gostaram e a resposta do @hkotsubo `bytes.fromhex(mac.replace('-', '')).hex(':')` são as melhores soluções.
Answer: Você pode separar a string que deseja (supondo que a mesma será sempre um endereço mac válido e que já houve o tratamento colocado na pergunta antes) e utilizar compreensão de listas:
mac = "b0be762931b3"
# Percorremos a string pulando sempre o próximo caractere
# (pois estamos usando i + 1, então já lemos ele na última iteração)
# e, ao final, concatenamos nossa lista de
# resultados com ':' utilizando o método join. Lembrando que o
# tamanho da string está sendo considerado com "-1", pois
# estamos sempre um item a frente.
':'.join(['{}{}'.format(mac[i], mac[i + 1]) for i in range(0, len(mac) - 1, 2)])

Explicação sobre o que foi feito acima:
Esse tipo de declaração nos permite criar listas em apenas uma linha se preferível, mas funciona como criar uma lista com um laço de repetição comum (pense num for) adicionando um valor em uma lista e retornando-a ao final. Um exemplo:
def gera_lista(tamanho_lista):
    resultado = []
    for i in range(tamanho_lista):
        resultado.append(i)

    return resultado

A função acima pode ser escrita como:
tamanho_lista = 5
[i for i in range(tamanho_lista)]

O método join() fará com que os valores que estão na nova lista gerada sejam concatenados e "separados" pelo valor que está no objeto de string no qual foi chamado (desde que o elemento seja uma string. Essa conversão para string pode ser feita com str(), que retorna uma string representando o valor do objeto). Se usarmos o exemplo acima e juntarmos os valores em uma string, separando-os por vírgula:
','.join([str(i) for i in range(5)])

Teremos o resultado:
"0,1,2,3,4"

Antes de escrevermos for i in... na declaração usando compreensão de listas, podemos inserir uma expressão. O uso do format() dentro do laço de repetição é apenas para juntar as strings e retornar uma nova string concatenada com os dois caracteres, mas poderia ter sido feito de formas diferentes (como mac[i] + mac[i + 1] ou f'{mac[i]}{mac[i + 1]}').
Agora, para não pularmos nenhum caractere ou deixar algum de fora, usamos um range e chamamos seu construtor com um terceiro argumento de step. Esse argumento diz ao iterator de "quanto em quanto" vamos iterar pelos valores gerados. Pense na definição como:
range(começo, fim, passo)

Juntando cada função, usos de expressões acima e um pouco de lógica, temos o resultado:
':'.join(['{}{}'.format(mac[i], mac[i + 1]) for i in range(0, len(mac) - 1, 2)])

Ao executar com o valor exemplificado na pergunta, teremos a saída:
b0:be:76:29:31:b3

E com o tratamento completo (já considerado na pergunta):
import re
mac = "b5b4-7422-37bc"
novo = re.sub(r"[^a-zA-Z0-9]","",mac)
print(':'.join([novo[i] + novo[i + 1] for i in range(0, len(novo) - 1, 2)]))

A saída será:
b5:b4:74:22:37:bc

Answer: Uma maneira de resolver o problema, é percorrendo a string e colocar um comando condicional if para fazer a inserção do caractere : no local indicado pelo contador, neste caso toda vez que houver um múltiplo do número 2.
Para descobrir quais valores são múltiplos do algarismo 2(dois) utilizamos o operador resto da divisão, representado por %.
A implementação seria assim:
mac_number = 'b0be762931b3'
formated_mac_number = ''
for i, item in enumerate(mac_number):
    if i % 2 == 0 and i > 0:
        formated_mac_number += ':'
    formated_mac_number += item
print(formated_mac_number)
# b0:be:76:29:31:b3

Usando a função enumerate como uma maneira de contar e iterar os itens da string que desejamos percorrer. Isso vai auxiliar na condição de quando efetuar a inserção do valor :

Outra possibilidade seria utilizar apenas um contador para efetuar a tarefa. Da seguinte forma:
mac_number = 'b0be762931b3'
formated_mac_number = ''
for i in range(len(mac_number)):
    if i % 2 == 0 and i > 0:
        formated_mac_number += ':'
    formated_mac_number += mac_number[i]
print(formated_mac_number)
# b0:be:76:29:31:b3

Para auxiliar nesta implementação, temos a função len, que vai setar como valor máximo o tamanho da string mac_number com o auxilio da função range que vai nos fazer percorrer todos os caracteres começando no índice 0 ao len(mac_number) aí basta percorrer a string mac_number através do valor do índice i.
Answer: Outra solução é remover os caracteres indesejados da string e a converter em um vetor de caracteres(lista) para então iterar por esse vetor inserindo o caractere ":", nos lugares apropriados, isso se antecipadamente levar em conta o quanto o vetor irá se modificara durante a operação portando o seu tamanho se aumentará, a uma taxa calculável, enquanto faz a iteração.
A cada dois caracteres o vetor de caracteres será aumentado em um caractere ":" , ou seja ao final da operação o comprimento do vetor resultante será uma vez o comprimento do vetor de entrada mais a sua metade de seu comprimento, onde tem que ainda ser descontado o último caractere pois não se adicionado ":" ao final da string. Supondo que s seja o vetor de entrada já purgado então ao final da operação o tamanho do vetor resultante terá o comprimento:
tamanho_do_vetor_resultante = (len(s) - 1) + (len(s) - 1) / 2

Ou simplificando e truncando:
tamanho_do_vetor_resultante = int((len(s) - 1) * 1.5)

No caso:
#O código não testa se o endereço mac tem a quantidade de dígitos correta. Implemente aparte.

mac = "b5b4-7422-37bc"

s = list(mac.replace("-",""))                    #Purga os caracteres indesejados.

for i in range(2, int((len(s) - 1) * 1.5), 3):   #Para i variando de dois ao comprimento projetado do vetor resultado a cada três elementos(não dois pois temos que levar em conta o último ":" inserido)...
  s.insert(i,":")                                #...insira na posição i o caractere ":" .

print("".join(s))                                #Imprima o resultado como string.

Teste o código no Ide.One
Comment: Por que não `for i in range(2, len(str), 2)` ou o que quer que funcione nesse sentido? O segundo `2` é o _step_. Fica mais clara a intenção a meu ver :)
Comment: Ahhhh bem observado. Vou deixar meu comentário aqui caso alguém cometa o mesmo engano que eu :)
Comment: @Piovezan, porque estou inserindo enquanto itero pelo vetor e tamanho dele expande a cada iteração.
Answer: Reutilizando seu código inicial, podemos fazer assim.
import re

mac = "b5b4-7422-37bc"
novo = re.sub(r"[^a-zA-Z0-9]","",mac)
tamanho = len(novo)

formatado = ':'.join(novo[i:i+2] for i in range(0,tamanho,2))

print(formatado)

Mas podemos facilitar um pouco mais a leitura substituindo a expressão regurar por algo mais simples, caso vc tenha certeza do formato inicial seja sempre como o da variavel mac
mac = "b5b4-7422-37bc"
novo = mac.replace("-","")
tamanho = len(novo)

formatado = ':'.join(novo[i:i+2] for i in range(0,tamanho,2))

print(formatado)

Sobre a formação, é usado o range que recebe 3 argumentos.

O primeiro indica que deve iniciar em 0;
O segundo é o limite    máximo, que no nosso caso é o tamanho da
variavél novo;
O terceiro    estamos indicando como ele vai fazer a contagem, no
nosso caso,    pulando de dois em dois;

Com isso o for vai iterar de dois em dois nos characters de novo até o final dele, o join vai "juntar" esses caracteres com ":" formatando assim o mac no formato desejado.


Network security: No incoming connections vs. reverse tunnel to proxy

Question: A client has a network that is restrictive. They want no incoming connections and they have no VPN. We're installing an admin tool that external admins need to access. One solution is that the admins access a cloud-based version of the admin tool and a cron job from their network occasionally grabs the data and updates the internal admin tool. This is a huge hassle. Now we've got to deal with data contention issues, delays, etc. I'd rather not do that.
Here's my question: If I propose a reverse tunnel from the admin tool server to a cloud-based SOCKS proxy that their external admin users can log into, is this something that an IT team might consider as being a secure alternative?
Comment: Go and sit down with your customer  and negotiate with their security department and NOC.  In general valid business requirements ought to be accommodated, unless they really can't, but rather than asking us about what might be achieved technology wise, instead ask what the other stakeholders at your clients' find  acceptable and can offer before theorising about circumventions ...
Comment: There have been discussions with IT prior to my arrival at the company. What I've outlined is all I know. I'm not sure how much of a negotiation was had. I'm planning to talk to their IT department soon. I just want to make sure that if I say, "Hi guys, we need access," and they say, "I'm sorry, but we already told you guys strictly no incoming connections," that I have a few smart alternatives. Or at least alternatives that they wouldn't say, "Nobody, in the history since the advent of the word 'network', would ever think that was a reasonable idea."
Answer: It is not a crazy idea and it is definitely more secure than an incoming connection so it is not a bad suggestion / compromise that they may accept. That said, reverse proxies do not protect you against poorly written applications, exploits like SQL injection will pass right through the reverse proxy unless you also implement filtering and inspection on requests at the proxy's end, so there is still some degree of risk...
One of the companies I work for had a similar problem providing mobile access for remote users to a proprietary software when installed on-premise (not everyone likes cloud), the solution was to use Azure's Hybrid Connection, its basically a reverse proxy but somehow being a Microsoft Azure based solution seems to improve the acceptance on their customers and has been well received.
Comment: Thanks. That's about what I was thinking; the sanity check is welcome.


How to determine how many runs are needed for a Monte Carlo simulation?

Question: I have been reading a lot of references online, but people seem to have different sorts of equations to determine the required number of runs.

This formula was the one I obtained from an article and I am wondering if this is indeed the right one. Also, how can I use this formula?
Edit:
I will use the Monte Carlo simulation to generate random numbers from a normal distribution. These random numbers will be used to represent demand as the random variates.
The model of interest is an inventory model where demand will be the variable to be simulated. The properties of the demand is that it is normally distributed, mean is non-stationary over time, independent and not correlated, and stochastic over a time horizon.
I performed a linear program using MATLAB, however, the solution of the problem is deterministic by nature--meaning it will always give the same "optimum" value for the specified parameter settings. What I want to achieve is to incorporate randomness into the system by using a Monte Carlo simulation which will test my model for robustness when different "real" demands are incorporated.
I would say a 95-98% accuracy would be good, but it is completely arbitrary because I do not really have anything to base it on.
Below is my code for the generation of the "real" demand values.
Where:
n= number of runs;
average(i)=mean of demand;
a(i)=standard deviation of demand;
CV=coefficient of variation;
sim_d="real" demand values;

This is the flowchart of the process to further explain the procedure (click to see)
Comment: Rather than quote some random formula which may or may not relate to what you're trying to do, please describe what you're trying to simulate, what outcomes you want to look at and (if possible at this stage)  what kind of accuracy you need (/uncertainty you can tolerate) on them.
Comment: What article? Give a reference. Ans.: A sufficient number. How sufficient is determined depends on what is being tested, speaking of which, what IS being tested?
Comment: I think I (sort of) understood what you're doing. Now, what uncertainty do you want to estimate with Monte Carlo? The uncertainty in the number of burgers ordered? The probability of this "stock-out", i.e., how often the number or burgers orderered may be less than the number or burgers ordered? Ps not so important, but just for curiosity's sake, why do you have two values of demand? Do you have two restaurants in your problem? Or is it the demand forecast in two successive days?
Comment: I don't understand: in a linear programming (optimization) problem, you have variables $(x_1,\dots,x_p)=\mathbf{x}$, linear constraint $\mathbf{A}\mathbf{x}-\mathbf{b}$, and a linear objective function $f(x_1,\dots,x_p)=\sum_{i=1}^p c_ix_i=\mathbf{c}\cdot\mathbf{x}$. What are you considering uncertain? The coefficient vector $\mathbf{c}$? The constraint matrix $\mathbf{A}$? The constraint vector $\mathbf{b}$? All of the above?
Comment: if one of the answers answered your question, you can [accept an answer](http://stats.stackexchange.com/tour) by clicking on the tick sign to the left of the question, below the number of votes, or if you think no answer is correct, you may leave a comment explaining what you would need to be discussed (as long as it's not another question: in that case you have to post a new question).
Comment: Thanks for including the process, but I still don't understand what "demand" is in the linear programming problem. It surely isn't one of the $x_i$, because those are not *inputs* to the optimization problem, in the sense that you don't assign a value to them in order to solve the problem.  You assign values to $\mathbf{c}, \ \mathbf{A}$ and $\mathbf{b}$, and then you find an optimal value $\mathbf{x}^*=(x_1^*,\dots,x_p^*)$ for your variables.
Comment: DeltaV, only one variable will be subject to randomness while keeping everything constant. That is the demand variable. For instance, demand=[30, 20] -> Input to and then run linear program -> Order 56 burgers -> Inject randomness into demand -> random demand using a mean of 30 and 20 and its corresponding standard deviation=[32 25] -> Incurs a stock-out in this example because "real demand" is total to 57 while the order quantity was only 56.
Comment: DeltaV, Actually it is an input to the linear program. Although I kind of understand why you are confused. There is no way to actually incorporate that normally distributed demand into the linear program. However, the demand was used as follows: A heuristic developed to solve for the upper bounds of the order quantities was used where the mean of the demand was an input to this heuristic (note: normal distribution has no closed form)->The heuristic has an output of a table of deterministic order quantities -> a mixed integer program was used to pull out these orders on certain conditions
Comment: That's precisely what I'm saying: since it's one of the inputs, it's not one of the variables you're optimizing for. In other words, you *assign* (input) a demand, and you *compute* (solve the linear programming problem for) a number of burgers ordered.
Comment: The values I want estimate are a lot: stock-outs, perish of goods (expired), cost, service level (demand fulfilled/available stock). Assuming that the model told me to order 50 burgers. How well does this solution work when randomness in injected in demand when I simulated "real" demand values? That is the question. And for your curiosity, it is demand forecast of two days (or periods). Yes it is not a decision variable, but is an input to clear it up.
Comment: So, you re-run the model multiple times with random demands, and for each couple of random demands you get a number of burgers predicted by the model. Right? If this is the setting, I can answer your question.
Comment: Almost there, but not exactly. The decision variable is how many burgers. This is then held constant. We change only the demand values to represent realistic demands. Then the information of interest is the stock-outs, cost, and etc. What I was asking in the question was: how many times do i need to simulate the demand values. For instance, do i need 500 simulated demand runs to say that it is accurate? e.g. (demand=[32 18] - 1st run, demand=[28, 24] - 2nd run,..., until 500th run]
Comment: It's still not clear to me which is the output random variable whose mean you would like to estimate with the Monte Carlo method. Different outputs will require a different number of Monte Carlo runs, so let's concentrate on **one** output. Would the average number of stock-out events over 13 following days be an RV of interest for you?
Comment: Yes it would be of interest. Stock-outs and also the service level is a function of demand.
Comment: The normal distribution is a limiting distribution with finite moments. Per the many comments already made, a decision of "how many" simulations to run is a function of the behavior(s) you are trying to represent. Do you want to express the mass or density of the normal PDF or are you interested in the extremes? In financial optimization, the prescribed number of simulations is commonly put at 10,000 -- this works in terms of defining the density of the normal PDF. To capture extreme tail behaviors based on the normal, 150 million simulations may not be enough.
Comment: @DJohnson, of course there's not a magic number $N$ which, for all problems, will ensure that you get a certain accuracy at a given confidence level. The only thing you can say in general is that if $N$ runs give you a certain accuracy at a fixed confidence level, you need 4 times as much runs to halve the confidence interval width, since the standard error of the MC estimator is inversely proportional to the square root of the number of runs. However, for specific cases where the hypotheses behind MC estimation are valid, you do have procedures to estimate $N$ for that case, as I showed.
Answer: The setting is a bit different from what I'm used to, but I think this is a classic Uncertainty Quantification (UQ) approach: specifically, it's Forward Uncertainty Propagation. The approach has limits, since you assume the demand distribution, instead than estimating it from data. Anyway, let's consider the following setting: with your model, you compute $C$, the number of burgers ordered over $p$ days. Using a constant coefficient of variation $\lambda$ and a vector of means $\boldsymbol{\mu}=(\mu_1,\dots, \mu_p)$, you define a random vector $\mathbf{d}=(d_1,\dots,d_p)$, whose components are independent, normally distributed with means given by $\boldsymbol{\mu}$ and standard deviations $(\sigma_1=\lambda\mu_1,\dots, \sigma_p=\lambda\mu_p)$. Then, we generate a random sample $D=(\mathbf{d}_1,\dots,\mathbf{d}_N)$ of size $N$ from the distribution of this vector:
set.seed(25)
C <- 50
N <- 500
lambda <- 0.1
means <- c(30, 20)
p <- length(means)

demands <- rnorm(N * p, mean = means, sd = lambda * means ) # vector of length p*N

Now, for each vector $\mathbf{d}_i=(d_{i1},\dots,d_{ip})$, you either had a stock-out event or not, depending on whether $\sum_{j=1}^p d_{ij} > C$ or not. In other words, the occurence of a stock-out is a Bernoulli random variable with mean $p$ and standard deviation $(1-p)p$. Let's build the vector of stock-out events:
seqs <- seq_along(demands)
orders_over_p_days  <- tapply(demands, rep(seqs, each = p)[seqs], FUN = sum) # vector of length N
stock_outs <- orders_over_p_days > C # logical vector, 0 if we had enough burgers for p days otherwise 1

The Monte Carlo method estimates the probability $p$ of a stock-out event using the sample mean of this vector. In other words:
$$\hat{p}_N=\frac{\sum_{i=1}^N p_i}{N}$$
$\hat{p}_N$ is the Monte Carlo estimator. Note that for each $i$, $p_i$ is either 0 (no stock-out) or 1 (stock-out). For example, in our case the value of the Monte carlo estimator is
phat <- sum(stock_outs)/N
> phat
#[1] 0.488

Since we have independent and identically distributed samples $p_i$, then, for $N\to\infty$, the distribution of this random variable
$$Z_N=\sqrt{N}\frac{\hat{p}_N-p}{\sqrt{(1-p)p}}$$
converges pointwise to a standard normal distribution. You can use this result to get approximate confidence intervals for your estimate of $p$, and from that, an estimate for the number of runs required to estimate $p$ to within a tolerance $\epsilon$, with a confidence level $\gamma$. Skipping the math, an approximate expression for $N$ would be
$$N=\frac{(1-p)p\left(\Phi^{-1}(\frac{1+\gamma}{2})\right)^2}{\epsilon^2}$$
where $\Phi^{-1}(x)$ is the quantile function of the standard normal distribution. Clearly, there is a problem here: the estimate for $N$ contains the unknown $p$. A practical solution is to run the Monte Carlo simulation for an initial number of runs, say, $N_{in}=500$, and compute $\hat{p}_{N_{in}}$. Using $\hat{p}_{N_{in}}$ we get an initial, crude estimate $(1-\hat{p}_{N_{in}})\hat{p}_{N_{in}}$ for $(1-p)p$, which leads to the approximate estimate for the total number of runs:
$$N=\frac{(1-\hat{p}_{N_{in}})\hat{p}_{N_{in}}\left(\Phi^{-1}(\frac{1+\gamma}{2})\right)^2}{\epsilon^2}$$
In deriving this formula we implicitly used quite a crude estimate for the confidence interval. For this reason, it's a good idea to increase the number of runs with respect to what you got from this formula, and to check the behavior of your estimator as the number of runs increases.
As an illustration, let's assume a confidence level $\gamma=0.95$ and an absolute accuracy $\epsilon = 0.01$, meaning that you would like to estimate the probability of a stock-out in $p$ days with an error of $\pm 0.01$, at a confidence level $0.95$. In our example we get:
gamma   <- 0.95
epsilon <- 0.01
q <- qnorm((1+gamma)/2)
N <- ceiling((1-phat)*phat*q^2/epsilon^2)
#[1] 9599

I would usually increase $N$ consistently, but let's use $N=10000$ just for the sake of example:
N <- 10000
demands <- rnorm(N * p, mean = means, sd = lambda * means )
seqs <- seq_along(demands)
orders_over_p_days  <- tapply(demands, rep(seqs, each = p)[seqs], FUN = sum)
stock_outs <- C < orders_over_p_days

phat <- sum(stock_outs)/N
#[1] 0.4923

We can also plot the trend of our estimate against $N$:
sample_size <- seq_along(stock_outs)
phat <- cumsum(stock_outs)/sample_size
op <- par(mar = c(5, 5, 4, 2) + 0.1)
plot(sample_size, phat, type = "l", xlab = "N", ylab =expression(hat(p)))

We conclude that an (approximate) $95\%-$confidence interval for $p$ is $0.49\pm0.01$.
PS the above formula is valid if $\epsilon$ is an absolute error: if you're interested in the relative error, then the approximate formula becomes
$$N=\frac{\frac{(1-\hat{p}_{N_{in}})}{\hat{p}_{N_{in}}}\left(\Phi^{-1}(\frac{1+\gamma}{2})\right)^2}{\epsilon^2}$$
Comment: You might consider saving this to a separate, more clarified question, as an answer to that new question, the question here may wind up being closed (by NOT me, BTW, & +1 from me).
Comment: Your formula for $Z_N$ is missing a factor of $\sqrt{N}.$
Comment: I'm afraid it's more mundane than that: earlier today somebody posted a new question asking whether that formula was correct or not!
Comment: @Carl thanks for the +1 and for the info.I will save this abswerand, if a new question gets posted, I will post it again.
Comment: @DeltaIV Hello, I am sorry for leaving a comment in this old post, but where are your formulas for calculating the ideal number of trials from? Is there any paper that talks about the formula that you presented here?
Comment: @whuber good catch, thanks - fixed. Let me know if you spot anything else. Just out of curiosity, how did you notice? Do you know the formula by heart, or is it because you can quickly recall the proof? You might also have computed the variance of $Z_N$ and saw that it wasn't 1, but I don't think that's how you noticed the mistake.
Answer: In the general case, the distribution generated by your deterministic function, based on the normally distributed inputs, may not itself be normal. Nor might it be solvable in closed form. However, in either or both cases, you can analyze the resulting distribution empirically, from the results of running the Monte Carlo distribution many times, and looking at the empirical variance, and other statistical measures of interest, of the resulting empirical samples.
Of course, if your distribution is analyzable in closed form, and is Gaussian, given Gaussian input, you might be able to derive a closed-form formulae for the variance of the output distribution, as a function of the variance and mean of the input Gaussian distribution.
Comment: +1 For effort, and, I do not like downvotes that come without constructive comments, pass it forward....
Answer: There's no need to complicate this. Monitor the metric that you're calculating, then stop when it stops changing.
For instance, if you're calculating the probability of an event, then you monitor the quantity $$\hat p=\frac{n_i}{i},$$
where $n_i$ - number of observations of an event after $i$ simulations. Set a threshold such as 0.01 and then watch $\Delta p_i=p_i-p_{i-1}$ or $\delta p_i=\Delta p_i/p_i$, once $\Delta p_i<0.01$ or $\delta p_i<0.01$ stop the simulations. The former is the absolute error and the latter is relative error.
The final $i$ is the number you're looking for.
The only time this will not work if when you have to know $i$ in advance for some reason, e.g. for capacity planning purposes, and you absolutely cannot do any trial runs. In this case you have a problem. In the example above you could try approximations if you know the order of magnitude of $\hat p$. You could use Wald's formula for variance to back out $i$ like this:
$$\sigma=\sqrt{\hat p(1-\hat p)/i}$$
The problem's that if you're using variance reduction techniques (which you should) then these formulas don't work that well: they'll overestimate the number of simulations.


Como selecionar categorias e contar número de produtos de cada categoria?

Question: Estou tentando selecionar as categorias do banco de dados e contar na mesma query o número de produtos cadastrados naquela categoria. Até aí tudo bem, o problema é que não consigo que retorne a categoria quando não existe nenhum produto cadastrado, por exemplo:
SELECT t1.id,t1.nome,t1.imagem,COUNT(*) AS Quantidade_produtos
FROM categorias_produtos AS t1
INNER JOIN produtos AS t2 ON t2.ref=t1.id
GROUP BY t1.id

Tenho as categorias:
categoria1
categoria2
categoria3

Produtos:
produto1 -> categoria1
produto2 -> categoria1
produto3 -> categoria2

Gostaria que o resultado da query fosse mais ou menos assim:
ID |   Nome   | Quantidade_produtos
 1 |categoria1|         2
 2 |categoria2|         1
 3 |categoria3|         0

Porém a query não me retorna isso:
ID |   Nome   | Quantidade_produtos
 1 |categoria1|         2
 2 |categoria2|         1

Está ignorando as categorias que não possuem nenhum produto cadastrado:
 3 |categoria3|         0

Alguma dica pra conseguir listar todas as categorias com a quantidade de produtos?
Answer: Invés de INNER JOIN com a tabela de produtos faça LEFT JOIN:
SELECT t1.id,t1.nome,t1.imagem,COUNT(t2.*) AS Quantidade_produtos
FROM categorias_produtos AS t1
LEFT JOIN produtos AS t2 ON t2.ref=t1.id GROUP BY t1.id

Pois o LEFT JOIN ele irá pegar tudo desde que contenha o registro na tabela a esquerda, já no inner ele teria de possuir o id nas duas tabelas para ele poder retornar um resultado para aquela linha e quando não possui o registro na tabela de produtos, ele irá ignorar essa linha caso seja usado inner join, por isso o uso de left join é o correto
Comment: @LeonardoPatricio só uma dica, edite sua pergunta, adicionando a explicação do `LEFT JOIN` nela. Fica mais fácil para ser lida como resposta do que como comentário por quem não está habituado com o modelo do SO (no caso visitantes desavisados)
Comment: Por que left join? poderia complementar a resposta explicando a diferença?
Comment: LEFT JOIN ele irá pegar tudo desde que contenha o registro na tabela a esquerda, já no inner ele teria de possuir o id nas duas tabelas para ele poder retornar um resultado para aquela linha e quando não possui o registro na tabela de produtos, ele irá ignorar essa linha caso seja usado inner join, por isso o uso de left join é o correto.
Comment: hmmm, fiz isso e me retornou quantidade 1 para todos que tinha 0, os outros ficaram certo
Comment: altere o COUNT(*) para COUNT(t2.ref), pois ae ele só vai contar os registros da tabela de produtos e não das duas tabelas. Qualquer dúvida é só dizer.
Comment: perfeito, muito obrigado :D
Comment: Marque como resolvida a questão. Obg.


Azure Bot Service: 'build.cmd' is not recognized as an internal or external command, operable program or batch file

Question: When I am trying to create my web-app bot, i am unable to find the build.cmd files (among the many files that are shown on those youtube tutorial videos) and i am unable to redeploy my bot after making changes on the online code editor. Please help! Thank you.
e
** I found that it might be because i chose the Node.js SDK version instead of C#. How can i re-deploy my online code editor scripts for the Node.js version?
Comment: Can you  clarify a bit more? You went on azure to create the bot, then  what? Pulled the  code down to locally make changes? Now you want to redeploy it to azure?
Comment: A number of the youtube videos are severely outdated  (even ones as recent as the beginning of this year). can you link what videos  you were watching?
Comment: Hi @JJ_Wailes,

I created a Web App Bot on azure, then i went to the online code editor (under the Build option) to edit some codes like change the DefaultNoAnswer replies and so on. But afterwards, I could not find a way to redeploy my scripts. The instructions written in the Build option said to run 'build.cmd' inside the console to save and redeploy my changes. BUt there wasnt any 'build.cmd' file available.

I think this is bc i chose Node.js SDK while creating my bot instead of C#. May i know how can we redeploy our scripts through the online code editor if we are using node.js sdk?
Comment: If you changed the code actually  ON azure, and didn't pull it down to your local machine, there is nothing to "redeploy". To (re)deploy, you're taking local code and pushing it to the azure servers. Your code never came off the azure servers. It's got nothing to do with the language you're using.
Comment: Is there any issues with your code? Ignore the whole 'redeploy' bit. If you change your code, and save it, and go back to 'test in webchat', does your bot reflect your changes?
Answer: There is no need to "redeploy" your code. I'm not sure what you're following as a tutorial, but that is an incorrect instruction. Code that is already on Azure is already deployed. You don't need to deploy it.
To get the 'build.cmd' bit out of the way: There is a portion on Azure that says this:

This is wrong. If the bot is C#, you have to run 'build.cmd' to recompile all the files, but if it's node, you can ignore it. I'll be reaching out to a member of the azure team to correct this.
As to making changes on  Azure. If you click the link from the image above, you go to the online code editor. You can make changes to  your code there, and simply save the files. For example, create the bot in Azure, then test in webchat:
NEW BOT, CREATED ON AZURE:

Once the deployment/creation is completed, you can go into the code editor and make changes:
MY CODE IN THE EDITOR

At this point, you want to watch one thing. In the upper right is a small icon that will either say 'dirty' or 'saved'. You can see in my image that it says 'saved'. Azure will auto save changes you make periodically, so you don't need to save yourself. Once that icon says 'saved', you hit the 'run' button on the vertical bar on the left (the 'play' button, top button in the lower section):
SAVE ICON

Two things will happen at this point: first, the output pane will open on the code editor, telling you that your server is being restarted:
OUTPUT PANE

And the second is that a new window will open, going to the page YOURBOTNAME.azurewebsites.net. As bots created on Azure don't have static webpages, this will show a simple page with  a "code":"ResourceNotFound". You can close this window.
Go back to azure, and to the 'test in webchat' for your bot. Hit the 'Start over' button on 'test in webchat'.
MY NEW WELCOME MESSAGE, FROM ONLINE CODE CHANGES


Authorship of Toccata and Fugue in D Minor, BWV 565

Question: An earlier question mentions the disputed authorship of Bach's Toccata and Fugue in D minor, BWV 565. Several musicologists allege that the work has stylistic elements that are problematic for the period in which it was supposedly written, while others present various explanations justifying the unusual traits, and still others appear not to take the authorship question seriously.
What's the scholarly consensus here? How serious is the BWV 565 authorship question? Is it just a curiosity, or does it have any significant ramifications for musicology?
Answer: Generally speaking, a minority of Bach scholars question the piece's attribution. Christoph Wolf, who is for many the top Bach authority does not question the piece's attribution at all.
For what it's worth, the mark's against Bach's authorship can mostly be explained away. There is no direct evidence against his authorship, unlike some other works where the authorship is more easily disputed.
Just to take two:

Parallel octaves throughout the opening of the toccata

Writing Parallel octaves, while strictly forbidden in counterpoint is a very natural thing to do on an organ, especially if youre options for registration are limited. Essentially, to make the organ play louder a composer would have to write harmonies with more notes. Bach wrote many pieces to demonstrate how loud, and powerful the organs he was using were.

True subdominant answers in the fugue

This is perfectly normal in Bach's work, and was known before Bach's time. Buxtehude did this.
There are many theories for why the piece is so different (it was written for Violin, or by a younger, more improvisatory Bach)
Compared to other pieces accused of being misattributed, for instance the Albinoni Adagio in G minor (which is certainly forged), there is little direct evidence to prove or disprove Bach's authorship. Just criticism of style.
This forum thread has some interesting discussion on the topic: http://classicalmusicmayhem.freeforums.org/bach-attrib-toccata-fugue-in-d-minor-bwv-565-t1818-30.html
As of today, no one has definitively proven it wasn't Bach.
Comment: Nice answer, thank you! I'm curious about the parallel octave claim in particular, and can't seem to track it down. The majority of "parallel octaves" I can think of in the opening don't even deserve that term since they are simply doublings of a single voice. If that counted as parallel octaves, then you'd be committing a contrapuntal error every time you had the flute play along with the violins or the basses play along with the cellos! Do you have a link to the original parallel octave claim?
Comment: It's on wikipedia - http://en.wikipedia.org/wiki/Toccata_and_Fugue_in_D_minor,_BWV_565 - and yes, these octaves can be thought of as "orchestration" octaves.
Comment: Hmmm, if even Wolff gives credence to the idea (even if only to say they exist simply to compensate for a poor organ), then there must be more to it than just the doublings I'm talking about. The wikipedia article doesn't get specific about where they are, but it must be more explicitly contrapuntal than those doublings to even warrant mentioning.
Comment: What about the basso continuo missing from that piece as well its general structure and  style, quite unchareacteristic of Bach's keyboard pieces?
Comment: "especially if your options for registration are limited": also, if the piece calls for a unison passage, why _not_ use both hands?  What's the other one going to do?  Hold a lighter in the air?
Answer: A theory I heard from an organ builder (no idea whether it was his own one or from somewhere else) is that it was an organ test piece (Bach was a feared organ tester and likely a driving force for several innovations by Silbermann who tried to get the better of him).  The alternation of high, fast, sparsely registered passages with low fully registered descending passages ending in full chords has large differences in air usage.  Without compensating bellows ("Schwimmerbälge", nowadays standard), the inertia of the weighted large main bellows would not accommodate the sudden changes in air usage and would starve the start of the heavy passages and overblow the start of the light passages.
Part of what makes the piece flashy for human listeners (in spite of not being of the same counterpuntal complexity one is used to with Bach) is also making it hard work for the organ, and it tends not to work well on unmodified organs predating the later Silbermann period.
Answer: On the other hand, the earliest known copy was not in Bach's hand, nor is the composer listed. It is full of Italian musical directions and articulation marks that are completely uncharacteristic of Bach. It was first attributed to Bach in a collection of organ works prepared by Felix Mendelssohn — but we don't know why he made the attribution. It was in his repertoire and he simply liked it. In other words, while you can't disprove Bach's authorship, you can't prove it either. There is no hard evidence either way.
It is a lovely piece, whoever wrote it.
Comment: This answer is sadly factually wrong, which is why I've reluctantly downvoted it. While we do not have a copy in Bach's hand (which is also the case for other works, including a good few whose authorship is beyond reproach), there is indeed at least one manuscript copy (dating well before Mendelssohn) which lists him as composer (ex., dated mid 18th century: https://www.bach-digital.de/receive/BachDigitalSource_source_00001657).


Perl DBD::MySQL execute doesn't support string parameter after limit keyword. Always treated as number

Question: We recently set up a new OS with up-to-date DBI MySQL, Perl, etc.
This pattern in found several of our applications, and is breaking when installed on the new OS.
my $sth = $dbh->prepare('select null colname, null colname2 limit 0'
        . ' union all select x, y from tbl where col like ?'
        . ' union all select z, a from tbl2 where col like ?');
$sth->execute('%test%', '%test%') or die ...;

The error is a MySQL Syntax error.
We've identified the issue in the way parameters are quoted.
In the above example, it resolves like this at MySQL.
select null colname, null colname2 limit 0
union all select x, y from tbl where col like
union all select z, a from tbl2 where col like

However, if '%test%' is swapped out with numbers (e.g. '555'), it comes through.
select null colname, null colname2 limit 0
union all select x, y from tbl where col like 555
union all select z, a from tbl2 where col like 555

Notice the absence of quotes.
We've identified this as being related to presence of the limit keyword. Removing the keyword solves the syntax error.
select null colname, null colname2
union all select x, y from tbl where col like '%test%'
union all select z, a from tbl2 where col like '%test%'

Also, setting '555' in Perl now results in '555' at MySQL, with quotes.
We found that using a derived table is the quickest way to resolve right now,
select * from (select null colname, null colname2 limit 0)a
union all select x, y from tbl where col like '%test%'
union all select z, a from tbl2 where col like '%test%'

(tried just parenthesis, but needed derived table to work) but I am curious if there's a way to control the quotation method through the DBI/DBD::MySQL interface instead. (avoiding an update to the statement)
Either change default behavior to disable the limit keyword logic
or, to force a particular parameter type as string?
Answer: Parsing of commands containing LIMIT is buggy. Try DBD::MariaDB instead which has hopefully already fixed the issue (here).
Answer: Does your updated OS include a newer version of MySQL? The documentation for UNION in MySQL says this:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

And this:

To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. The following example uses both clauses:
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;

So I think you need to add some parentheses to your SQL.
Comment: I tried just parenthesis but somehow it didn't solve the problem like a derived table was doing.


Database connection in Visual Studio

Question: Alright, I have done this a bunch of times on my faculty but this time I just can't make it work..
I built a simple test app and it still does not work.
private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string _connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\data.mdf;Integrated Security=True";

            string insertSql = "INSERT INTO T_TEST " +
            "(Name, Age) VALUES " +
            "('Test', 21)";
            using (SqlConnection connection = new SqlConnection(_connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = insertSql;
                /*command.Parameters.Add(new SqlParameter("@Name1", "testName"));
                command.Parameters.Add(new SqlParameter("@Age1", 21));*/
                connection.Open();
                command.ExecuteNonQuery();
                Console.WriteLine(command.ExecuteNonQuery());
                connection.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

Console output always returns 1. And the whole code seems like it working but when I close the program and check the DB its empty..
Yes I set the "Copy" option to "Copy if newer".
And do I need to close the connection every time I open it? Since on our faculty we didn't close it ever at all.
And can anyone explain what are .Net and vb.net?
Thank you.
Comment: This is not pure C++, because the identifier '`public`' is not placed before function definitions.  Maybe you tagged this incorrectly?
Comment: VB.Net is a version of Visual Basic developed by Microsoft that uses the .NET framework.  The idea was to have executables written in different languages share common resources (including code), so MS created the .NET framework and created .NET versions of other languages.
Comment: What do you mean in the first comment?
Comment: I changed it. Anything related to my problem? :S
Comment: @drescherjm that's not even C++/CLI, that's C#.
Comment: Are You looking into the correct database (file)?
Comment: Soon as I used full path to DB it started working. But will it work on another PC since the path wouldn't be the same?
Answer: Try This Code ...
SqlConnection sqlcon = new SqlConnection("<< Your Connection String Value >>");
    sqlcon.Open();

    SqlCommand sqlcom = new SqlCommand();
    sqlcom.Connection = sqlcon;
    sqlcom.CommandType = CommandType.Text;
    sqlcom.CommandText = "INSERT INTO Jobs(JobType,JobCreation,JobStatus) VALUES (@job_type,@job_createtime,@job_iscompleted)";

    sqlcom.Parameters.Add("@job_type", SqlDbType.SmallInt).Value = (Int64)comboBoxJobType.SelectedIndex;
    sqlcom.Parameters.Add("@job_createtime", SqlDbType.DateTime).Value = DateTime.Now;
    sqlcom.Parameters.Add("@job_iscompleted", SqlDbType.Bit).Value = 0;

    sqlcom.ExecuteNonQuery();
    sqlcom.Parameters.Clear();

    sqlcon.Close();
    sqlcom.Dispose();

Database connection in Visual Studio


Next Occurance of day of next week (Specifically, the next occurance of Wednesday) based on the current date

Question: In Oracle SQL Developer, how does one determine the calendar date of the next occurrence of Wednesday, based on the current date.  I have searched and seen many examples for Ruby, PHP, MYSQL, but not for oracle sql.  I read this article about DATETIME calculations, but these we have not gone over in class.  We are working with date conversion, case, when, timestamps, and intervals but I'm not sure how to go about this problem.
Answer: Nex_day function will return the date of the first weekday, specified as the second parameter of the function, later than a date specified as the first parameter of the function. For example:
SQL> select next_day(sysdate, 'WEDNESDAY') next_day
  2    from dual
  3  ;

NEXT_DAY
-----------
05-DEC-2012

Answer: You can use DATE function called NEXT_DAY
Try this
SELECT NEXT_DAY(SYSDATE,'WEDNESDAY') "Next WED"
  FROM DUAL ;


Incorrect integer value for INET_ATON

Question: When I try to insert an IP into my database as an integer using the INET_ATON function:
insert into network (NwID,IP,Subnetz) values ('1','INET_ATON(127.0.0.1)','INET_ATON(255.255.255.0)');

it tells me that it's getting an incorrect integer value (error 1366). This is my table:
NwID: Type:int(11) Null:NO Key:PRI Default:NULL
IP: Type:int(11) unsigned NUll:NO Default:NULL
Subnetz: Type:int(11) unsigned NUll:NO Default:NULL

how do I fix this?
Comment: insert into network (NwID,IP,Subnetz) values ('1',INET_ATON('127.0.0.1'),INET_ATON('255.255.255.0'));
Comment: EDIT: It worked! I still had a trigger I didn't delete from before, thanks
Answer: SOLUTION:
insert into network (NwID,IP,Subnetz) values ('1',INET_ATON('127.0.0.1'),INET_ATON('255.255.255.0'));

Comment: Why do you my comment answer copy??? You said it's not working. So why you answer the question. You should delete your answer.
Comment: Because I still had a trigger in my db, I had forgot about. That's why the IP was null. After deleting the trigger your command worked, so it, objectively, was the right answer to my question.
Comment: Ok. It's fine for you.

Incorrect integer value for INET_ATON


Best way to fire and forget async code inside TransactionScope

Question: I'm doing some stuff inside a using block for a TransactionScope object. At some point I wanted to call some async code by firing and forget (I don't want to wait for the result, and I'm not interested in what happens during that call) and I wanted that code to not be part of the transaction (by using TransactionScopeOption.Suppress option).
So initially I made something similar to the methodFails that I have commented in the code below. It got me a nice "System.InvalidOperationException: 'TransactionScope nested incorrectly'". I looked up in SO for somebody having similar problems, and found this Question where the answer by ZunTzu gave me the idea for method1 using TransactionScopeAsyncFlowOption.Enabled option, which works as I expected for methodFails but without the exception.
Then I thought of an alternative that I put in method2 that consists in putting the async code in a third method (method3) called by firing-and-forget while the TransactionScopeOption.Suppress option is kept in the non-async method2. And this approach seems to work as good as method1 in my sample program.
So my question is: which approach is better, method1 or method2, or maybe a third one that I have no thought about? I'm leaning for method1 because it sounds like "the people making the TransactionScope class put that TransactionScopeAsyncFlowOption there for a reason". But the fact that TransactionScopeAsyncFlowOption.Enabled is not the default for a TransactionScope makes me think that maybe there is a performance hit by enabling that, and fire-and-forget may be a special case where I can save that performance hit.
The sample code:
    class Program
    {
        static void Main(string[] args)
        {
            using (TransactionScope scope1 = new TransactionScope())
            {
                // Do some stuff in scope1...

                // Start calls that could execute async code
                //Task a = methodFails(); // This commented method would launch exception: System.InvalidOperationException: 'TransactionScope nested incorrectly'
                Task b = method1(); // Fire and forget
                method2();

                // Rest of stuff in scope1 ...
            }
            Console.ReadLine();
        }

        static async Task methodFails()
        {
            //Start of non-transactional section
            using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
            {
                //Do non-transactional work here
                Console.WriteLine("Hello World 0.1!!");
                await Task.Delay(10000);
                Console.WriteLine("Hello World 0.2!!");
            }
            //Restores ambient transaction here
            Console.WriteLine("Hello World 0.3!!");
        }

        static async Task method1()
        {
            //Start of non-transactional section
            using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            {
                //Do non-transactional work here
                Console.WriteLine("Hello World 1.1!!");
                await Task.Delay(10000);
                Console.WriteLine("Hello World 1.2!!");
            }
            //Restores ambient transaction here
            Console.WriteLine("Hello World 1.3!!");
        }

        static void method2()
        {
            //Start of non-transactional section
            using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
            {
                //Do non-transactional work here
                Task ignored = method3(); // Fire and forget
            }
            //Restores ambient transaction here
            Console.WriteLine("Hello World 2.2!!");
        }

        static async Task method3()
        {
            //Do non-transactional work here
            Console.WriteLine("Hello World 2.1!!");
            await Task.Delay(10000);
            Console.WriteLine("Hello World 2.3!!");
        }
    }

Comment: If you just want to run your code in fire-and-forget outside of the transaction scope, I'd say it's a good use-case for `Task.Run`
Comment: @Kevin Gosse I read some time ago in Stephen Cleary's blog that Task.Run should be for CPU bound code. In my production code, the "Task.Delay" call is in fact a stored procedure call that takes several seconds to complete, so I think it fits better in the async-await scenario
Comment: That's the kind of comment that sometimes make me wonder if that blog article didn't hurt more than it helped. `Task.Run` is useful whenever you want to offload work to another thread. It rarely makes sense for I/O bound operations and it's an easy-to-make mistake, that's why Stephen made the approximation "Task.Run = CPU bound". But it doesn't mean you shouldn't use it when it helps you, as long as you understand what it does
Comment: I interpret that article along the lines of "if it there is a (reasonable) way to get the I/O job done with async-await, go with that". In my case, I don't see any of the two options I initially posted being a bad way to solve the problem, and async-await syntax conveys a little bit better than Task.Run the nature of the work being done. But I agree with you that it's worth evaluating all the tools available.
Answer:
But the fact that TransactionScopeAsyncFlowOption.Enabled is not the default for a TransactionScope makes me think that maybe there is a performance hit by enabling that, and fire-and-forget may be a special case where I can save that performance hit.

TransactionScopeAsyncFlowOption.Enabled was introduced for backward compatibility purposes when they fixed a bug. Strangely, you don't benefit from the bug fix unless you "opt in" by setting this flag. They did it that way so the bug fix didn't break any existing code that relied on the buggy behavior.
In this article:

You might not know this, but the 4.5.0 version of the .NET Framework contains a serious bug regarding System.Transactions.TransactionScope and how it behaves with async/await. Because of this bug, a TransactionScope can't flow through into your asynchronous continuations. This potentially changes the threading context of the transaction, causing exceptions to be thrown when the transaction scope is disposed.
This is a big problem, as it makes writing asynchronous code involving transactions extremely error-prone.
The good news is that as part of the .NET Framework 4.5.1, Microsoft released the fix for that "asynchronous continuation" bug. The thing is that developers like us now need to explicitly opt-in to get this new behavior. Let's take a look at how to do just that.

A TransactionScope wrapping asynchronous code needs to specify TransactionScopeAsyncFlowOption.Enabled in its constructor.
Comment: Interesting article, in special the part clarifying why is not the default value. The doubt I still have is that `method2` is not async, although it calls an async method, so maybe there I'm not "wrapping asynchronous" code. Anyway, I think I will avoid premature optimizations, that maybe even are not an optimization, and go with the "Enabled" option. Thanks!
Answer: You could call your async methods within a HostingEnvironment.QueueBackgroundWorkItem call.
HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
    await LongRunningMethodAsync();
});

QueueBackgroundWorkItem is summarized as follows:

The HostingEnvironment.QueueBackgroundWorkItem method lets you
  schedule small background work items. ASP.NET tracks these items and
  prevents IIS from abruptly terminating the worker process until all
  background work items have completed.
Comment: Didn't know about that QueueBackgroundWorkItem, sounds good but... unfortunately for this specific problem I'm not in an ASP.NET environment.


Using different conda envs with Sublime REPL

Question: I'm trying to set up Sublime Text 3 as a multilingual editor for doing data science.
For this I use Sublime REPL for executing code in Sublime, and intend to use Anaconda's (continuum analytics) built in virtual environments to make a venv for each project.
Unfortunately, the virtualenv option in Sublime REPL does not seem to support environments made with conda create.
By default it seems that Sublime REPL is using the root copy of python in anaconda, as it prints this information.
Python 3.5.1 |Anaconda 4.1.0 (x86_64)| (default, Jun 15 2016, 16:14:02)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

However, even trying fixes proposed by other questions:
Sublime text3 and virtualenvs and
How Do I Setup SublimeREPL with Anaconda's interpreter? once things are set up I get an error
PermissionError(13, 'Permission denied')

When I try to point at a virtual env created with conda create.
Is there any way to make Sublime REPL execute code with a particular conda environment? Or do I need to avoid the Anaconda distribution and use a manual install of python and virtualenv?
Answer: This question might be a duplicate for this one.
As explained in the answer above, you can extend the list of usable python versions:
(Almost a) Quotation from the answer above:
In your Packages/User folder, create SublimeREPL/config/Python/Main.sublime-menu with the following contents:
[
    {
        "id": "tools",
        "children":
        [{
            "caption": "SublimeREPL",
            "mnemonic": "r",
            "id": "SublimeREPL",
            "children":
            [
                {
                    "caption": "Python",
                    "id": "Python",

                    "children":[
                        {
                            "command": "repl_open",
                            "caption": "Python - YourVirtualEnv",
                            "id": "repl_python",
                            "mnemonic": "p",
                            "args": {
                                "type": "subprocess",
                                "encoding": "utf8",
                                "cmd": ["/path/to/your/virtualenv/bin/yourPythonVersion", "-i", "-u"],
                                "cwd": "$file_path",
                                "syntax": "Packages/Python/Python.tmLanguage",
                                "external_id": "python",
                                "extend_env": {"PYTHONIOENCODING": "utf-8"}
                            }
                        },
                        {
                            "command": "repl_open",
                            "caption": "IPython - YourVirtualEnv",
                            "id": "repl_python_ipython",
                            "mnemonic": "p",
                            "args": {
                                "type": "subprocess",
                                "encoding": "utf8",
                                "autocomplete_server": true,
                                "cmd": ["/path/to/your/virtualenv/bin/yourIPythonVersion", "-u", "${packages}/SublimeREPL/config/Python/ipy_repl.py"],
                                "cwd": "$file_path",
                                "syntax": "Packages/Python/Python.tmLanguage",
                                "external_id": "python",
                                "extend_env": {
                                    "PYTHONIOENCODING": "utf-8",
                                    "SUBLIMEREPL_EDITOR": "$editor"
                                }
                            }
                        }
                    ]
                }
            ]
        }]
    }
]

If you're on Windows, either use a single / as path delimiter, or double \:
c:/Anaconda/bin/python.exe
# or
c:\\Anaconda\\bin\\python.exe

Save the file, and you should now have Tools -> SublimeREPL -> Python -> Python - Anaconda and IPython - Anaconda menu options to start REPLs with the Anaconda interpreter.
If you have multiple versions of Python installed (for example, 2.7
and 3.3) or multiple virtualenvs you can just duplicate the children contents and alter the
caption and cmd paths appropriately.


How to add two random variable's pdf?

Question: X,Y are independent random variables.
X's pdf = f(x)
Y's pdf = g(x)
if Z= X+Y
what is the Z's pdf?
Can it be calculated?
Comment: The *first hit* upon Googling the very title of this question produces a good answer: please read our faq about the wisdom of doing a little bit of research before asking a question.
Comment: @whuber but now this question is ;)
Answer: Reference: http://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter7.pdf
If $X$ and $Y$ are two independent, continuous random variables, then you can find the distribution of $Z=X+Y$ by taking the convolution of $f(x)$ and $g(y)$:$$h(z)=(f*g)(z)=\int_{-\infty}^{\infty}f(x)g(z-x)dx$$If $X$ and $Y$ are two independent, discrete random variables, then you can find the distribution of $Z=X+Y$ by taking the discrete convolution of $X$ and $Y$:$$\mbox{P}(Z=k)=\sum_{i=-\infty}^{\infty}\mbox{P}(X=i)\cdot\mbox{P}(Y=k-i)$$
Comment: It's pretty much the same as what I've written above. $X-Y$ is the same as $X+(-Y)$. The distribution of $-Y$ is the same as the distribution of $Y$ except that it is mirrored over the vertical line at 0.
Comment: Thank you~Can I also ask if Z2=X-Y,what is the pdf of Z2? (This time I have do the search and couldn't find the answer)(Should I post another question or just here is ok?)
Answer: If $A$ is the domain for $f(x)$ then $h(z)=\int_{x\in A}f(x)g(z-x)\,dx$.
A sum would be used in the discrete case.

How to add two random variable's pdf?


Backups devices for Windows Server Backup and Symantec

Question: What is the best way to backup windows SQL, Exchange or AD servers data to?
NAS, external USB , iSCSI or perhaps some other backup solution?
I will not however be considering cloud backup solutions due to bandwidth restrictions and cost.
Currently I find NAS devices to give the best results but clients that do not have the budget for backup software use Windows Server Backup but then they can make only 1 backup to a NAS at a time.
Answer: You can not answer this question without knowing more about the specific scenario. There is no "best" way, it depends on the use case. Network topology, location, cost, bandwith, available equipment, size of the network and so on. For a small SOHO it may be best to backup to external USB drives because it's cheap and reliable but you won't see that in a Fortune 500 company...So this question can't be answered without knowing details.


Sine Wave With Alternating Wavelength

Question: Please Read Everything Fully and Carefully Before Responding!!
I'm trying to formulate parametric equations for a sine wave where the wavelength grows by a constant on alternate sides, in this case, 1.3, and where  the amplitude decreases in an inverse manner. (See my image. It MUST be noted that the image probably does NOT look like the actual, properly graphed wave will!)
To give you an idea of the sort of equations i'm looking for:
$$y(t)=(function)$$
$$x(t)=sin(t)(function)^{-1}$$
NOTE. I'm using the term 'wavelength' in a way that is, to my understanding not in conformity with the standard definition. But, the above image should clarify what I'm talking about satisfactorily.
NOTE. A note to everyone: I'd rather deal with this problem in the form that is given by my example equations, unless there is some issue with doing so...
Comment: I'd suggest a function of the form $f(x)\sin g(x)$.
Comment: @GEdgar, yes, they ought to grow/shrink in step and in inverse. (See the example equations.
Comment: @LordSharktheUnknown, thank you for the input. Can you elaborate?
Comment: $x=1.3^t,y=1.3^{-t}\sin\pi t$.
Answer: There's a lovely function $y = f(x)$ which is simply turned into a parametric equation by defining it as $\langle t, f(t) \rangle$.
Therefore, $$y = \cos\left(\pi\left(\frac{\ln\Big(\big(x+\frac1{r+1}\big)(r^2-1)+1\Big)}{\ln r}\right)\right)$$
For your case, $r=1.3$.
This function matches the above graph, where it starts at $(0,-1)$. If you prefer a different starting location, please drop a comment and I'll be back with an improved answer!
$$y = \cos\left(\pi\left(\frac{\ln\Big(\big(x+\frac{r^{(n)}-1}{r^-1}\big)(r^2-1)+1\Big)}{\ln r}\right)\right)$$
See the tiny $n$ in the exponent? Mess with that, and you have phase shift. You can also drop a negative in front of the cosine, or change it to sine, or etc. Just to preempt any questions.
Alrighty!
$$\langle\frac{r^{2t}-r^{n}}{r^{2}-1},r^{\left(\frac{r^{2t}-r^{n}}{r^{2}-1}\right)}\cos\left(2\pi t\right)\rangle$$
Comment: @JinnyEcckle Sorry it took me so long to get back on this. The relevant formulas and parameters are here: https://www.desmos.com/calculator/mi3sauwzvn. There is a parametric way to do this (from which you can see my method for solving the problem: geometric series!) but it doesn't seem to be any neater than the original. Especially when you throw in amplitude. Nonetheless, enjoy!
Comment: Thank you so much! I love your function. It is indeed absolutely beautiful! I want to accept it as the answer. I will if you're willing to post something that will make it correspond to this https://www.desmos.com/calculator/wwqngyymh4 for $$x(t)$$

By this I mean, I want the wave's height to decrease to the same degree that its wavelength increases. A good way of thinking about this is that the answer will fit on a hyperbolic type shape.

Thank you again so much!
Comment: See this link for what I mean with the hyperbolic shape:
https://www.desmos.com/calculator/notnadmsbf
Comment: A note: My intuition has lead me to think that this will be easier to work on parametrically.
Comment: Thank you! Brilliant work!

Sine Wave With Alternating Wavelength


How to search Github GraphQL users by Company

Question: I want to find all users that have set their "Company" field in their Github Homepage to "Github".  I see it is a defined field in the Github Docs at https://developer.github.com/v4/object/user/.  However, I can't seem to search for it.
My current query on https://developer.github.com/v4/explorer/ returns no results
{
  search(query: "company:Github", type: USER, first: 100) {
    userCount
    edges {
      node {
        ... on User {
          login
          name
          company
        }
      }
    }
  }
}

Answer: To search all users by the company, query on the organization. Currently, you are passing a key-value pair as a string to search for instead of value string. Try this query to get all list of employees who have set their company name Github.
{
  organization(login: "github") {
    email
    members(first: 100) {
      totalCount
      nodes {
        ... on User {
          company
          login
          name
          isEmployee
        }
      }
    }
  }
}

See the results in the attached image:


Selecting the appropriate algorithm for creating and calculating permutations of element-sharing pairs

Question: I am interested in what algorithm would have the lowest time complexity for performing the following task:
Given a list of tuples, such as [(A, B), (B, C), (C, D), (D E), (A, D), (E, A), (A, C)],
find sequences such as [A, B, C, D, E, A] or [A, D, C, B, A], which start and end with the same letter and are being formed by joining pairs that share at least one element of the tuple. Note: (A, B) is being considered to be the same as (B, A), just like (A, C) is the same as (C, A), so it can be used to create both pair (C, B, A, C) or (A, B, C, A)
The important constraint is having a limit on the length. E.g. making sure that sequence is no longer than 7 total elements.
I've attempted to solve this problem by expanding the tree one element at the time until the max length of 7 is reached, but I am curious if there are better approaches to solving this problem. Thank you so much and looking forward to hearing your great ideas!
Comment: So when you have (A,B), then (A,B,A) is a solution? Or is there a constraint that a tuple can only be used once?
Answer: Time Complexity
The (worst-case) time complexity of any algorithm for solving this problem will have a lower bound of O(n) where n is the number of edges (i.e. tuples) of the graph:

In case you need to find all cycles from A to A, you cannot exclude looking a certain edge, as it might well be part of one such cycle.
In case you need to find any cycle from A to A, you might be in a situation where there is only one such cycle, and in the worst-case you may find that the last edge you visit is the one closing the cycle.

So in either situation, you (may) need to look at each edge at least once.
Algorithms
In essence there are two strategies: breadth-first or depth-first search. Both have a time complexity of O(n).
The algorithm you seem to have tried with is a breadth-first search. It is the better choice when you need to find the shortest cycle, because then you can exit the algorithm as soon as you find a cycle (A-to-A).
A depth-first search is also a viable option, certainly when there is a limit set to the length of the cycle. In that case the space complexity is O(m), where m is the maximum length of a cycle. Depending on the graph (its size, its average branching factor), this could be much cheaper than the O(n) space that a breadth-first search requires.
Also, a breadth-first search needs to constantly switch states, while the transitions that occur during recursion and backtracking (characteristic of a depth-first search) are often easier to deal with.
Preparations
Whichever strategy you use, make sure to first create an efficient data structure for the graph.
The simple data structure that consists of an array of pairs (like depicted in your question) is not good enough. For achieving the optimal time complexity, you need to build an adjacency list (or something similar), so you can find a node's neighbors (reachable via one tuple) in constant time.
Comment: Thank you so much, Trincot! What would you recommend in this situation? Imagine that (A, B) has a cost of 0.8, while (B, C) has a cost of 0.6, and (B, D) has a cost of 0.7, Both (C, A) and (D, A) have equal cost. Our goal is to find the lowest cost, which would be 0.8 + 0.6 + equal_cost < 0.8 + 0.7 + equal_cost. The important thing here is that we don't stop finding "A to A", but rather on "maximum length" of the sequence, such as 6. And out of all sequences that have length of 6, we need to find the one with the minimum cost. Thank you!
Comment: Usually [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Algorithm) is used for such a scenario. In this case you would not extend paths when they are longer than 6, and you would not stop when finding the target node with shorter length. But when you find it with a length of 6, you'll be sure to have the path with minimal cost. See also [A* algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm).


What is this japanese wooden instrument called?

Question: Yesterday I stumbled upon an interesting percussion instrument:

(Instrument at 3:28 of the video)
The instrument takes the form of an oblong wooden block with 12 small round holes (6 at each far end, spaced evenly along the smaller width) connected by some sort of cut-out-trenches in a more or less aestethic manner. It seems to be played the same way a xylophon is played, the trenches/barriers likely modifying the way vibrations propagate, thus modulating the eventual sound.
quick screen-grab...
Comment: I'm voting to close this question as off-topic because instrument identification questions are off-topic.
Comment: Oh wow. Did the rules change?
Comment: If someone asked me why this is "off-topic", I couldn't explain them.
Comment: @dot_Sp0T it's always been off topic as per the FAQ https://music.stackexchange.com/help/on-topic
Comment: @Dom that's the thing. I'm pretty sure I checked the faq when asking the question. Probably even additionally tried to raise someone on the general chat to ask for advice with the new stack. But either way I got an answer and it was good.
Answer: It's a tongue drum, slit (slot?) drum, sometimes called a log drum. Not particularly Japanese, maybe U.S. I think.
Probably one of the oldest instruments used by Man. Originally made from hollowed out logs - hence log drum, used for sending messages (jungle drums?) and can be made from metal, in a way resembling steel pans, but with vibrating tines instead. It belongs to the idiophone family.
Made from wenge wood for the top (tines), and padouk for the sides and bottom, as resonators. Often tuned in pentatonic - so could be construed as 'Japanese', possibly. Usually an octave and a half/ two octaves, C and F seem to be common, but some just produce a more percussive than pitched sound.