Tratamento de string - como separar número decimal de texto na string?

Question: O algoritmo abaixo da um ping no host e faz todo o tratamento até pegar a parte específica que eu quero que é o valor da taxa do ping
<?php
$host = 'www.google.com.br';
$execPing = shell_exec('ping -c 1 ' . $host);
$vetExpl = explode("\n", $execPing);
$locStr = array_keys(preg_grep('/icmp_seq/', $vetExpl))[0];
$dadosVet = array_slice($vetExpl, $locStr, -5);
foreach ($dadosVet as $vetLinha) {
  $strVetor = explode(' ', $vetLinha);
  $tempo = preg_grep('/time=/', $strVetor);
  echo "
";
  var_dump($tempo);
}
?>

O que acontece é que a variável $tempo, que contem o valor da taxa, imprime parte texto e parte número. ex abaixo:
array(1) {
  [7]=>
  string(9) "time=69.7"
}

O que quero é pegar somente os números com o decimal, neste caso o 69.7
Testei com diversos exemplos e não consigo separar o número decimal do texto

Não posso usar indice, a posição muda conforme muda o endereço IP
usando o endereço www google com br, ele me traz a taxa na posição 7
usando endereço dentro da rede, ele me traz a taxa na posição 6
Comment: Pode mostrar o resultado de $strVetor?
Comment: Se todas as strings tiverem esse formato, você pode fazer 1 implode, ficaria
`$time = implode("=", $tempo);` e para acessar ficaria `$time[1]`
Comment: @PauloVictor não seria `explode`?
Comment: Sim, o correto de fato é explode, ficaria `$time = explode("=", $tempo);`, desculpe, fiz correndo.
Comment: Já tinha feito assim. Continua dando NULL
Comment: Tente `$time = explode("=", $tempo[7]);`
Comment: array(9) {
  [0]=>
  string(2) "64"
  [1]=>
  string(5) "bytes"
  [2]=>
  string(4) "from"
  [3]=>
  string(24) "eze03s06-in-f3.1e100.net"
  [4]=>
  string(15) "(220.127.116.11):"
  [5]=>
  string(10) "icmp_seq=1"
  [6]=>
  string(6) "ttl=39"
  [7]=>
  string(9) "time=63.0"
  [8]=>
  string(2) "ms"
}
Comment: com "$time = explode("=", $tempo[7]);" também não funciona, pois dependendo do número IP pode mudar a posição da string no array
exe: se uso 'localhost' a posição no array passa a ser 6
Comment: Andrei, coloca um exemplo de entrada e um da saída esperada... vai ficar mais fácil de te ajudarem.
Answer: Basta usar a função explode conforme abaixo.
Note que foi retornado um array, portanto você sabe a posição que precisa recuperar.
Espero ter ajudado.
<?php
$host = '192.168.0.24';
$execPing = shell_exec('ping -c 1 ' . $host);
$vetExpl = explode("\n", $execPing);
$locStr = array_keys(preg_grep('/icmp_seq/', $vetExpl))[0];
$dadosVet = array_slice($vetExpl, $locStr, -5);
foreach ($dadosVet as $vetLinha) {
  $strVetor = explode(' ', $vetLinha);
  for($i=0; $i<sizeof($strVetor); $i++){
     if(preg_match("/time/", $strVetor[$i])){
        $tempo = explode("time=", $strVetor[6]);
        echo "\n";
        echo "Tempo: " . $tempo[1];
        echo "\n";
        echo " ";
     }
  }
}
?>

Resultado:

root@79bbb258c614:/var/www/teste# php lala.php
Tempo: 0.869
  root@79bbb258c614:/var/www/teste#

Pode haver uma diferença no índice do seu array, isso dependendo da versão do teu ping. Então, testa o índice e você conseguirá achar certinho.
dê um var_dump no $strVetor e veja o índice que precisa.
Comment: Não funcionou. Estou rodando no debian
Comment: Realizei o teste antes e deu certinho... Consegue enviar o erro que deu?
Comment: ";
  echo "\n";
  echo "Tempo: " . $tempo[1];
  echo "\n";
  echo " ";

}
?> Resultado: root@79bbb258c614:/var/www/teste# php lala.php

Tempo: 1.03
Comment: aqui aparece NULL
Comment: Então, faça como comentei ali na resposta (editei ela). Dê um var_dump no $strVetor e veja qual é o índice que você tem que usar.
Comment: ele muda conforme muda o endereço IP que uso
usar 192.168.0.1 ou 10.117.10.100 é diferente de usar localhost ou endereço de sites
conforme muda o IP muda o indice que vou precisar
Comment: Cara, é simples.. basta você testar se no índice corrente, existe o tempo, e imprimir :)
Comment: Editei novamente com o ajuste que você precisa.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/91872/discussion-between-filipe-l-constante-and-andrei).
Answer: Assim funciona
<?php
$host = 'localhost';
$execPing = shell_exec('ping -c 1 ' . $host);
$vetExpl = explode("\n", $execPing);
$locStr = array_keys(preg_grep('/time=/', $vetExpl))[0];
$dadosVet = array_slice($vetExpl, $locStr, -5);
foreach ($dadosVet as $vetLinha) {
  $strVetor = explode(' ', $vetLinha);
  $tempo = preg_grep('/time=/', $strVetor);
  $str = implode('',$tempo);
  $taxa = substr($str, 5);
}
echo "
";
print_r($tempo);
print_r($taxa);
?>


How do you find system manufacturer/model on Linux without root access?

Question: I'm working on a module for Condor that will collect hardware information so that we can use realistic numbers to compute power savings, etc.  The difficulty is that I don't maintain most of the client systems, so I have to write this with no assumptions as to what may or may not be installed on the system and I can't do anything that requires root access.
I've looked at various utilities (lshal, lshw, hwinfo, etc) and none of them seem to be universal across both Debian- and RedHat-based systems.  I have neither the authority nor the desire to force other departments on campus to have one of those packages installed.
dmidecode seems to be pretty universal, but it's not helpful without root privileges.  I haven't been able to find any files in /proc that contain the system manufacturer and model.  Is there something I'm missing or do I need to try to get all of the distributed admins to install one of the aforementioned utilities?
Answer: You're going to need dmidecode to get that info-and even that isn't going to guarantee you can get the correct hardware info. It should work for Dell and HP server machines, but everything outside of their gets kind of dicey.
Comment: I've found DMIdecode works pretty well on any server/workstation grade hardware. The ulta-cheap consumer grade equipment, not so much. DMIDecode also runs on BSD systems and a variety of other *nix (YMMV).
Comment: dmidecode is a great tool, but entirely unhelpful for me in this case, since the Condor process does not run as root.  The only way it would work is if I got the administrators of the machines this will run on to make dmidecode setuid, which sounds like a bad idea.
Comment: Then you're up a creek. You're going to need something to decode the data stored in the BIOS and you need to be running as root to get to that data. The other option is to allow them to set the make/model in your app so you can make some guesses as to the amount of power its using.
Answer: It's a bit second-hand, but you might try running 'dmesg' and seeing if anything interesting is there.  Doesn't (usually) require root privs.
Answer: The files you are looking for are in /sys, not /proc.  Take a look at what's available in the directory /sys/devices/virtual/dmi/id.  For example:
$ cd /sys/devices/virtual/dmi/id
$ cat sys_vendor product_name product_version
System76
Pangolin
pang11
$ ls -l product_*
-r--r--r-- 1 root root 4096 May 24 00:09 product_family
-r--r--r-- 1 root root 4096 May  9 15:38 product_name
-r-------- 1 root root 4096 May 24 00:09 product_serial
-r--r--r-- 1 root root 4096 May 24 00:09 product_sku
-r-------- 1 root root 4096 May  9 15:38 product_uuid
-r--r--r-- 1 root root 4096 May  9 15:38 product_version

As the file permissions show, you need to be root to get the serial number or UUID, but the other information like name, version, and vendor is accessible to all users.
Comment: @MatthewIfe I don't think he needs to, though, because he didn't mention anything about needing serial numbers.  Just manufacturer and model (which are called sys_vendor and product_name here).

In any case, this information probably comes 12 years too late to be of use to the original poster.
Comment: You could potentially change the permissions with udev rules though, add a group membership for example and add condor to the group.


How can i copy from Azure to AWS?

Question: I have a file in Azure storage that i want to copy to AWS S3 bucket.
I want to have as minimal cost as possible.
I have copied from Azure storage to a local machine and then from local machine to AWS S3 bucket.
But I will be charged twice , copying to local and then to AWS.
Is there a way i can copy straight from Azure to AWS and have one cost ?
I am using the aws az cli and az cli for Azure.
UPDATE:
i HAVE A 150G file

SAVE IN AZURE STORAGE (COST) ?
Pull from Azure to local machine (COST) ?
PULL FROM LOCAL MACHINE TO AWS (COST) ?

whereas if i did the following

SAVE IN AZURE STORAGE (COST) ?
Pull from Azure Storage to AWS (COST) ?

The second scenario has one less action ?
Comment: The second scenario has one less action, but the action you removed didn't cost much to begin with. Getting data out of Azure is what you pay for, and storing data in AWS in Azure is what you pay for. You do both in both scenarios. Storing data locally, and uploading it into AWS are almost free. However, the second scenario will save you some time, which may be relevant. It's entirely possible to move data from Azure to AWS, you're just distracting everyone with reasons that aren't valid.
Comment: There is no charge for uploading to Amazon S3, except for the PUT request (`$0.005 per 1,000 requests`). Azure seems to have a similar charge for GET. Azure also seems to have a `$0.02 per GB` charge for data going to the Internet. You would need to pay these costs regardless of _how_ the data is transferred. How did you calculate that you would be "charged twice"?
Comment: well i save to Azure storage 1st cost.  Then i download from Azure to a local machine 2nd cost. Then i upload , PUT to AWS 3rd cost ?
Comment: There is a cost for getting data from Azure. You need to pay that regardless of whether you "copy straight from Azure to AWS". There is a cost for putting data in Azure. You need to pay that regardless of whether you "copy straight from Azure to AWS".  There is a cost for transferring data over the Internet. You need to pay that regardless of whether you "copy straight from Azure to AWS". So, there is no difference in S3/Blob costs as a result of how you actually perform the copy.
Comment: I have put an update in the question
Comment: So can you please explain like i have in a tabular form .. what costs what ?
Comment: To copy a file from Azure to AWS S3 bucket, you can use AzCopy to download the file from Azure storage to your local machine, and then use the AWS CLI to upload the file to S3.
AzCopy does not support direct data transfer from Azure Storage to AWS S3. AzCopy is primarily designed for transferring data between local storage and Azure Storage or within Azure Storage services. Therefore, you can use AzCopy to copy the file from Azure to Blob storage, and then use the AWS CLI to copy the file to S3.
Comment: Here are the steps to copy the file from Azure to S3 using AzCopy and AWS CLI:

1.  Download and [install AzCopy](https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-v10) and [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine.

```
Invoke-WebRequest -Uri https://aka.ms/downloadazcopy-v10-windows -OutFile \azcopy.zip
Comment: 2.  Use AzCopy to copy the file from Azure storage to Blob storage:

```
azcopy copy "https://.blob.core.windows.net//" "https://.blob.core.windows.net//?" --recursive=true

```

Replace  ``,  ``,  ``, and  ``  with the appropriate values for your Azure storage account, container, blob, and SAS token. This command copies the file from Azure storage to Blob storage using the SAS token for authentication.
Comment: 3.  Use the AWS CLI to copy the file from Blob storage to S3:

```
aws s3 cp "s3:///" ""

```

Replace  ``  and  ``  with the appropriate values for your S3 bucket and object, and  ``  with the path to the local file where you want to save the downloaded file. This command copies the file from Blob storage to S3.
Comment: so what your saying is that i need to copy to a local drive first
Answer: You can create a data pipeline in Azure Data Factory to copy data directly from Azure Blob Storage to AWS S3.
https://learn.microsoft.com/en-us/azure/data-factory/connector-amazon-simple-storage-service?tabs=data-factory
Comment: can i not do it all with az cmds ?
Comment: Yes, you can do everything with az cli that would be the DevOps way to do it.
Answer: Is there a way I can copy straight from Azure to AWS and have one cost?
No. You are using two different services and each will charge you for their part of the copy process.
Azure will charge you for:

The request to GET the file
The Data Transfer cost for sending data to the Internet

AWS will charge you for:

The request to PUT the file

Storage costs are charged "per GB month" based on how long you store the file. Thus, storage costs are not part of the cost of copying the file.

How can i copy from Azure to AWS?


Find out scale from these 3 chords

Question: I am playing these 3 chords in the following sequence:
AM - CM - DM
What scale do they belong to?
I first thought its A Mixolydian:
<code>// But this can't be it, because it doesn't have C#(used in A major)
Dorian      1   2   b3  4   5   6  b7
Dorian      A   B   C   D   E   F#  G
</code>
I tried to see if it fits Dorain:
<code>//But this can't be it because it doesn't have C note(used in 2nd chord C major of the sequence)
Myxolydian  1   2   3   4   5   6  b7
Myxolydian  A   B   C#  D   E   F#  G
</code>
This seems like a usual or common sequence of chords. How can it be so complicated? Am I missing something?
Comment: You've found a chord sequence that isn't all contained in one scale. That's OK. Did you think it wasn't?
Comment: Are you asking this to establish what key the piece is in, or to find a scale (set of notes) that you can use to solo over the chord changes? Doesn't A Mixolydian have F#? And A Dorian have F#?
Comment: @Tim Yes Fixed it. Well im looking for key, but my next step is to solo over it. So eventually i need both
Answer: The 'theory' goes as follows: it's common (and acceptable) to use chords from parallel keys. Put simply, there's always the set of 3 majors, 3 minors and a diminished that are diatonic. Let's take D as an example.
Dmaj., Em, F#m, G maj., A maj., Bm, C#o.
Now, Dm: Eo, Fmaj., Gm, Am, Bbmaj., Cmaj., Dm.
There are your 3 maj. chords!
Let's take A as an example.
Amaj., Bm, C#m, Dmaj., Emaj., F#m, G#o.
And Am: Bo, Cmaj., Dm, Em, Fmaj., Gmaj.
There are your 3 chords!
The theory, as we've said many times here (and elsewhere!) tries to explain what happens, usually in a 'human' way. It's how we are. But now that bit of 'theory' is stated, A,C and D together should make sense. It won't ever change what they sound like, though. And that is a far more important factor...
For soloing over, Am pent is a good start. It works over the Amaj, C and D with lots of complementary notes.
Comment: Im not sure i undeerstood _But now that bit of 'theory' is stated, A,C and D together should make sense. It won't ever change what they sound like, though_ this well. Theory doesnt say A,C,D to be all major(there is no such scale so i assume no such theory)...Could you explain please
Comment: You appear to be somewhat entrenched in the 'if it's not part of theory it can't be allowed' school of thought. There have been several nods towards that sentiment recently. What the theory is attempting to do, quite well usually, is explain how certain things work. Sometimes it's at a bit of a loss, and that's when ears take over, because at the end of the day, any piece will survive better if it sounds good, rather than if it merely obeyed all the 'rules'.
Answer: The notes you have in the three chords are A C D Eb E F G.
All that proves is that "music" doesn't have to follow an arbitrary set of "rules" about "naming scales".
In the long run, learning that fact is probably going to be more beneficial than jumping through the hoop of "identifying the correct scale name".
When in doubt, throw your theory books on the fire, and just use your ears!
Comment: Did you miss C# which is a part of AM(the first chord)?
Answer: Technically, those three chords don't fit in one key so one scale (mode) won't have all of the notes exactly.  I agree with the answer above that your ear is the most important thing.
An A minor scale would sound fine over this progression as would a D minor scale.  A minor pent scale would work fine also.
Answer: I just googled it and found 2 unusual scales that fits in that Am Cm Dm structure.
Eight Tone Spanish Scale
A#/Bb ichikosucho Scale
So I've never heard of these scales before but they seem like fitting in that progression, I think that there is no reason to find a perfect scale that fits perfectly or finding a name for that "perfect" scale. They're all made up, just go by ear, that's the only proper way to do music. Cheers.

Find out scale from these 3 chords


Why computing the variance of the extracted random effect (using ranef) is not the same as the output from lme?

Question: I am applying a mixed model to predict tumor progression (y) using tumor volume (x) as the fixed effect and center ($i=1,...10$) as random intercept. The model can be written as:
$$y_{ij}=\alpha+\beta x_{ij}+b_{i}+\epsilon_{ij}$$
I used the lme() function in R:
fit1 <- lme(PD ~ log(Volume), random = ~1 | CenterID, data=Data)

The result shows that the standard deviation of the random intercept is 0.079. Thus $b_{i}$ follows a normal distribution $N(0,0.079)$.
In the meantime, I can extract the random intercept by applying ranef(fit1). This gives a list of $b_{i}$ corresponding to each center. Then I compute the standard of this vector.
sd(ranef(fit1)[[1]])

I would expect that it gives similar result as 0.079. However, it is far different.
Can someone tell me why sd(ranef(fit1)[[1]]) gives different result than the model output VarCorr(fit1)? What is exactly the relation between ranef(fit1) and VarCorr(fit1)?
Comment: The same question is asked [here](http://stats.stackexchange.com/questions/68106/understanding-the-variance-of-random-effects-in-lmer-models), but a different answer is given.
Answer: VarCorr() here provides the variance estimate of the random intercept by REML, but sd(ranef(fit1)[[1]]) shows the standard deviation of the empirical Bayesian estimates of the random intercept. In other words, say we have parameter $\sigma$, VarCorr() gives us the estimate $\hat \sigma$; we can generate a random sample based on $\hat \sigma$, and then calculate the standard deviation of the random sample by sd().
The two would be different since the result by sd() is an estimate of the result by VarCorr(). The similarity depends on the data set, and the two are similar when tested with the Orthodont example in lme().
> summary(fit1 <- lme(distance ~ age, random = ~1 | Subject, data=Orthodont))
Random effects:
 Formula: ~1 | Subject
        (Intercept) Residual
StdDev:    2.114724 1.431592

> sd(ranef(fit1)[[1]])
[1] 2.003087


Form Div breaks parent div and wraps

Question: I really need your help with this. For the life of me, I cannot begin to understand as to why I cannot seem to get my form DIV to properly be positioned on the right side of my 2 column layout.
See attached picture below:

Here is the HTML & CSS in question:

* {
  font-family: Segoe UI;
  font-size: 9pt;
}
html, body {
  padding: 0;
  margin: 0;
}
body {
  background: rgb(187,195,203);
}
.Absolute-Center {
  margin: auto;
}
#wrapper {
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
}
#layout {
  height: auto;
  width: 900px;
  border: 1px solid rgb(112,112,112);
}
#box1 {
  background: rgb(141,155,169);
  color: #FFF;
  padding: 3px;
  font-weight: bold;
}
#box2 {
  width: 100%;
  background: rgb(240,240,240);
  border-bottom: 1px solid rgb(180,180,180);
  padding: 4px;
  box-sizing: border-box;
}
#box3 {
  width: 100%;
  border-bottom: 1px solid rgb(180,180,180);
}
#box4 {
  background: #FFF;
  float: left;
  width: 175px;
  height: 375px;
  border-right: 1px solid rgb(180,180,180);
}
#box5 {
  background: rgb(240,240,240);
  height: 375px;
}
#box7 {
  background: rgb(240,240,240);
  padding: 5px;
  text-align:center;
}
#leftcolumn {
  float: left;
}
#rightcolumn {
  border: 0;
  padding: 3px;
  text-align: center;
}
.clear {
  clear: both;
}
fieldset {
  margin: 0;
  padding: 2px;
  padding-bottom: 5px;
}

div.wrapper {
  width: 500px;
}
div.form {
  width: 100%;
  background-color: rgb(240,240,240);
  border: 1px sold #000;
  padding: 5px;
}
div.row {
  clear: both;
  padding-top: 5px;
}

div.row span.label {
  float: left;
  width: 50px;
  text-align: right;
  padding-right: 5px;
}
div.row span.formw {
  float: left;
  width: 200px;
  text-align: left;
}
div.spacer {
  clear: both;
}
span.title {
  color: rgb(70,141,180);
}
input {
  width: 150px;
  border: 1px solid #000;
}

Application Title

File Information

Comments

            <form>

FILE INFORMATION

                Date Received

                From:<input type="text"/>

                To:<input type="text"/>

            </form>

Answer: It's because you float box4 left but you do not float box5 right. So it is still in the flow of the document and pushed below the float left.
Answer: Added float:left and width: 78%; to .box5 Press in the snippet the fullpage button to see it

* {
  font-family: Segoe UI;
  font-size: 9pt;
}
html, body {
  padding: 0;
  margin: 0;
}
body {
  background: rgb(187,195,203);
}
.Absolute-Center {
  margin: auto;
}
#wrapper {
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
}
#layout {
  height: auto;
  width: 900px;
  border: 1px solid rgb(112,112,112);
}
#box1 {
  background: rgb(141,155,169);
  color: #FFF;
  padding: 3px;
  font-weight: bold;
}
#box2 {
  width: 100%;
  background: rgb(240,240,240);
  border-bottom: 1px solid rgb(180,180,180);
  padding: 4px;
  box-sizing: border-box;
}
#box3 {
  width: 100%;
  border-bottom: 1px solid rgb(180,180,180);
}
#box4 {
  background: #FFF;
  float: left;
  width: 175px;
  height: 375px;
  border-right: 1px solid rgb(180,180,180);
}
#box5 {
  background: rgb(240,240,240);
  height: 375px;
  float:left;
  width: 78%;
}
#box7 {
  background: rgb(240,240,240);
  padding: 5px;
  text-align:center;
}
#leftcolumn {
  float: left;
}
#rightcolumn {
  border: 0;
  padding: 3px;
  text-align: center;
}
.clear {
  clear: both;
}
fieldset {
  margin: 0;
  padding: 2px;
  padding-bottom: 5px;
}

div.wrapper {
  width: 500px;
}
div.form {
  width: 100%;
  background-color: rgb(240,240,240);
  border: 1px sold #000;
  padding: 5px;
}
div.row {
  clear: both;
  padding-top: 5px;
}

div.row span.label {
  float: left;
  width: 50px;
  text-align: right;
  padding-right: 5px;
}
div.row span.formw {
  float: left;
  width: 200px;
  text-align: left;
}
div.spacer {
  clear: both;
}
span.title {
  color: rgb(70,141,180);
}
input {
  width: 150px;
  border: 1px solid #000;
}

Application Title

File Information

Comments

            <form>

FILE INFORMATION

                Date Received

                From:<input type="text"/>

                To:<input type="text"/>

            </form>

Answer: I got it to sit in the right container by adding float:right to the form container div
Fiddle - http://jsfiddle.net/90777hu9/

Form Div breaks parent div and wraps


Find the equation of the circle that touches these three lines $x= 0$, $y=0$, $x = a$.

Question:
Find the equation of the circle that touches these three lines $x= 0$, $y=0$, $x = a$.

Here is my attempt:
$x = 0$ and $y = 0$, these both line go through the $x$ and $y$ axes. And also the circle touches those two lines. So the center will be $C(p,p)$. That means $r = k = h = p$. The circle also touches the $x = a$ line. That means $r = a/2$. From that, I determined the center as $C(a/2, a/2)$.
The equation:
$$\left(x - \frac{a}{2}\right)^2 + \left(y - \frac{a}{2}\right)^2 = \left(\frac{a}{2}\right)^2$$
$$x^2 + y^2 - 2ax - 2ay + \frac{a^2}{4} = 0$$
which is not the correct answer.

Now can anyone tell me what's wrong with this attempt?
Comment: Be careful expanding your squares!
Answer: Your error is very simple: you have wronged expanding the square, in fact $\left(x - \frac{a}{2}\right)^2 + \left(y - \frac{a}{2}\right)^2 = \left(\frac{a}{2}\right)^2$ is not $x^2 + y^2 - 2ax - 2ay + \frac{a^2}{4} = 0$, but: $$x^2-ax+\frac{a^2}{4}+y^2+ay=0$$ In other words: $$4x^2+4y^2-4ax-4ay+a^2=0$$
Also, by simmetry, I get $\left(x - \frac{a}{2}\right)^2 + \left(y + \frac{a}{2}\right)^2 = \left(\frac{a}{2}\right)^2$: $$4x^2+4y^2-4ax+4ay+a^2=0$$
To clarify, see this graph where $a=6$:
Comment: Also, by symmetry, is missing another solution: circle with center $(a/2,-a/2)$ and radius $a/2$.
Comment: Yes, it's correct.
Comment: why (-a/2).I actually didn't get it.How did you get two solutions and if a is negative then It feels like c(+- a/2, +-a/2).I get confused>can you please explain.
Comment: @Ghost: see the graph in my answer.
Comment: Please check coefficients $4$ after expansion in last equations of both the numerators !
Comment: @Matteo.. now after edit it is OK.
Answer: If the simple error in your calculation [coefficient in middle $2xy$ term in expansion of $(x+y)^2$ ] is removed the correct equation is
$$ (x^2+y^2)-a (x+y)+ \frac{a^2}{4}=0 $$
The origin/corner touching circle is in the first or fourth quadrant according as odd term $y$ is positive or negative.
$$ (x^2+y^2)-a (x-y)+ \frac{a^2}{4}=0 $$
Everything else is quite OK.


How to access a specific Angular component from an external URL?

Question: I have a single page angular application that has a .NET Core back-end and is hosted on Azure.
The application allows users to reset their password if they have forgotten it, and the process it follows is that an email is sent to the user with a link to reset the password.
However, when I click the link I get a '404 Page not found' error, I understand that this is because the page doesn't exist as what I want the user to see is a component within the SPA.
I have routing setup, which works correctly when I run it in development but not when it is hosted.
Is there anyway that this can be achieved, either through code or adjusting my Azure Web App Service?
My Routing:
export const routes: Routes = [
  { path: '', component: HomeComponent },
  {
    path: '',
    runGuardsAndResolvers: 'always',
    canActivate: [AuthenticateGuard],
    children: [
      { path: 'downloads', component: MenuDownloadsComponent },
      { path: 'user-profile', component: UserProfileComponent }
    ]
  },
  {
    path: '',
    runGuardsAndResolvers: 'always',
    canActivate: [ManagerGuard],
    children: [
      { path: 'manager-dashboard', component: DashboardManagerComponent },
      { path: 'history', component: MenuHistoryComponent }
    ]
  },
  {
    path: '',
    runGuardsAndResolvers: 'always',
    canActivate: [AdminGuard],
    children: [
      { path: 'admin-dashboard', component: DashboardAdminComponent },
      { path: 'user-admin', component: MenuAdminUserComponent },
      { path: 'company-admin', component: MenuAdminCompanyComponent },
      { path: 'software-admin', component: MenuAdminSoftwareComponent },
      { path: 'release-admin', component: MenuAdminReleaseComponent },
      { path: 'item-admin', component: MenuAdminItemComponent },
      { path: 'release-type-admin', component: MenuAdminTypeReleaseComponent },
      { path: 'item-type-admin', component: MenuAdminTypeItemComponent },
      { path: 'uploads', component: MenuUploadsComponent }
    ]
  },
  { path: 'password-reset', component: UserPasswordResetComponent },
  { path: '**', redirectTo: '', pathMatch: 'full' }
];

Comment: Can you show your routing config code
Comment: Can you please show routing config code ?
Comment: @TonyNgo  please find my routing config above in the edit
Comment: Do you really need to make the functionality of "Forgot Password" in angular? Your issue can be easily resolved if you use MVC Controller, Action & View for this purpose (generating the link and redirecting on clicking the same), as you are already using .NET Core for back-end.
Answer: You are define wrong in these route
{
    path: '', // need some route here
    runGuardsAndResolvers: 'always',
    canActivate: [AuthenticateGuard],
    children: [
      { path: 'downloads', component: MenuDownloadsComponent },
      { path: 'user-profile', component: UserProfileComponent }
    ]
  },
  {
    path: '', // need some route here
    runGuardsAndResolvers: 'always',
    canActivate: [ManagerGuard],
    children: [
      { path: 'manager-dashboard', component: DashboardManagerComponent },
      { path: 'history', component: MenuHistoryComponent }
    ]
  },
  {
    path: '', // need some route here
    runGuardsAndResolvers: 'always',
    canActivate: [AdminGuard],
    children: [
      { path: 'admin-dashboard', component: DashboardAdminComponent },
      { path: 'user-admin', component: MenuAdminUserComponent },
      { path: 'company-admin', component: MenuAdminCompanyComponent },
      { path: 'software-admin', component: MenuAdminSoftwareComponent },
      { path: 'release-admin', component: MenuAdminReleaseComponent },
      { path: 'item-admin', component: MenuAdminItemComponent },
      { path: 'release-type-admin', component: MenuAdminTypeReleaseComponent },
      { path: 'item-type-admin', component: MenuAdminTypeItemComponent },
      { path: 'uploads', component: MenuUploadsComponent }
    ]
  },

You need to have a path for path: '',. Right now I see you have 4 route config have same value path: ''. So you need to some route for another 3. Because you have default route for HomeComponent
Comment: Along with above solution use hashing strategies in the ngmodule providers
Comment: @tonyngo I am not sure what you mean, as I am using guards so that only certain people can access certain areas of the application, the path's need to be like this (or I have been led to believe this is the way to do it)
Answer: I have discovered the answer to this, and it lay in the Azure Web App Settings
You need to add a path mapping to resolve the redirection to the component you need, see the attached screenshot:

To find the path I needed, I had to access the FTP, the address of this in Azure can be found in the Deployment Centre tab, under 'FTP/Credentials':


Is it legal to convert triple integral to a double integral problem instead?

Question: i am given the following problem:
$$\iiint_K e^z$$  where :
$$ K \{x^2+y^2+z^2 \leq 1\} $$
here are the steps that i did=
$$z=\sqrt{1-x^2-y^2}$$
then the problem becomes a double integral problem :
$$\iiint_K e^z = \iint_D e^{\sqrt{1-x^2-y^2}} dxdy$$
using the polar coordinates we get:
$$x=r \cos(t)$$
$$y=r\sin(t)$$
$$0\leq t \leq 2\pi$$
$$0\leq x\leq1$$
partial derivitives of $z_x, z_y$ are given by:
$$z_x= \frac{-x}{\sqrt{1-x^2-y^2}}$$
$$z_y= \frac{-y}{\sqrt{1-x^2-y^2}}$$
now the integral becomes:
$$\int_0^1\int_0^{2\pi}\frac{e^\sqrt{1-r^2} }{\sqrt{1-r^2}}r dtdr  $$
$$=2\pi \int_0^1 e^udu $$
$$=2\pi(e-1)$$
my question here if this operation is mathematically legal, given that this is really a projection on the $xy$ plane right?
Answer: No, it is not legitimate to project the surface of a sphere onto a disk and integrate it there unless you also include a factor to account for the ratio between a region on the surface of the sphere and the region of the disk it maps to. But even worse, you started with a volume integral and then proceeded to ignore the entire interior of the sphere and the surface of the lower hemisphere.
It seems to be time to start over from the beginning.
You might consider a disk method of integration instead.
Comment: would you mind providing an answer that doesnt include using the spherical coordinates?
Answer: For any $z_0\in[-1,1]$, the section $z=z_0$ of the ball $x^2+y^2+z^2\leq 1$ is a circle with radius $\sqrt{1-z_0^2}$, hence area $\pi(1-z_0^2)$. By Cavalieri's principle
$$ \iiint_{B}e^{z}\,dx\,dy\,dz = \int_{-1}^{1}e^{z_0}\pi(1-z_0^2)\,dz_0 =\color{red}{\frac{4\pi}{e}}$$
nice and easy.


refresh JFrame after adding new Components

Question: I want to add some new Components to my JFrame during runtime when a button is pressed.
This works so far, but i have to resize the window manually to see the new components.
Is there any Action I can fire or a method to call to refresh the window? Any help appreciated. Thanks in advance.
Answer: You have to revalidate(); the frame. If that doesn't work you also have to call repaint();
Comment: ok had to hack a little bit arround in my classes but it works! (btw you did mean validate() right? ;))
Comment: repaint works and revalidate does not - any idea why?
Comment: indeed, since JFrame is already a top level container, you just can call validate();.
Comment: Well, generally components are added to a JPanel, not the frame directly, so you would revalidate the panel.
Answer: Call
revalidate();
repaint();

revalidate tells the layout manager to reset based on the new component list. This will also trigger a call to repaint.
repaint is used to tell a component to repaint itself.
Answer: in java repaint(); working for me. while revalidate(); not working for me.


Inferences about $\mu$ based on the sum of two dependent normal RVs

Question: Given:
$X \sim \mathcal{N}(\mu, \sigma^2)$
$Y|X=x \sim \mathcal{N}(0, (\theta x)^2)$
$Z = X + Y$
I want to be able to make hypothesis tests or confidence intervals for $\mu$ using $Z$ and known $\theta$ and $\sigma^2$. For example, I draw $z = 950$, and I have $\sigma^2 = 10000$ and $\theta = 0.10$.  How would I estimate a confidence interval for $\mu$ with this information?
Edit:
I'm not really sure how to go about this analytically, but I've been able to create confidence intervals numerically.  Here's an empirical plot of the likelihood of $\mu$ given the observed $z$ and parameters in the above example.

Code for the above plot:
<code>import scipy.stats as stats
import numpy as np
import pandas as pd

x_var   = 10000
theta   = 0.10
samples = int(4e7)

df1       = pd.DataFrame(index=range(samples))
df1['mu'] = stats.uniform.rvs(size=samples)*1500+500
df1['x']  = stats.norm.rvs(loc=df1['mu'] , scale=np.sqrt(x_var)         , size=samples)
df1['y']  = stats.norm.rvs(loc=0         , scale=np.abs(theta*df1['x']) , size=samples)
df1['z']  = df1['x'] + df1['y']

z_observed = 950
df1.drop(df1[np.round(df1['z']) != z_observed].index, inplace = True)

hist1 = (pd.DataFrame(np.histogram(df1['mu'],bins=99,density=True))
            .transpose().rename(columns={0: 'L_mu', 1: 'mu'}))
hist1.plot(x='mu',y='L_mu')
</code>
Comment: The notation "$Y \sim N(0, (\theta X)^2)$" is sloppy because $X$ is random: I guess you meant $Y | X  = x \sim N(0, (\theta x)^2)$.
Comment: @be_excellent_to_each_other probably not.
Comment: Nope, not homework.  Real work that's got me stumped.  I'll add some more information to the post.  Thanks.
Comment: @Zhanxiong Would it be possible to get a closed-form likelihood function for $\mu$ from this joint PDF?
Comment: We can calculate the mean and variance of $Z$ by applying the double expectation formula. In this way confidence interval of $\mu$ can be constructed by CLT. $EZ = \mu$  I think it works if the variance of $Z$ is not a function of $\mu$.
Answer: Writing the density of $X$ as $f_X(x)$ and the conditional density of $Y| X=x$ as $f_{Y|x}(y|x)$ we find the joint density as
$$
\frac{{\mathrm e}^{\frac{-\left(-x +\mu \right)^{2} \theta^{2} x^{2}-y^{2} \sigma^{2}}{2 \sigma^{2} \theta^{2} x^{2}}}}{2 \sigma  \pi  \theta  {| x |}}
$$ which I cannot recognize as a known distribution. We can try to find the density of $Z=X+Y$ by transformation to $(Z=X+Y, Y)$ (which have a jacobian of 1) and then integrating out $y$, I find the joint density of $(Z,Y)$ to be
$$
\frac{{\mathrm e}^{\frac{-\left(-z +y +\mu \right)^{2} \left(-z +y \right)^{2} \theta^{2}-y^{2} \sigma^{2}}{2 \sigma^{2} \left(-z +y \right)^{2} \theta^{2}}}}{2 \sigma  \pi  \theta  {| -z +y |}}
$$  but trying to integrate out $y$ does not give a closed form:
$$
\int_{-\infty}^{\infty}\frac{{\mathrm e}^{\frac{-\left(-z +y +\mu \right)^{2} \left(-z +y \right)^{2} \theta^{2}-y^{2} \sigma^{2}}{2 \sigma^{2} \left(-z +y \right)^{2} \theta^{2}}}}{2 \sigma  \pi  \theta  {| -z +y |}}d y
$$
but you could use this expression for finding the likelihood via numerical integration. See Parameter Estimation for intractable Likelihoods / Alternatives to approximate Bayesian computation  for other ideas for intractable likelihoods.
Another idea is to calculate the moment generating function, which do have a closed form. It can be found relatively easily via the double expectation theorem (again I jump the details, I did those with maple):
$$ \DeclareMathOperator{\E}{\mathbb{E}}
M_Z(t)= \E e^{tZ} = \frac{\exp\left\{ -\frac{t(\mu^2 t \theta^2+\sigma^2 t + 2\mu)}{2(\sigma^2 t^2 \theta^2 -1)}  \right\}}{\sqrt{1-\sigma^2 t^2 \theta^2}}
$$ which is valid as long as the argument of the square root is positive, which is for $t^2 < \frac1{\sigma^2 \theta^2}$.  Then we can use the saddlepoint approximation, see How does saddlepoint approximation work?, as an approximate likelihood function.
Out of time now, will add details later.


After adding skip-innodb mysql doesn't start

Question: I am trying to setup these values:
#skip-bdb
#skip-locking
#skip-innodb

When I add them to /etc/mysql/my.cnf and even if I turn ON of of, them after I do the service restart mysql fails to start, and no error message printed.
sudo service mysql restart
[ ok ] Stopping MySQL database server: mysqld.
[FAIL] Starting MySQL database server: mysqld . . . . . . . . . . . . . . failed!

Previously I made sure that I have no InnoDB tables, and all files of that type were removed.
I tried looking for error files but I couldn't locate it:

/var/log/mysql.err is a 0 byte file
/var/log/mysql folder has no files

rsyslog was changed in past with inetutils-syslogd, and this might have changed the log files, and it could be the reason why I don't see any error logs, and I am stuck how to look or go forward.
Comment: On debian, mysql logs to syslog, so check other files in /var/log too
Comment: You can stop mysql from using syslog by removing the file /etc/mysql/conf.d/mysqld_safe_syslog.cnf
Comment: OK I removed that and gave a try, and nothing visible on the screen, and files were not changed in the log directory
Answer: The syntax has changed.  Assuming you are trying to disable InnoDB so that you can use the MyISAM storage provider instead, here's how you do that.  Instead of skip-innodb, put
innodb=OFF
default_storage_engine=MyISAM

in your /etc/mysql/my.cnf (under the [mysqld] section).  Note that you need both: the new syntax for disabling InnoDB is innodb=OFF, but you also need to specify some other default storage engine to replace InnoDB.  To verify that this has been successful, restart MySQL and run
mysqladmin -u root -p var | grep have_innodb

You should see the result
| have_innodb                                       | DISABLED              |

See also https://stackoverflow.com/a/11772814/781723.
I don't know what the equivalent is for skip-bdb or skip-locking.
Comment: This is correct for newer versions. I am using; Server version:  5.5.35-0+wheezy1 (Debian)
Answer: None of those options are available in current mysql packages.  Having any of those would cause mysql to fail to start.  If you want to see the error, you can run mysqld by itself by hand as root in a shell, and I'd expect to see it die when it encounters the first of these invalid options.
You can get a list of the available config parameters by running mysqld --help --verbose on the command line.  mysqld --help --verbose | grep skip should also confirm that these options are no longer available.


Subgradient of extension of convex function.

Question: Let $X $ be a  convex and compact subset of $R^n$. There is a function $f :X \to R$ which is smooth & convex. It is known that $f$ can be extended to a convex $f_{ext}:R^n \to R$ as follows:
$f_{ext}(x)=f(x) $ if $x \in X$
$f_{ext}(x)=\infty $ if $x \notin X$
What is the subgradient of $f_{ext}$? Can it be proved that subdifferential of$ f_{ext}$, $\partial   f_{ext}(x)= \nabla f(x)+\partial I(x)$ (where $I(x)$ is the indicator function of set $X$ defined as:  $I(x)=0 $ if $x \in X$ else $I(x)= \infty$.)?
Comment: My understanding of convex functions is that they must be defined on all of $\mathbb{R}^n$ (or whatever other real vector space), but are permitted to take the value $\infty$ (or $-\infty$, sometimes). So, I would say $f$ is not technically a convex function, and would represent it by $f_{\mathrm{ext}}$ instead. I don't know, for example, how to define $\partial f(x)$ where $x$ is in the boundary of $X$. How do you define the subderivative at a point in the boundary of the domain?
Comment: @TheoBendit this is not quite correct. It is not necessary for any function, convex or otherwise, to be defined on all of $\mathbb{R}^n$. A function's domain may indeed be a strict subset of $\mathbb{R}^n$ (or any vector space). For a convex function, this domain must be a convex set. That said, we often adopt a so-called _extended-real_ convention where we define the value of a convex function to be $+\infty$ outside of its domain; this enables us to talk about it as defined on all of $\mathbb{R}^n$. But this really is just a convention.
Comment: @MichaelGrant For a **convex** function (not a function in general), the way that I learned the theory, the function must take (possibly infinite) values at every point in a vector space. The "domain" refers to points that don't map to $\infty$, which is different to the domain in the classic sense. We're not saying anything different, really, but my point is, I only know the definitions of subgradients for my convention for defining convex functions. As far as I'm concerned, the way to represent $f$ as a convex function is with $f_{\mathrm{ext}}$, so I'm not certain what's being asked here.
Comment: It may sound like nitpicking but I think it's worth it. What you are describing is what is called the _extended real convention_ for defining convex functions. It is _just_ a convention—a way of simplifying the way convex functions are considered and manipulated. It is _not_ necessary, and it is artificial. "Infinity" is not a real number, after all: for any two real numbers $x$ and $y$, for instance, the value of $x-y$ exists—but this is not the case if $x=y=+\infty$. So in _absence_ of this convention, a function can have a domain that is a strict subset of the surrounding vector space.
Comment: For more information, look at Section 3.1.2 of Convex Optimization by Boyd & Vandenberghe, where it is clearly indicated that the use of infinities is a convenience.
Comment: What do you mean by $f :X \to R$ be smooth  a function? !

Do you mean $f$ is smooth on $int X $ ?
Comment: @Redshoes yes, f is smooth on $int(X)$
Comment: @Theo It is clear that in interior of X ,sub grad of $f_{ext}$ is $\nabla f$, but the real question is what is subgrad on   boundary of X? Is there a way to prove the above proposition?
Comment: @MichaelGrant $\infty - \infty = \infty$ in the convention as I've learned it. It makes sense; you can subtract convex functions of different domains, but it's only sensible on the intersection of the domains. I'm aware that it's a convenience, but the issue is that I don't know what's being asked here. It's fine to have different conventions, but I have no idea how you would define the subgradient of a convex function at a boundary point of the domain, unless it is to basically define it to be equal to $\partial f_{\operatorname{ext}}$. I just don't understand the problem.
Comment: $\infty-\infty$ is undefined and care must be taken to avoid it. Honestly the questioner is effectively asking if the subgradient is the same with the convention, and of course it is. The subgradient at the boundary points is definitely interesting and worth determining. Outside of the domain of course it is empty.
Comment: @Manu I have no idea what the subgradient is on the boundary of $X$, unless it's defined to be $\partial f_{\mathrm{ext}}$. If someone has asked me what the subgradient of $f$ was, I would guess that the definition of subgradient for convex functions defined on convex subsets of $\mathbb{R}^n$ would coincide with the definition of the subgradient of $f_{\mathrm{ext}}$. But since you're asking me to prove that they're the same, I'm lost. As I understand it, there's no question. But maybe Michael Grant can help you?
Comment: Actually, for a convex function to be smooth on its entire domain, its domain must be open, and if the domain isn't the entire vector space, it must approach $+\infty$ on any boundary point. So this question really is a simple one, because no boundary conditions need be considered. If the function was not smooth there would be work to do!
Answer: Note that for the function $f:X \to \Bbb R$  $$\partial f(\bar{x}) = \{ y \in \Bbb R^n ~|~~ \langle y , x -\bar{x} \rangle  \leq f(x) - f(\bar{x})  ~~  \forall x \in X \} $$
$$=  \{ y \in \Bbb R^n ~|~~\langle y , x -\bar{x} \rangle  \leq f(x) - f(\bar{x})  ~~  \forall x \in \text{dom } f = \text{dom } f_{ext} \} $$
$$= \partial   f_{ext}( \bar{x})$$
What convex analysis tells you for subdifferential at boundary of $X$ is that $$     \partial f(x) := \partial   f_{ext}(x) $$
Thus writing subdifferential of $f_{ext}$ in terms of subdifferential of $f$ is trivial since they coincide.
Note that $$\partial   f_{ext}(x)= \nabla f(x)+\partial I(x)$$
is not true when $x \in$ boundary of $X$. Since $f$ is smooth on only $\text{int}X $
By the way $\partial I (\bar{x}) = N (\bar{x} ; X).$
As an example think about the function $f[-1,+1]  \to R$ with $f(x) = - \sqrt{1-x^2}. $ what would be the $\partial f (1)$
HOWEVER if $\nabla f : \text{int} X \to R^n$ be bounded function then we have  $$  \partial   f_{ext}(\bar{x})=  \text{Lim Sup}_ {x \to \bar{x}}  \nabla f(x)+\partial I(\bar{x}) $$
Comment: Why limsup? Can we write some formal proof for the above statement? Intuitively it looks correct!
Comment: I don't mean the traditional limsup in $R$.

I mean the outer limit . @Manu


Attaining the norm of a C*-algebra quotient by an ideal

Question: The following statement is Exercise I.26 in K. Davidson's book C-Algebras by Example*:

Let $\mathfrak{A}$ be a C*-algebra, $\mathfrak{J}$ be an (two-sided
  and closed) ideal of $\mathfrak{A}$ and $A \in \mathfrak{A}$. Then
  there exists $J \in \mathfrak{J}$ such that $\|A - J\| = \|A + \mathfrak{J}\|$.

The book gives a hint of applying the Jordan decomposition (Corollary I.4.2 in the book) of the element $|A|-\|A+\mathfrak{J}\|I$. But I don't see how to proceed from here. Any help would be appreciated. Thank you!
Comment: Note also that this is a lifting problem: If $\pi \colon A \twoheadrightarrow B$ is surjective and $b \in B$, there exists $a \in A$ with $\lVert a \rVert = \lVert b \rVert$ and $\pi(a) = b$.
Answer: Here is a proof without using the hint.
It suffices to prove the following statement: If $\pi:A \to B$ is a surjective *-homomorphism between $C^*$-algebras and $y \in B$, then there exists $x \in A$ such that $\pi(x)=y$ and $\|x\|=\|y\|$. Also, we just need to prove the statement when $\|y\|=1$.
Special Case: $\underline{y=y^* \quad and \quad \|y\|=1}\\$
Since $\pi$ is surjective, there exists $a \in A$ such that $\pi(a)=y$. Replacing $a$ by $\frac{a+a^*}{2}$, we may assume in addition that $a=a^*$.
Let $f: \mathbb{R} \to \mathbb{R}$ be the continuous function defined by
\begin{equation*}
f(t)=
\begin{cases}
t &\text{ , if  } \quad  |t| \leq 1 \\
\frac{t}{|t|} &\text{ , if} \quad  |t| >1
\end{cases}
\end{equation*}
Let $x=f(a)$. Then $\|x\| \leq \|f\|_\infty \leq 1$ and $\pi(x)=\pi(f(a))=f(\pi(a))=f(y)=y$. The last equation holds because $\sigma(y) \subseteq [-1,1]$ and $f(t)=t  $ for all $t \in [-1,1]$.
General Case:$\underline{\|y\|=1} \\$
Let
\begin{gather}
 Y=
\begin{pmatrix}
0 & y\\
y^* & 0 \\
\end{pmatrix}.
\end{gather}
Then $\|Y\|=\max\{\|y\|,\|y^*\| \}=1$ and $Y=Y^*$. Apply the special case to the surjective *-homomorphism  $\pi_2:M_2( A) \to M_2(B)$ given by
\begin{gather}
\pi_2
\begin{pmatrix}
x_{11} & x_{12}\\
x_{21} & x_{22} \\
\end{pmatrix}
=
\begin{pmatrix}
\pi(x_{11}) & \pi(x_{12})\\
\pi(x_{21}) & \pi(x_{22}) \\
\end{pmatrix}.
\end{gather}
and $Y$, there exists $X \in M_2(A)$ such that $\|X\| \leq 1$ and $\pi_2(X)=Y$. Let $x \in A$ be the $(1,2)$-entry of X. Then $\|x\| \leq \|X\| \leq 1$ and $\pi(x)=y$.
Since $\pi$ is norm-decreasing, $1=\|y\| =\|\pi(x)|\leq \|x\|$. This completes the proof.


Update progress of MBProgressHUD

Question: I have a scenario in which my app downloads a large chunk of data only for the first time and this happens in say ViewController1. I'm using a different class to download the data and another one to save the data. So my question is, how can I update the progress of MBProgressHUD object created in ViewController1 to display the progress to the user?
The approach that I've adopted is to use NSNotificationCenter to send notifications. I'm sending notifications at the end of methods (13) in the class that saves data.
Here's what I've been doing:
//ViewController1.h
@interface ViewController1 ()
{
    MBProgressHUD *hud;
    float progress;
}
@end

//ViewController1.m
        - (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(receiveNotification:)
                                                     name:@"downloadComplete"
                                                   object:nil];

        }
- (IBAction)sumitButtonDidClick:(id)sender {
    hud = [[MBProgressHUD alloc] init];
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    hud.label.text = NSLocalizedString(@"Please wait...", @"HUD preparing title");
    hud.minSize = CGSizeMake(150.f, 100.f);

        [hud showAnimated:YES];

        double delayInSeconds = 1.0;

        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      progress = 0.0f;

        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
DownloadClass * obj1 = [[DownloadClass alloc] init];
            [obj1 downloadData];
dispatch_async(dispatch_get_main_queue(), ^{
                    [hud hideAnimated:YES];
});
}

- (void) receiveNotification:(NSNotification *) notification {

    if ([[notification name] isEqualToString:@"downloadComplete"])
    {
        NSLog (@"Successfully received the download complete notification!");
        progress += 7.7f;
        //[hud setProgress:progress]; // won't work
        dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD HUDForView:self.view].progress = progress;

    });
    }
}

Update: I'm receiving the notifications posted by the class that saves
  data
Answer: You have created a instance variable for MBProgressHUD as MBProgressHUD *hud; and you start progress on a sumitButtonDidClick method as below :
hud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, -30, 320, 768) ];
        hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
        hud.label.text = NSLocalizedString(@"Please wait...", @"HUD preparing title");
        hud.minSize = CGSizeMake(150.f, 100.f);
        UIWindow *window=[[[UIApplication sharedApplication]delegate]window];

        hud.center=window.center;

        [window addSubview:hud];

        [hud showAnimated:YES];

But increasing progress as Class method of MBProgressHUD as [MBProgressHUD HUDForView:self.view].progress = progress;.
Fix for the issue is below :
dispatch_async(dispatch_get_main_queue(), ^{
   hud.progress = progress;
});

if you want to hide the progress you can use
 dispatch_async(dispatch_get_main_queue(), ^{
       [hud hideAnimated:YES];
    });

Comment: tried setting the progress as:`[hud setProgress:progress]`. But the progress won't update.
Comment: updated my answer can please to progress set in main queue
Answer: The official documentation lists it like this:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeAnnularDeterminate;
hud.label.text = @"Loading";
NSProgress *progress = [self doSomethingInBackgroundCompletion:^{
    [hud hideAnimated:YES];
}];
hud.progressObject = progress;

You can find it here: https://github.com/jdg/MBProgressHUD
Answer: According to the documentation for MBProgressHUD you appear to be creating the HUD incorrectly. The example they give, is as follows...
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

// Set the bar determinate mode to show task progress.
hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    // Do something...
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
});

You are creating an instance and attaching it to UIWindow
Comment: this is because I need a horizontal bar. `MBProgressHUDModeDeterminateHorizontalBar`
Comment: @Prashant I've updated the example, its worth looking at the demo project
Comment: thank you. I'll give it a try. I've been trying the same thing.
Comment: The thing is when I use  `dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0)` the data is saved via a background thread, which is not an intended behavior. So I'm directly `//Doing someting` and then requesting an update of the process in the `receiveNotification:` method that gets fired as and when a notification is posted.

Update progress of MBProgressHUD


Is there any use for multiple variables in same quantifier?

Question: For predicates, it is possible to pass multiple variables. They are called polyadic predicates in that case, for example, $P(x, y)$. But how about quantifiers. I have not seen an example of this but want to be sure.
Is there usage for something like:
a)
$$∀(x∈A, y∈B)(x | y)$$
in the first-order logic?
I could provide arguments in the following manner:
If multiple domain sets are provided, then values could be passed to the quantifier in tuples taking one item from each domain to match each argument. Say $A = [1 2 3]$ and $B = [1 2 3 4]$. Then we send arguments in groups of: $(x=1, y=1)$, $(x=2, y=2)$, and $(x=3, y=3)$ and leave the last iteration out because there is no pair for y: $(x=undefined, y=4)$. Is this too far from convention?
Or should it just be:
b)
$$∀x∈A(∀y∈B(x | y))$$
Or maybe even:
c)
$$∀x∈A∀y∈B(x | y)$$
Apparently b) and c) would give same truth value, but a) differs dramatically from the last two...
$|$ is just an arbitrary operation between $x$ and $y$.
Comment: What does '$x|y$' mean in this context?
Comment: It is any comparison operation that makes x and y relative.
Comment: So, can you write $x|y$ as binary predicate instead, e.g. as $P(x,y)$?
Comment: If so, such constructs are often used mathematics. In mathematics, different quantifiers in the same statement may be restricted to different, possibly empty sets. For convenience, in most presentations of FOL, every quantifier in the same statement is assumed to be restricted to the same unspecified, non-empty  "domain of discussion."
Answer: Technically, it all depends on how the formal syntax is exactly defined (though I have never seen a formal syntax that would support the first version, I suppose one could define syntax in a way that supports that).
But in practice everyone will understand all these three forms. So, unless you are doing a formal logic proof, go ahead and use any of those forms.
In fact, in math proofs you do often see $\forall x,y ...$
EDIT
OK, so I think I understand now what you are trying to do: you want the one quantifier to signify one object ... but it would have to be an object that exists in $A$ as well as $B$.  Hmmm, 'too far from convention' is not a bad phrase to use here :). But I think it is also 'too far from useful' as well.  If the quantifier signifies one object, then I would say use one variable as well. ... and if it needs to be in $A$ as well as $B$, then maybe just do:
$$\forall x \in A \cap B \ x|x$$
Comment: I added a bit more information for the first case. Can you please take a second look?
Comment: @MarkokraM Oh!  So your one quantifier would really denote just one object with which multiple variables would be  instantiated.  OK, well, *that* is certainly highly unusual .. hmmm... I can't say I have ever seen anything like it, but as I said, one can of course define the syntax in any way one wants, as long as one provides a semantics ... Then again, it really seems not very helpful, for if you really want just one object, then why not just use 1 variable as well? Though you would say that you are dealing with different domains ... but it needs to be in the intersection.
Comment: Getting closer. I still made a small clarification to the argument split part. But now it seems as you stated. One could join domains and send tuples each containing two items. That would simplify quantifier to one argument. I guess, it doesnt matter if argument is a single value or tuple (set) of values. My question still is, when if ever quantifier should use multiple arguments?
Comment: @MarkokraM Well, then I stand by my original observation ... whenever we do write something like $\forall x,y ...$ that is just shorthand for $\forall x \ \forall y ...$, and that will capture all possible pairs $(x,y)$ .  ANd if you want $\forall x,y ...$ to mean one object, then you should really just use one variable.
Answer: I never seen the first, and can be better write as
$$
\forall(x,y)\in A\times B
$$
that I prefer also to the other two notations.
Comment: Would this be equivalent to cases b) and c)?
Comment: How would you denote, if domain sets A and B should provide values in pairs? I guess A×B now joins sets to correlate with cases b) and c)?
Answer: The logics used in proof assistants like those in the HOL family and many others support this kind of syntax for quantifiers. It is often called "pattern-matching abstraction", because in place of the bound variable after the quantifier, we have a "pattern" $(x \in A, y \in B)$.


xpath select node texts and child nodes

Question: I am using python scrapy to scrape some data from a website.
the web site content is something like this

 not needed

  content 1

content 2

content 2

content 2

content 2

content 2

 this is also not needed

I need to get the full html data excluding div with class a,b.
so my output will be like this

content 1

content 2

content 2

content 2

content 2

content 2

How can I write correct xpath for that or should I write xpath for div with class 'details','a','b 'and use string operations to remove div with class 'a','b'?
Note that here content   is the text of and is not a child of div with class 'details'
Answer: You can get all children except the div with class a or b using node() and self:: syntax:
//div[@class="details"]/node()[not(self::div[@class="a" or @class="b"])]

Demo using scrapy shell:
$ scrapy shell index.html
>>> nodes = response.xpath('//div[@class="details"]/node()[not(self::div[@class="a" or @class="b"])]').extract()
>>> print ''.join(nodes)
  content 1

content 2

content 2

content 2

content 2

content 2

xpath select node texts and child nodes


React Router 4: Route a page to 404 page if it doesn't match with my routing URLs

Question: <Switch>
<Route exact path="/" component={App}/>
<Route path="/home" component={Dashboard}/>
<Route component={NotFound}/>
</Switch>

I'm getting redirected to 404 page when my urls is http://localhost:8080/home1 but when I gave the wrong url with sub paths ( http://localhost:8080/home/1) it fails to render my NotFound component and shows a empty screen. Can anyone suggest me what i'm missing?
Comment: That is how it is supposed to match , as home1 does not match with home. But in the second example it matches correctly and then renders as exact isn't specified
Comment: But it suppose to works when it matches only my Router "path"? Second example was not matched with my paths so it should redirects to 404 page..is my understanding is correct?
Answer: <Switch>
    <Route exact path="/" component={App}/>
    <Route path="/home" component={Dashboard}/>
    <Route path="*" component={NotFound}/>
</Switch>

Comment: You should provide an explanation in your answer.


@Transactional doesn't genetate INSERT in database

Question: I'm doing REST service using Spring+Hibernate and trying to tune transaction.
When I saving in function annotated @Transactional Hibernate doesn't generate query with entitiy INSERT statement. Only receives new id. This is log:
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?

My source files:
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation=
            "http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
            http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.3.xsd
            ">

    <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost/project8098" />
      <property name="username" value="usr" />
      <property name="password" value="pwd" />
   </bean>

  <bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="cama.entities" />
      <property name="hibernateProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
         </props>
      </property>
   </bean>

    <tx:annotation-driven transaction-manager="transactionManager"  />

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <context:annotation-config/>
    <context:component-scan base-package="cama.controllers"/>
    <context:component-scan base-package="cama.dao"/>
    <context:component-scan base-package="cama.dao.users" />
    <context:component-scan base-package="cama.messages.email"/>
    <context:component-scan base-package="cama.messages.firebase"/>

    ...

</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Children Attendance Monitoring Application</display-name>

  <servlet>
      <servlet-name>cama</servlet-name>
          <servlet-class>
              org.springframework.web.servlet.DispatcherServlet
          </servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>
   <listener>
       <listener-class>
           org.springframework.web.context.ContextLoaderListener
       </listener-class>
   </listener>
    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>
           /WEB-INF/beans.xml
           /WEB-INF/security.xml
           /WEB-INF/test.xml
       </param-value>
    </context-param>
    <servlet-mapping>
        <servlet-name>cama</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>
            org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>0</session-timeout>
    </session-config>

</web-app>

cama-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
                        http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.3.xsd
                        ">

   <context:component-scan base-package="cama.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
    </bean>

    <mvc:view-controller path="/" view-name="index"/>

   <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

</beans>

Class with controller
package cama.controllers;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import cama.dao.users.AdministratorDAO;
import cama.entities.Administrator;
import cama.resources.URL;

@RestController
@RequestMapping(URL.ADMINISTRATORS)

public class AdministratorController extends AbstractController{

    @Autowired
    private AdministratorDAO controllerDAO;

    @RequestMapping(method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public @ResponseBody Administrator create(@RequestBody Administrator entity){

        controllerDAO.save(entity);

        return entity;

    }

    ....

}

DAO class:
package cama.dao.users;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cama.entities.User;

public abstract class AdministratorDAO{

    @Transactional
    public void save(Administrator entity) {
        Session session = getSessionFactory().openSession();
        entity.setNewSecretCode();
        session.save(entity);
        //session.flush(); //Without flush doesn't save entity !!!
        session.close();
    }

    ...

}

Help me please find what is wrong. When I do operation delete it works correctly and delete entity.
Answer: Afaik, if you use the @Transactional annotation, you don't have to open and close Sessions manually. So, in your Dao:
@Transactional
public void save(Administrator entity) {
   Session session = getSessionFactory().getCurrentSession();
   entity.setNewSecretCode();
   session.save(entity);
}

It will be the container which will take care of opening the transaction, flushing the Session, and committing the transaction saving the entity on your database.
Answer: When using @Transactional, Hibernate's writes to the database are in a transaction that won't be committed until you call flush(). This is useful when you might want to rollback your transaction.


how to dynamically download a file using struts 2 annotations (passing variable into annotation)

Question: im new to struts 2 and im asking if there's a way to pass a variable argument into struts 2 annotation.
here is what i already did but with no luck
public class DownloadFileAction  extends ModuleGenericClass{
    private InputStream inputStream;
   private String fileName;

   @Action(value="/downloadFile",results={
         @Result(name="success",type="stream",params = {
                 "contentType",
                 "application/octet-stream",
                 "inputName","inputStream",
                 "bufferSize","1024","contentDisposition",
                 "filename=\"${fileName}\""})
         })
   public String execute() throws Exception {
         fileName = "testing";
         inputStream = //myInputStream
         return SUCCESS;
   }

    public void setCourrierId(String courrierId) {
        this.courrierId = courrierId;
    }
   public String getfileName() {
      return fileName;
   }

   public void setfileName(String fileName) {
      this.fileName = fileName;
   }

   public InputStream getInputStream() {
       return inputStream;
   }

   public void setInputStream(InputStream inputStream) {
       this.inputStream = inputStream;
   }
}

i searched on the net but i found only solutions with xml Struts and that is not what i want =(
Comment: Your getter should be `getFileName`, does it work with the correct name?
Comment: shame on me, i spent hours searchingin the time where the mistake is in front of my eyes =$
thank you so much it does work
Comment: Fresh eyes often spot things immediately :)
Answer: Your filename getter method is named incorrectly, it should follow the JavaBean pattern:
public String getFileName() { ... }

OGNL's failing to call the getter; dynamic parameters work in annotations as they do in XML.


match tuple with null

Question: I don't understand why the following case doesn't match.  Null should be an instance of Any, but it doesn't match.  Can someone explain what is going on?
val x = (2, null)
x match {
    case (i:Int, v:Any) => println("got tuple %s: %s".format(i, v))
    case _ => println("catch all")
}

prints catch all

Thanks.
Answer: This is exactly as specified.
Type patterns consist of types, type variables, and wildcards.
A type pattern T is of one of the following forms:

* A reference to a class C, p.C, or T#C.
This type pattern matches any non-null instance of the given class.

It's interesting that so much relevance has been attributed to null being a member of Any.  It's a member of every type but AnyVal and Nothing.
Comment: I presume a/the motivation for this choice is that it matches the behaviour of the "instanceof" bytecode on the JVM.
Comment: That, and letting null through would completely suck.  You must have an obscene null tolerance to go looking for motivations!
Comment: "Obscene null tolerance" or not, there's an argument that the most natural and straightforward meaning for a type pattern "x: T" is to match any member of type T. For example, it would avoid irregularities like "val x: Any = null" -- fine, but "val (x: Any, y: Any) = (null, null)" -- MatchError. That "completely sucks" too.

I'm not saying that Scala made the wrong choice, nor that it's particularly important given that idiomatic Scala avoids using null.
Comment: That's a poor example since that issue has nothing to do with null.  "val (x: Int, y: Long) = (5, 5)" also fails with a match error.  In any case, if you're using null in such a way that this comes up, I propose that you're doing it wrong.
Comment: I'm afraid I don't follow you. Your example fails, I presume, because the second 5 is type inferred as an Int, so it fails the runtime type test, but that doesn't seem applicable to my example.
Answer: Have you tried the v placeholder for anything?
val x = (2, null)
x match {
    case (i:Int, v) => println("got tuple %s: %s".format(i, v))
    case _ => println("catch all")
}

Answer: That's as specified (Scala Reference 2.7, section 8.2):

A reference to a class C, p.C, or T#C.
  This type patternmatches any non-null instance of the given class.
  Note that the prefix of the class, if
  it is given, is relevant for
  determining class instances. For
  instance, the pattern p.C matches only
  instances of classes C which were
  created with the path p as prefix.
Answer: I'm just guessing here since I'm no scala expert but according to the documentation for the Any class in scala I'm thinking that since null isn't an object, it doesn't derive from Any and as such doesn't match the first listed case.
Adding the code sample below. It prints "something else" when run.
val x = (2, null)
x match {
    case (i:Int, v:Any) => println("got tuple %s: %s".format(i, v))
    case (i:Int, null) => println("something else %s".format(i))
    case _ => println("catch all")
}

After more research it seems like null should match with any sense the documentation says that it extends AnyRef which extends Any.
EDIT: Like everyone else has said. The first case doesn't match null on purpose. It's specified in the documentation.
Comment: `null` is the singleton instance of the class `Null`.
Comment: That makes sense. The documentation for null (http://www.scala-lang.org/docu/files/api/scala/Null.html) says it extends AnyRef which extends Any, so it seems like it should match case(i:Int, v:Any).

match tuple with null


Vector autoregression for mix of stationary and nonstationary variables

Question: I am currently investigating the impact of certain indicators such as GDP and inflation on the stock market. However some of my variables are non-stationary and some stationary in levels. All variables are stationary in first differences.
My question:

Since I have a mix of I(0) and I(1), I need to take the first difference of the I(1) variables and then use VAR. Say that I have a dependent variable $y$ which is I(0) and independent variables $x_1$ which is I(1) and $x_2$ which is I(0). Do I take the first differences of only $x_1$ and then apply the VAR model? Is that correct?
If I take the first differences, then might I lose the long-run relationship between the variables?
Is ARDL the better method in this case?

If you have any references regarding the above I would be grateful.
Comment: I have answered a related question [here](http://stats.stackexchange.com/questions/148994/time-series-analysis-var-or-vecm/149263#149263).
Answer:
In your example there is only one integrated variable, $x_1$; hence, taking the first differences of $x_1$ and leaving the other variables $y$ and $x_2$ in levels before estimating a VAR model is fine. But if you had more than one integrated variable, you should consider cointegration.
If there is more than one integrated variable and some of the integrated variables are cointegrated, then taking the first differences of the integrated variables and ignoring the cointegrating relationship would indeed be suboptimal. You could say that then you lose the long-run relationship.
I don't know.

Note: differencing variables that are I(0) in levels should be avoided. It induces extra structure that need not be there. The term is "overdifferencing". See this, this or this.
Comment: Thanks. Regarding 1) So if I have 8 variables, where four of them are I(0), and the rest are I(1) then I should use maybe Johansen test disregarding the fact that I have a mix of stationarity?
Comment: I don't remember this right away, but there should be some guidelines for what to do with mixes of I(0) and I(1) variables. You would have to do a search on that. If I had to answer immediately, I would say do the Johansen procedure on the I(1) variables only and then add the I(0) ones when building your model. But that might not be optimal.


Receive data from app user swift

Question: Preface: New to coding but have tried to do expensive research without finding anything that I thought would work---so please go easy
I am attempting to create an app that a user will fill out a form of multiple text fields and then when the submit button is touched, it will send the completed fields in an email to one specific email address.
I am stuck at the process of how to send the email with the data entered. I do not want to do this within the app with MFmailcomposer. Can I do this from a back end like firebase for example, or is there a better way to implement---or is this even possible? Hoping someone can at least point me in the right direction, I feel like Ive been stuck for weeks.
Thx
Answer: There are services that will send emails for you (like MailChimp). They have an SDK and you'd have to integrate the SDK into your app. Or you could create your own API and call said API through your app and handle the email notifications in your API. Firebase looks like it has custom email options, but only for the Javascript SDK.

Receive data from app user swift


Probability generating function of mixture of discrete random variables

Question:
Consider a discrete distribution $X$ that is a mixture of two
  discrete distributions $A$ and $B$. Explicitly, $X=A$ with probability
  $p$ and $X=B$ with probability $1-p$. Denote the pgfs of $A$ and $B$
  as $\mathcal{G}_A$ and $\mathcal{G}_B$ respectively.

I want to write an expression for the pgf $\mathcal{G}_X$ of $X$.
Here's what I've done so far, am I on the right track?
Let $Y\sim X$ and denote the probability measure on $A$ and $B$ as $\mathbb{P}_A$ and $\mathbb{P}_B$ respectively. Then:
$$
\begin{align*}
\mathbb{P}(Y=k) &= \begin{cases}
\mathbb{P}_A(Y=k) & \textrm{with probability $p$} \\
\mathbb{P}_B(Y=k) & \textrm{with probability $1-p$}
\end{cases} \\
&= p\mathbb{P}_A(Y=k) + (1-p)\mathbb{P}_B(Y=k)
\end{align*}
$$
Then
$$
\begin{align*}
\mathcal{G}_X(z) &= \sum_{k=0}^{\infty}z^k\mathbb{P}(Y=k) \\
&= \sum_{k=0}^{\infty}z^k\left(p\mathbb{P}_A(Y=k) + (1-p)\mathbb{P}_B(Y=k)\right) \\
&= \sum_{k=0}^{\infty}pz^k\mathbb{P}_A(Y=k) + \sum_{k=0}^{\infty}(1-p)z^k\mathbb{P}_B(Y=k) \\
&= p\sum_{k=0}^{\infty}z^k\mathbb{P}_A(Y=k) + (1-p)\sum_{k=0}^{\infty}z^k\mathbb{P}_B(Y=k) \\
&= p\mathcal{G}_A(z)+(1-p)\mathcal{G}_B(z)
\end{align*}
$$
Comment: Pay attention to title. In probability theory, there are several kinds of generating function, so need to specify which you want to talk.
Comment: Sorry, I have changed the title.
Answer: The solution and the general method are both correct, but some of your notation is unnecessary (e.g., there is no need to define $Y$ at all).  Note that this result is just a special case of a more general probability rule, which holds that that the probability generating function of any mixture random variable can be written as a weighted average of the probability generating functions of its mixture parts (with weights equal to the mixture probabilities).

Theorem: Let $X$ be a mixture of the random variables $A_1,...,A_k$ with mixture probabilities $p_1,...,p_k$, then the probability generating function of $X$
  can be written as:$$\mathcal{G}_{X}(z) = \sum_{i=1}^k p_i \cdot \mathcal{G}_{A_i}(z).$$
Proof: From the stated mixture form we have $X = A_H$ where $H \sim \text{Categorical}(p_1,...,p_k)$.  Thus, using the law of total expectation you have:$$\begin{equation} \begin{aligned}
\mathcal{G}_{X}(z)
= \mathbb{E}(z^X)
&= \mathbb{E}(z^{A_H}) \\[6pt]
&= \mathbb{E}( \mathbb{E}(z^{A_H}|H)) \\[6pt]
&= \mathbb{E}( \mathcal{G}_{A_H}(z)) \\[6pt]
&= \sum_{i=1}^k p_i \cdot \mathcal{G}_{A_i}(z), \\[6pt]
\end{aligned} \end{equation}$$ which was to be shown.  $\blacksquare$

Observe that nothing in this proof requires any assumption about the distributions of the random variables $A_1,...,A_k$ to be discrete.
Comment: +1 -- but by deleting the unnecessary word "convex" everywhere you will make the underlying idea even clearer and provide an interesting generalization.
Comment: @whuber: Edited.
Comment: Thank you.  Note that the $p_i$ needn't be probabilities: there are applications where distributions are expressed as linear combinations of others with negative coefficients (or even complex coefficients).  See https://stats.stackexchange.com/a/72486/919 for an example.
Comment: @whuber: Fair enough, but would you still call that a "mixture distribution"?
Comment: I understand why one might want to restrict the coefficients to positive numbers, but have yet to run into a situation where that restriction was necessary or useful.  In some sense, allowing for negative coefficients is akin to introducing imaginary numbers in algebra: they might not admit the same interpretations as ordinary numbers, but they can be useful and ultimately might provide more satisfactory explanations of otherwise mysterious behaviors.


Problem on the comment form #validation and #submit

Question: I've tried to create a validation and submit functions on a custom comment form, using drupal 7.9,  but it's not working, and I don't know why.
In the following code, we can see the "dpm's" in the first function, but not the "dpm's" in the last ones.
function job_form_comment_node_job_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'job_comment_validate';
    $form['#submit'][] = 'job_comment_submit';
    dpm($form);
    dpm($form_state);
}

function job_comment_validate($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

function job_comment_submit($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

if I add a #validate or #submit it also doesn't call others drupal hook comments like presave, insert etc.
If I comment these lines, the hooks are called, but I can't use the validation or the submission functions in this case.
Do you have any idea on why this happens?
Comment: Do you have any module that defines the `comment_node_job_form()` function?
Comment: No, I have not.
Comment: Does the comment get saved when the form is submitted? Also, what you can see in #submit when you dpm
Comment: Just to be clear, you wouldn't see the dpms from the validate and submit functions until you actually _submitted_ the form. You're not expecting to see them when you just load the page, are you?
Comment: you have `job_from_....alter` then you have ` job_comment_validate` and `job_comment_submit`...1. whats your module name? 2. Can you post the implementation the define the `comment_node_job_form` form.. should be `function comment_node_job_form..` if you do not have, then your alter function is not altering anything ..
Answer: You're missing $form_id, the third parameter of the function.
See hook_form_alter() reference on drupal.org. The problem you're experiencing might be a (weird) way of PHP reacting to that.
In situations like this you may want to check for errors on the logs (Drupal, PHP, MySQL). Some times there are useful hints there to figure what's wrong.
Comment: It is not necessary to use `$form_id` in `hook_form_FORM_ID_alter()`, as that hook is only called for the form with ID equal to "FORM_ID."
Comment: No, I can specify a hook for hook_form_alter in both ways. Either using the $form_id as the third parameter or using the following signature hook_form_ +form_id+ _alter(&$form, &$form_state), the proof is that I can see the dpm's in the first functions.

I've already tried to try to use your hook signature and I have exactly the same result.


Shimura Varieties actual varieties for any level?

Question: Since I have not been answered on my other thread Shimura varieties/Double coset for non-neat level so far and I can't work with this uncertainty, I'll just put down the most important questions here. I would still be grateful if someone would take time for the other thread. Let $(G,X)$ be a Shimura datum. Are the level $K$ varieties $\text{Sh}_K(G,X)$ also (quasi-projective) varieties if $K$ is not sufficiently small (in which case they are normal)? Do the $X_K=\text{Sh}_K(G,X)$ also have models over a number field if $K$ is not sufficiently small? Does the tower of Shimura varieties $\{X_K\}$ have a model over $E$ even if $K$ runs through all open compact $K$? Now let $D$ be a general Hermitian symmetric domain and $\Gamma \subset \text{Is}^+(D,g)$ a discrete subgroup of the holomorphic isometry group of $D$. Bailey-Borel says $\Gamma\backslash D$ is a normal quasi-projective variety over $\mathbb{C}$ for any $\Gamma$ (not necessarily torsionfree). Does it have a model over a number field?
Answer: First as you said Bailey-Borel theorem says that $D/\Gamma$ is analyticification of a quasi-projective smooth variety for any torison free $\Gamma$ and a quasi-projective normal variety for any $\Gamma$.
you can understand all $Sh(G,X)_K$ as varieties, and they all have canonical models over reflex field.(although sometimes it is better to look at the $Sh(G,X)_K$ for big $K$ as a stack because the variety is only a coarse solution to moduli problem you want to consider).
all the connected components have a model over some number field so $D/\Gamma$ always have a model over some number field for any $\Gamma$ that comes from a congurance subgroup of some $G$ such that $G^{ad}=Hol(D)$.maybe for any $\Gamma$ you can find a model over a number field but this model is not in any way canonical and after all the interesting point about canonical models is that you have a model over a fixed number field otherwise you only want a model over $\bar{\mathbb{Q}}$.
*just to clarify what I mean by look at big level shimura variety as a stack: you can write $Sh(G,X)_K=Sh(G,X)_{K'}/\frac{K}{K'}$ for a neat group $K'$, this quotient is represented by a normal quasi-projective variety in the category of schemes(because $\frac{K}{K'}$ is a finite group) but sometimes it is better to look at the quotient stack which could be equal to that normal variety or not.
Comment: @yes your first comment is right.for your third comment yes the whole tower is defined over a fixed number field(which called the reflex field). for your second comment I'm not sure about general $\Gamma$, but for any congurance subgroup it is defined over some number field but the number field is depend on $\Gamma$
Comment: Dear Ali thank you very much for your answer! Just to clarify: 1. $(G,X)$ be a Shimura datum. The $X_K=\text{Sh}_K(G,X)$ for $K$ open compact are always normal quasi-projective varieties and defined over some reflex field (number field). But for big $K$ they generally only give coarse moduli solutions instead of fine ones. And thus it is better to look at the $X_K$ as stacks for big $K$ instead of variety. Did I understand it correct up to here?
And 2.
Comment: And 2. The $D/\Gamma$ as in my opening question above ($D$ Hermitian symmetric domain, $\Gamma \subset \text{Hol}^+(D)$) are normal quasi-projective varieties over $\mathbb{C}$ and have a model over some number field for any $\Gamma$. But as $\Gamma$ varies, the number field changes and in the whole tower $\{D/\Gamma\}_\Gamma$ only gets a model over $\overline{\mathbb{Q}}$ instead of over a fixed number field. I was clear about this because the tower attached to a connected Shimura datum is not defined over a fixed number field in contrast to a general Shimura datum. But does the
Comment: If $(G,X)$ is a (general) Shimura datum, then the tower $\{X_U\}_U$ of Shimura varieties is defined over a fixed number field where $U$ runs through all sufficiently small (open compact) $U$. And I know that the single $X_U$ have a canonical model over some number field for any $U$ (not only small enough $U$) if I understood you correctly. But is the tower $\{X_U\}_U$ also defined over a fixed number field when $U$ runs through all (!) compact open $U$ and not just the small enough ones? That's my last question.
Comment: Dear Ali, I see. Thank you very much, your answers were really very helpful!
Comment: I have one very last question. If $K \subset K'$ are neat, then the map $p: \text{Sh}_K (G,X) \to \text{Sh}_{K'}(G,X)$ is a finite etale morphism. What can we say about the degree of the map $p$: Is it equal the index $[K':K$]? And is this map $p$ a Galois cover if $K$ is a normal subgroup of $K'$, with deck transformation group/Galois group of $p$ egal $K'/K$?
Comment: @VitalyVoedevsky this realy has not anything to do with shimura varieties, basically you are asking if you have a variety $X$ and a good action of a finite etale group on it(the finite group$K'/K$ in your case, the action is good because the subgroups are neat) then what properties the qutient map $X\to Y$ has?the answer is it has all the good properties you think. you can check any book that discuss the qutient of action of a finite group on a scheme to see the exact statement
Comment: @VitalyVoedevsky also the official site policy is that don't ask new question on the comments, ask a separate question because other users can't find the question and answer by search in the comment


Jasmine erro - Uncaught [object Object] thrown

Question: Quando executo o meu teste recebo o seguinte erro Uncaught [object Object] thrown cada vez que o teste é executado ele fala que o erro é em local diferente, não consigo entender o motivo. Algumas vezes o teste passa sem acontecer esse erro porem são poucas vezes o maior problema é que a descrição desse erro não é muito descritiva.Segue uma foto de exemplo:
Edição
Sempre que executo os testes obtenho o mesmo erro:

porém cada vez em um lugar diferente e em um teste diferente, por exemplo este teste da foto passou no teste anterior, porem ao executar o teste novamente o erro apareceu nele (como na foto).
O codigo dele é o seguinte:
   it('Given_invalidCnpj_When_RegisterOrg_Then_ExpectFalsy', () => {
    expect(service.validateCNPJ("19737128000161")).toBeFalsy();
});

como podemos ver não a nada demais para gerar um erro, isso esta tornando a identificação deste erro absurdamente difícil pra mim. Lembrando que se eu executar o teste novamente não vai dar erro neste teste, ele vai passar e o erro ira aparecer em outro teste em outro componente, sem relação nenhuma com o da imagem.
Comment: Possui código? Mais detalhes? Precisamos de evidências para poder ajudar.
Comment: Tudo bem, vamos por parte, "Dividir para conquistar", vamos ao primeiro erro, poste o que está acontecendo e posteriormente iremos ajustando o restante.
Comment: Encontrei o problema, obrigado pela atenção Jakson!
Comment: Desculpa @Jackson é que como cada hora acontece em um componente diferente então não sei exatamente o que mostrar :/
Comment: Vamos la, vou editar e adicionar algumas informações. como por exemplo o código do teste que der erro nesta execução
Comment: Que isso, que bom que conseguiste :D
Answer: Encontrei onde estava o problema, um companheiro de equipe adicionou estas duas linhas para testar e acabou não retirando, não sei por qual motivo ela gerava este erro bem genérico.
A solução foi apenas retira-las


Require field on publish only

Question: I have a D8 site on which I would like to require an image field to be completed only when a node is published; if the publish box is not checked, the field should not be required. I was able to do this with a custom module in D7, but since D8 has decoupled entity validation from form validation, I'm at a loss.
I've tried doing this with the Rules module, with no luck.
Answer: Simply add a validation on the entity level, then you have easy access to the whole entity.
You can see an example in content_translation_entity_type_alter():
$entity_type->addConstraint('ContentTranslationSynchronizedFields');

You register a constraint like any plugin, the only special thing is that there are two classes, the plugin class itself doesn't really have anything except the messages usually while the validator has the logic, in the validate method::
ContentTranslationSynchronizedFieldsConstraint
ContentTranslationSynchronizedFieldsConstraintValidator::validate
Once you have that, writing the actual logic is often much easier, because you have a fully built entity object to work with and don't have to wory about getting the raw values from the form values. And as a bonus, it will also automatically work for REST/json_api and any other module that uses the validate() method to ensure that created entities are valid before saving them.
For example, verifying that an image field is not empty when the entity is published:
if ($entity->isPublished() && $entity->hasField('field_image') && $entity->get('field_image')->isEmpty()) {
  // add a violation...
}

Comment: This was excellent. Thank you! For additional guidance, I used [this guide](https://www.bluestatedigital.com/ideas/drupal8-data-validation/) and [this guide](https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint).
Answer: I know this question was answered, but if anybody else is looking for a less custom solution I wrote a module that adds this functionality: https://www.drupal.org/project/require_on_publish.
Answer: You can do that by adding custom validation for the form
function custom_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#validate'][] = 'mycustom_node_form_validate';
}

Then you need to implement your custom validator:
function mycustom_node_form_validate($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  if ($node->getType() == 'node_type') {
    // Get status and image values.
    $status = $form_state->getValue('status');
    $image_field = $form_state->getValue('field_my_image_field');
    // Check if image is empty and status is published.
    if (empty($image_field['fids']) && $status['value']) {
      $form_state->setErrorByName('field_my_image_field', t('Image missing.'));
    }
  }
}

Another way to accomplish that can be by using Conditional Fields This is a really great module which let you control the visibility of the fields based on values of another field.
Just enable it and under the content type operations, you can find Dependencies option where you can map the dependency.

Require field on publish only


Hausdorff Spaces w/ only Trivial Continuous Maps into $\mathbb{R}$

Question: Looking at the wiki article for the Stone-Cech compactification, it states:

Andrey Nikolayevich Tikhonov introduced completely regular spaces in 1930 in order to avoid the pathological situation of Hausdorff spaces whose only continuous real-valued functions are constant maps.

Completely regular spaces are T1 spaces where points can be separated from closed sets by continuous maps into the interval $[0, 1]$, so these of course have non-trivial continuous functions.
My question is - what is an example of such a pathological space as above? E.g. an example of a Hausdorff space whose only continuous real-valued functions are constant maps? The source cited ultimately ends up being Tikhonov's 1930 paper in Russian, which I unfortunately cannot read.
Answer: Spaces for which every continuous function $f:X\to\mathbb{R}$ is constant are called strongly connected.
Pi-base is an useful database of topological spaces that lists some of them, see here. Also see the classic book, "Counterexamples in topology" by Steen and Seebach.
One of the more geometric examples here seems to be the irrational slope topology, see here. The reason given in the database is that its connected and countable, hence automatically strongly connected.
Comment: Elaborating on the last paragraph, if $X$ is connected and has size $<2^{\aleph_0}$ then $X$ is strongly connected: if a continuous $f:X\rightarrow\mathbb{R}$ contained distinct points $a,b$ in its range, then by connectedness of $X$ the whole interval $[a,b]$ would have to be in the range of $X$.
Comment: Thanks @NoahSchweber! I was actually introduced to examples of countable, connected, hausdorff spaces (e.g. the goloumb space) before, and it is clear why such spaces need to be "strongly connected". Not sure why such examples did not occur to me before.


Converter Double para String MongoDB

Question: Possuo um campo Double em uma collection no MongoDB e gostaria de trocar este campo em toda coleção para String.
Answer: //inteiro para string
db.temp.find({name: {$exists:true}}).forEach( function(x) {
    db.temp.update({_id: x._id}, {$set: {name: x.name.toString()}});
});

//string para data
db.temp.find({name: {$exists:true}}).forEach( function(x) {
    db.temp.update({_id: x._id}, {$set: {name: ISODate(x.name}});
});

//string para inteiro
db.temp.find({name: {$exists:true}}).forEach( function(x) {
    db.temp.update({_id: x._id}, {$set: {name: NumberInt(x.name)}});
});

Fonte: http://codigosimples.net/2016/03/05/conversao-de-tipos-com-mongodb/

Converter Double para String MongoDB