How to validate age and alert if the current date is the user's birthday?

Question: Okay, I'm very new to Javascript (I started about 2 months ago in my computer's class) and I'm doing an assignment that requires a form that includes date of birth (with day/month/year each in a dropdown) and I need to be able to:
a) Confirm that the user is over 18 and send an alert if not.
and;
b) Provide a "happy birthday" message if the current day is the user's birthday
I've searched tirelessly for a solution but I can't find one that I understand.
This is what I've got so far:
    <form name="contest">
    Date of Birth:
    Year: <select name="year">
            <option></option>
            <option>2015</option>
            <option>2014</option>
            <option>2013</option>
            <option>2012</option>
            <option>2011</option>
            <option>2010</option>
            <option>2009</option>
            <option>2008</option>
            <option>2007</option>
            <option>2006</option>
            <option>2005</option>
            <option>2004</option>
            <option>2003</option>
            <option>2002</option>
            <option>2001</option>
            <option>2000</option>
            <option>1999</option>
            <option>1998</option>
            <option>1997</option>
            <option>1996</option>
            <option>1995</option>
            <option>1994</option>
            <option>1993</option>
            <option>1992</option>
            <option>1991</option>
            <option>1990</option>
        </select>
    Month: <select name="month">
            <option></option>
            <option value="jan">January</option>
            <option value="feb">February</option>
            <option value="mar">March</option>
            <option value="apr">April</option>
            <option value="may">May</option>
            <option value="jun">June</option>
            <option value="jul">July</option>
            <option value="aug">August</option>
            <option value="sep">September</option>
            <option value="oct">October</option>
            <option value="nov">November</option>
            <option value="dec">December</option>
        </select>
    Day: <select name="day">
            <option></option>
            <option>01</option>
            <option>02</option>
            <option>03</option>
            <option>04</option>
            <option>05</option>
            <option>06</option>
            <option>07</option>
            <option>08</option>
            <option>09</option>
            <option>10</option>
            <option>11</option>
            <option>12</option>
            <option>13</option>
            <option>14</option>
            <option>15</option>
            <option>16</option>
            <option>17</option>
            <option>18</option>
            <option>19</option>
            <option>20</option>
            <option>21</option>
            <option>22</option>
            <option>23</option>
            <option>24</option>
            <option>25</option>
            <option>26</option>
            <option>27</option>
            <option>28</option>
            <option>29</option>
            <option>30</option>
            <option>31</option>
        </select>

    <input type="button" name="" onClick="checkInput(this.form)" value="Submit"/>
    <input type="reset"/>
</form>

Any help would be greatly appreciated! Thanks :)
Comment: What JavaScript have you tried?
Comment: So far you only have an HTML form.  Take a stab at writing the JavaScript for checkInput().  Consider using http://jsfiddle.net, as you can post a link to your efforts right here in your question.
Comment: @EricJ.- Better advice would be to use built-in *scriplet* markup. This way the code would be available as long as this site exists.
Comment: @PM77-1 Scriptlet?  How is that a thing in this context?
Comment: @JohnGreen - Sorry. Meant `snippet`.
Answer: Straightforward.
function checkInput()
{
  // get today's date.
  var today = new Date();
  today.setHours(0,0,0,0); // set time to start of day for comparison.

  // create a new date based on user input.
  var bdate = new Date(Date.parse(
    document.querySelector('select[name="year"]').value + ' ' +
    document.querySelector('select[name="month"]').value + ' ' +
    document.querySelector('select[name="day"]').value
  ));
  today.setYear(0); // ignore year part of date.
  bdate.setYear(0); // ignore year part of date.

  if (today.valueOf() == bdate.valueOf())
  {
    alert('Happy Birthday');
  }
  else
  {
    alert('Merry Unbirthday.');
  }
}

Comment: How would I extend that for the age restriction (must be over 18)?
Comment: By the way @cabellicar123  I made some previous attempts at the JS but it wasn't even close to correct
Answer: In your function(checkInput) you need to check if the current date is equal with the date that the user has give. You can get current date via:

var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // +1 Because january is 0
var year = today.getFullYear();

And then its easy to make the compare.


Impute with the Mean or Median? Instrumental Variables

Question: I am using instrumental variables and I have missing data.  In r, I don't believe you can use the MICE package with the AER package.  Therefore, I am going to impute with either the mean or median values.  My variable is heavily skewed, so I am incline to use the median value.  Do researchers use the median-imputation?  I am more familiar with researchers using mean-imputation.
Is there an alternative to imputation with the mean and median value?  If you can use the AER and MICE packages together, could someone point me to code that uses it?
Comment: Single imputation of the type you intend to use will result in seriously underestimated standard errors of your final parameter estimates, and false significance.  I would only use that approach if the proportion of incomplete observations is tiny.
Answer: The hard part about multiple imputation is the imputation, which mice can do even if for some reason you can't use the additional pooling functionality it provides. A quick look at the AER package suggests that it is mostly data, with examples using many functions like lm that certainly are compatible with mice.
If you do find a particular analysis function that is not compatible with the pooling functions of mice, proceed as follows, following the general procedure for multiple imputation:

Do your multiple imputations with mice and keep each separate complete imputed data set.
Perform your analysis separately on each of the imputed data sets.
Based on your understanding of the nature of the analysis method and the goals of your study, pool the results of the separate analyses appropriately. This can be as simple as taking means and variances of coefficients over the multiple imputation analyses.

This process is much better than relying on single imputations, and may have the side effect of helping you learn more about how the particular analysis method in question works.


SSL certificate does not update

Question: My previous SSL certificate just expired.

I tried to buy another free SSL certificate from AliCloud and also sslforfree.com. I'm pretty sure I have already installed a right certificate in the server. But when I test it in my Mac (www.10studio.tech), it always shows the old certificate.
Clearing browsing history does not help.
Could anyone confirm me that it is not working just for me? And what could I do?
Edit 1:
I use docker and nginx. In nginx and sslforfree.com, I have the following my_server_block.conf.
server {
  listen  3002;
  absolute_redirect off;
  root  /app;

  location = / {
    rewrite ^(.*)$ https://$http_host/docs/introduction redirect;
  }

  location / {
    try_files $uri $uri/ =404;
  }
}

server {
  listen  3001 ssl;

  ssl_certificate      /certs/whole.crt;
  ssl_certificate_key  /certs/private.key;

  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;

  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;

  location / {
    proxy_pass http://localhost:3002;
    proxy_redirect off;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Ssl on;
  }
}

docker-compose.yml:
version: "3"
services:
  docusaurus:
    image: bitnami/nginx:1.16
    restart: always
    volumes:
    - ./build:/app
    - ./certs:/certs:ro
    - ./my_server_block.conf:/opt/bitnami/nginx/conf/server_blocks/my_server_block.conf:ro
    ports:
    - "3001:3001"
    - "3002:3002"

nginx.conf:
# Based on https://www.nginx.com/resources/wiki/start/topics/examples/full/#nginx-conf
# user              www www;  ## Default: nobody

worker_processes  auto;
error_log         "/opt/bitnami/nginx/logs/error.log";
pid               "/opt/bitnami/nginx/tmp/nginx.pid";

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format    main '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status  $body_bytes_sent "$http_referer" '
                       '"$http_user_agent" "$http_x_forwarded_for"';
    access_log    "/opt/bitnami/nginx/logs/access.log";
    add_header    X-Frame-Options SAMEORIGIN;

    client_body_temp_path  "/opt/bitnami/nginx/tmp/client_body" 1 2;
    proxy_temp_path        "/opt/bitnami/nginx/tmp/proxy" 1 2;
    fastcgi_temp_path      "/opt/bitnami/nginx/tmp/fastcgi" 1 2;
    scgi_temp_path         "/opt/bitnami/nginx/tmp/scgi" 1 2;
    uwsgi_temp_path        "/opt/bitnami/nginx/tmp/uwsgi" 1 2;

    sendfile           on;
    tcp_nopush         on;
    tcp_nodelay        off;
    gzip               on;
    gzip_http_version  1.0;
    gzip_comp_level    2;
    gzip_proxied       any;
    gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
    keepalive_timeout  65;
    ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;

    include  "/opt/bitnami/nginx/conf/server_blocks/*.conf";

    # HTTP Server
    server {
        # port to listen on. Can also be set to an IP:PORT
        listen  8080;

        location /status {
            stub_status on;
            access_log   off;
            allow 127.0.0.1;
            deny all;
        }
    }
}

Comment: Your certificate is showing as expired according to SSL Labs. Can you share your configuration?
Comment: By the way, this isn't directly relevant to your problem, but the report also showed that your server is configured to accept connections using both TLS 1.0 and 1.1, both of which should be deprecated.
Comment: Where's your Docker configuration? Dockerfile, docker-compose.yml, whatever?
Comment: I just added `docker-compose.yml`; there is no `Dockerfile`.
Comment: I think you need to re`build` this. Your nginx is reporting version 1.9.4, which is quite old and not at all the 1.16 you've requested.
Comment: How did you see my nginx is `1.9.4`?
Comment: I just looked at the response headers.
Comment: I just added `nginx.conf`. How could I `rebuild` all this?
Answer: The obvious thing is you have to reload/restart your web server after updating the TLS certificate.
It looks like you're using docker-compose, but your containers don't seem to have been updated, as your nginx version reports 1.9.4 while you seem to have asked for 1.16.x. Consider force updating with something like:
docker-compose up --force-recreate --build -d

Comment: I did... I use docker, and I restarted the container, nginx... everything...
Comment: I added some note...
Comment: I just tried `docker-compose up --force-recreate --build -d`, it did not help...
Comment: @SoftTimur At this point I think there is some important detail that is missing. We don't have any way to know what that is. Please think about your set up and describe any part of it that you might not have mentioned before.
Comment: Don't you think it is because we did not clear the old SSL certificate on our machine properly?
Comment: @SoftTimur I have no idea. That is one of the things you have not yet described.
Comment: I wrote `clearing browsing history does not help`... By the way, `image: bitnami/nginx:1.16` is the version of the image, rather than the version of nginx...
Answer: Verify that the certificates in that location are the correct certificates.  Assuming you have correctly restarted nginx, and there is no other configuration overwriting the one you provided, nginx must be loading the certificates at that location.  Perhaps you placed the certificates in that directory on the host machine rather than in that directory within the Docker image?

SSL certificate does not update


How does the Metropolis Algorithm "get off the ground"?

Question: I'm thoroughly confused by the Metropolis Algorithm as defined in Casella and Berger's Statistical Inference. Namely, here's the definition (p.254):
Let $Y \sim f_Y(y)$ and $V \sim f_V(v)$, where $f_Y$ and $f_V$ have common support. To generate $Y \sim f_Y(y):$

Generate $V \sim f_V$. Set $Z_0=V$.

Then for $i=1,2,...:$

Generate $U_i \sim \text{uniform}(0,1)$, $V_i \sim f_V$, and calculate $\rho_i=\text{min}(\frac{f_Y(V_i)}{f_V(V_i)} \frac{f_V(Z_{i-1})}{f_Y(Z_{i-1})},1).$
Set $$Z_i =\begin{cases}
      V_i & \text{if }U_i\leq \rho_i \\
      Z_{i-1} & \text{if }U_i > \rho_i
   \end{cases}.$$

Then $Z_i \to Y$ in distribution as $i \to \infty$.
But with such a definition $\rho_1 = 1$ and $Z_1 = V$, so that all $\rho_i=1$ and all $Z_i = V$. Am missing something or is there an error in the definition?
Is it that even though $V_1$ and $Z_0$ have the same distribution, you're drawing twice and then not necessarily $v_1 = z_0$?
Comment: Why do you think that $p_i = 1$ for all $i$?
Comment: Your last paragraph does not appear to say anything about why you think $p_i = 1$ for all $i$....
Comment: @jbowman, see my last paragraph. Is that's how it's supposed to be understood? Because then I don't think that $\rho_i = 1$ for all $i$ anymore. But if not, then I thought the two terms would just be reciprocals of one another, because $V_i = Z_{i-1} = V$.
Answer:
The confusion stems from a misunderstanding of the notation $$V \sim
  f_V$$ which means both (a) $V$ is a random variable with density $f_V$
  and (b) $V$ is created by a PRNG algorithm that reproduces a
  generation of a random variable with density $f_V$. Each time a
  generation $V_i\sim f_V$ occurs in the algorithm from Casella and
  Berger, a new realisation of a random variable with density $f_V$
  occurs, which is independent from all previous realisations, hence
  different from these previous realisations. (Setting aside discussions
  about the pseudo-randomness of these generators and the resulting
  approximation in the independence statement.) Equivalently, stating that the $_$'s are all identically distributed from the same distribution $_$ does not mean that their realisations all are numerically identical.

The starting point of the Metropolis-Hastings algorithm is arbitrary, either fixed $Z_0=0$ for instance or random, for instance $Z_0\sim f_V$ [a notation meaning that $Z_0$ is distributed from $f_V$]. This starting value is always accepted. For $i=1$, one generates $V_1\sim f_V$ [meaning that $V_1$ is distributed from $f_V$, independently and thus different from $Z_0$]
$$Z_1 =\begin{cases}
      V_1 & \text{if }U_1\leq \rho_1=\min\left(\frac{f_Y(V_1)}{f_V(V_1)} \frac{f_V(Z_{0})}{f_Y(Z_{0})},1\right) \\
      Z_{0} & \text{if }U_1 > \rho_1
   \end{cases}$$
and $\rho_1\ne 1$ in general. Hence sometimes $V_1$ is accepted and sometimes not. The same applies to the following steps.
To make a toy illustration on how the algorithm applies, take $f_V$ to be the density of a $\mathcal N(0,1)$ distribution and $f_Y$ to be the density of a $\mathcal N(1,1)$ distribution. A sequence of iid generations from $f_V$ is for instance [by a call to R nrorm]
$$0.45735433,-0.99178415,-1.08312586,-0.85762451,0.92186197,-0.50442298,...$$
[note that they are all different] and a sequence of generations from $\mathcal U$ is for instance [by a call to R nunif]
$$0.441328,0.987837,0.386258,0.316593,0.195910,0.2772669,...$$
[note that they are all different]. Applying the algorithm with starting value $Z_0=0$ means considering
$$\frac{f_Y(V_1)}{f_V(V_1)} \frac{f_V(Z_{0})}{f_Y(Z_{0})}=0.9582509\big/
0.6065307=1.579889>1$$
which implies that $Z_1=V_1=0.45735433$. Then
$$\frac{f_Y(V_2)}{f_V(V_2)} \frac{f_V(Z_{1})}{f_Y(Z_{1})}= 0.2249709 \big/ 0.9582509 = 0.2347724 < U_2=0.987837$$
which implies that $Z_2=Z_1$. The algorithm can be applied step by step to the sequences provided above, which leads to
\begin{align*}
\frac{f_Y(V_3)}{f_V(V_3)} \frac{f_V(Z_{2})}{f_Y(Z_{2})}&=0.2053581 \big/0.9582509 = 0.2143051 < U_3 \qquad Z_3 = Z_1\\
\frac{f_Y(V_4)}{f_V(V_4)} \frac{f_V(Z_{3})}{f_Y(Z_{3})}&=0.2572712 \big/0.9582509 = 0.2684800 < U_4 \qquad Z_4 = Z_1\\
\frac{f_Y(V_5)}{f_V(V_5)} \frac{f_V(Z_{4})}{f_Y(Z_{4})}&=1.5247980 \big/0.9582509 = 1.591230 > 1 \qquad\quad  Z_5 = V_5\\
&\qquad\qquad\vdots\\
\end{align*}
producing a sequence as, e.g., below (notice the flat episodes in the graph, which correspond to a sequence of rejections).
$\qquad\qquad\qquad$
As a last remark, the only potentially confusing part in the description of Casella and Berger is the very first sentence where the random variables $Y$ and $V$ are not needed. It could have been clearer to state "Let $f_Y$ and $f_V$ be two densities with common support."
Comment: Not at all: I mean that you can take over and repeatedly apply the same steps for the subsequent values of $V_3$, $V_4$, ..., to see when the next value of $V_i$ is accepted and when it isn't.
Comment: What's unclear about it? The definition above states that $Z_0 =V \sim f_V$ and that all subsequent $V_i \ \sim f_V$ also. This is the definition given in the book and I was or am confused about how the algorithm works given that.
Comment: At the very end, when you say that $Z_2 = Z_1$ and so on, you mean that $Z_1 = Z_2 = Z_3 = \dots$?


Variável de sessão vazia quando redirecionado

Question: Estou usando variáveis de sessão para verificar o usuário logado no site.
Tenho dois links diferentes para a mesma página, um gerado automaticamente por um script PHP através de uma consulta no meu banco de dados. O outro eu mesmo coloquei no site.
O que está acontecendo é o seguinte, quando uso o link gerado pela consulta no banco de dados as variáveis de sessão que tenho definidas mantém todas o seu valor. Mas quando uso o link que eu coloquei na página, todas as variáveis de sessão ficam vazias.
Alguém tem alguma ideia do que pode estar acontecendo?
Comment: Olá gabriel, sem código não tem como resolver seu problema.
Comment: Está utilizando `session_start();` em todas as páginas?
Comment: Oi Marcelo, coloquei o código resumido embaixo
Comment: Uso `session_start();` em todas as páginas sim
Answer: Enfim, consegui resolver meu problema, mas vou deixar as coisas mais bem explicadas aqui para alguém que possa ter o mesmo problema que o meu.
Em uma página do site gero o link para outra pelo seguinte script:
<?php
//Verifica as questões do relatório disponíveis no banco de dados
$query = "SELECT idquestao, numquestao FROM questao WHERE relatorio_idrelatorio = '"
        . $_GET['id'] . "' ORDER BY numquestao";
$result = mysqli_query($link, $query);
while ($linha = mysqli_fetch_array($result)) {
    $acessar = "http://www.site.com/questao.php?id=" . $linha['idquestao'];
    echo "
Atividade " . $linha['numquestao'] . "
";
}
?>

E nessa mesma página gero um link para a mesma outra página pelo código:
Reponder

O meu problema era o seguinte, quando usava o link que foi gerado pelo script PHP era redirecionado para a outra página e as minhas variáveis de sessão mantinham os seus valores.
<?php
    session_start();
    if (!$_SESSION['id'] || !$_SESSION['nome'] || !$_SESSION['usuario']) {
        //header("Location:http://www.site.com/?erro=2");
    }
    echo $_SESSION['id'];
    echo $_SESSION['nome'];
    echo $_SESSION['usuario'];
?>

De forma que o código acima exibia os valores passados para as variáveis quando o usuário fez o login.

2 Gabriel gabriel

Porém quando usava o link que eu mesmo tinha colocado na página, as variáveis de sessão apareciam vazias.

A forma como o problema se resolveu foi apenas retirando o "www" do início do link
Reponder

Dessa forma quando clico no link as variáveis de sessão apresentam os valores corretamente.

2 Gabriel gabriel

Não sei o porque desse problema, mas resolvi dessa forma.
Aparentemente o PHP não gosta de "www" rs


How to resize the disk of a Fedora guest VM in VMWare ESXi

Question: How do I resize (specifically increase) the disk size of a Fedora guest VM running under VMWare ESXi 4.1?
I have a Fedora 16 VM with an lvm2 formatted disk, and I've increased its disk size using the vSphere client from 50GB to about 250GB. I rebooted the guest, and it correctly shows this size using fdisk -l /dev/sda. However, df -H still shows the old size.
I've found a few KB articles explaining how to resize partitions for some flavors of Linux, but nothing for Fedora with ext4. That article seems to imply I have to create a completely new partition, and that I can't simply expand the existing partition. Using Gparted, it also prevents me from simply resizing the existing partition. Is this impossible to do under Linux?
Edit: It turns out the drive is formatted as LVM2, which apparently most Linux tools, such as GParted, don't support.
Edit: The partition in logical volume I need to resize is the root partition. Is there any way to do this without a LiveCD?
Answer: This is a bit of a cut'n'paste of a document I wrote for internal use and although it probably over-answers your question I thought I'd put it on here in case it's of use to you or others OK.

Login to the machine as root or sudo each of the following commands, enter fdisk –l, you should see something like this;
Disk /dev/sda: 21.1 GB, 21xxxxxxxxx bytes
255 heads, 63 sectors/track, 5221 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          13      104391   83  Linux
/dev/sda2              14        2610    20860402+  8e  Linux LVM

In this case I've altered the values but as you can see this machine has a single ~20GB root virtual disk with two partitions, sda1 and sda2, sda2 is our first LVM 'physical volume', see how LVM uses a partition type of '8e'.
Now type pvdisplay, you'll see a section for this first PV (sda2) like this;
  --- Physical volume ---
PV Name               /dev/sda2
VG Name               rootvg
PV Size               19.89 GB / not usable 19.30 MB
Allocatable           yes (but full)
PE Size (KByte)       32768
Total PE              636
Free PE               0
Allocated PE          636
PV UUID               PgwRdY-EvCC-b5lO-Qrnx-tkrd-m16k-eQ9beC

This shows that this second partition (sda2) is mapped to a 'volume group' called 'rootvg'.
Now we can increase the size of the virtual disk using the usual vSphere VSClient by selecting the VM, choosing to 'edit settings', then selecting 'Hard Disk 1'. You can then increase the 'Provisioned Size' number – so long as there are no snapshots in place anyway – and select OK. This will take a few seconds to complete.
If you then switch back to the Linux VM and enter
echo "- - -" > /sys/class/scsi_host/hostX/scan

where the X character is likely to be zero, it will perform a SCSI bus rescan, then run fdisk –l, you should see something like;
Disk /dev/sda: 42.2 GB, 42xxxxxxxxx bytes
255 heads, 63 sectors/track, 5221 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          13      104391   83  Linux
/dev/sda2              14        2610    20860402+  8e  Linux LVM

You'll see that the disk size has increased, in this case to ~40GB from ~20GB but that the partition table remains the same.
We now need to create a new LVM partition, type parted, you should see something like this;
GNU Parted 1.8.1
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted)

You'll now need to create a new partition for the extra new space, type 'p' to see the current partition table such as this;
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 42.9GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system  Flags
 1      32.3kB  107MB   107MB   primary  ext3         boot
 2      107MB   21.5GB  21.4GB  primary               lvm

Then type mkpart, then select 'p' for 'Primary', for file system type enter 'ext3', for start enter a number a little higher than the combination of both 'sizes' listed above (i.e. 107MB + 21.4GB, so say 21.6GB), for end type the size of the disk (i.e. in this case 42.9GB). Once you press enter it will create this new primary partition, type 'p' to show the new partition table, you should see something like;
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 42.9GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system  Flags
 1      32.3kB  107MB   107MB   primary  ext3         boot
 2      107MB   21.5GB  21.4GB  primary               lvm
 3      21.5GB  42.9GB  21.5GB  primary               ext3

You'll see that the new partition started after the first two and fills the available space, unfortunately we had to set it to a type of 'ext3', so let's change that.
Type 't', then the partition number (in our case 3 as it's the third partition), then for the 'hex code' enter '8e' – once you'd done this type 'p' again and you should see it change to 'Linux LVM';
Disk /dev/sda: 42.9 GB, 42949672960 bytes
ads, 63 sectors/track, 5221 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        1          13      104391   83  Linux
/dev/sda2           14        2610    20860402+  8e  Linux LVM
/dev/sda3         2611        5221    20972857+  8e  Linux LVM

Now we need to create a new LVM 'physical volume' in this new partition, type pvcreate /dev/sda3, this should then create a new LVM PV called /dev/sda3, type pvdisplay to check;
--- Physical volume ---
PV Name               /dev/sda3
VG Name
PV Size               20.00 GB / not usable 1.31 MB
Allocatable           no
PE Size (KByte)       0
Total PE              0
Free PE               0
Allocated PE          0
PV UUID               gpYPUv-XdeL-TxKJ-GYCa-iWcy-9bG6-tfZtSh

You should see something similar to above.
Now we need to extend the 'rootvg Volume Group', or create a new one for non-root 'volume group', type vgdisplay to list all 'volume groups', here's an example;
--- Volume group ---
VG Name               rootvg
System ID
Format                lvm2
Metadata Areas        2
Metadata Sequence No  19
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                8
Open LV               8
Max PV                0
Cur PV                2
Act PV                2
VG Size               21.3 GB
PE Size               32.00 MB
Total PE              1276
Alloc PE / Size       846 / 26.44 GB
Free  PE / Size       430 / 13.44 GB
VG UUID               tGM4ja-k6es-la0H-LcX6-1FMY-6p2g-SRYtfY

If you want to extend the 'rootvg Volume Group' type vgextend rootvg /dev/sda3, once you press enter you should see a message saying the 'volume group' has been extended.
If you wanted to create a new 'volume group' you'll need to use the vgcreate command – probably best call me for help with that.

Once extended enter vgdisplay again to see that the 'rootvg' 'volume group' has indeed been extended such as here;
--- Volume group ---
VG Name               rootvg
System ID
Format                lvm2
Metadata Areas        2
Metadata Sequence No  19
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                8
Open LV               8
Max PV                0
Cur PV                2
Act PV                2
VG Size               39.88 GB
PE Size               32.00 MB
Total PE              1276
Alloc PE / Size       846 / 26.44 GB
Free  PE / Size       430 / 13.44 GB
VG UUID               tGM4ja-k6es-la0H-LcX6-1FMY-6p2g-SRYtfY

You can see the 'VG Size' is as expected.
Now we need to extend the 'logical volume', type lvdisplay to show our 'logical volumes', you'll see something like;
--- Logical volume ---
LV Name                /dev/rootvg/var
VG Name                rootvg
LV UUID                NOP1jF-09Xt-LkX5-ai4w-Srqb-xGka-nYbI2J
LV Write Access        read/write
LV Status              available
# open                 1
LV Size                3.00 GB
Current LE             320
Segments               3
Allocation             inherit
Read ahead sectors     auto
currently set to       256
Block device           253:2

If we want to expand the /var file system from 3GB to 10GB then type lvextend –L 10G /dev/rootvg/var, now type lvdisplay again, you'll see the 'logical volume' has grown to 10GB;
--- Logical volume ---
LV Name                /dev/rootvg/var
VG Name                rootvg
LV UUID                NOP1jF-09Xt-LkX5-ai4w-Srqb-xGka-nYbI2J
LV Write Access        read/write
LV Status              available
# open                 1
LV Size                10.00 GB
Current LE             320
Segments               3
Allocation             inherit
Read ahead sectors     auto
currently set to     256
Block device           253:2

Now the last thing we need to do is to grow the actual file system, this doesn't have to use all of the newly added space by the way. Enter df –h to show the current filesystems, here's an example;
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/rootvg-root
                      2.0G  1.4G  495M  74% /
/dev/mapper/rootvg-home
                      248M  124M  113M  53% /home
/dev/mapper/rootvg-var
                      3.0G  1.1G  1.8G  30% /var
/dev/mapper/rootvg-usr
                      3.0G  936M  1.9G  34% /usr
/dev/mapper/rootvg-opt
                      3.0G  811M  2.0G  29% /opt

If we want to expand the /var file system from 3GB to 10GB then type resize2fs /dev/mapper/rootvg-var (or on CentOS maybe xfs_growfs /dev/mapper/rootvg-var, or similar commands depending on the type of file system).  When you press enter the actual filesystem will grow, this may take time, enter df –h once completed to check.
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/rootvg-root
                      2.0G  1.4G  495M  74% /
/dev/mapper/rootvg-home
                      248M  124M  113M  53% /home
/dev/mapper/rootvg-var
                      9.88G  1.1G  8.2G  12% /var
/dev/mapper/rootvg-usr
                      3.0G  936M  1.9G  34% /usr
/dev/mapper/rootvg-opt
                      3.0G  811M  2.0G  29% /opt

You're now finished!
Comment: Step 8 fails for me, when I try to run `lvextend /dev/mapper/VolGroup-lv_root /dev/sda3`, with the error: Physical Volume "/dev/sda3" not found in Volume Group "VolGroup"
Comment: On `CentOS 7` use `xfs_growfs /dev/centos/root` instead of `resize2fs /dev/centos/root` as explained http://stackoverflow.com/questions/26305376/resize2fs-bad-magic-number-in-super-block-while-trying-to-open
Answer: Perform the following steps before lvextend

#pvcreate /dev/sda3 (to create a new physical volume, if you can't create then probably you didn't reboot after creating the partition)
#pvdisplay (to check that you have created a new physical volume)
#vgcreate VolGroup /dev/sda3 (to assign the VolGroup to the new physical volume)
#lvdisplay (to get the logical path name of the partition you want to extend)
#lvcreate -LxxGB -n root_new VolGroup (to assign logical size and create a new logical volume)
#lvextend /dev/mapper/VolGroup-lv_root /dev/sda3 (extend the root(if) partition finally)
#lvdisplay (check the LV size if it has increazed or not)
#resize2fs /dev/mapper/VolGroup-lv_root (to resize the actual file-system)
#df -h (then check whether the actual file-system value has increazed or not)
Answer: you have to resize it now
resize2fs /dev/sda

You must be on the 2.6 kernel do this with the file system mounted and the parameter enabled to allow online resizing.  Otherwise, you have to first unmount the device, resize, them mount the device again.
Comment: "Device or resource busy..."


is it possible that $X_{j}$ and $X_{k}$ are independent of each other conditioning on $Z = f(X_1,\cdots, X_N)$?

Question: Suppose I have $N$ random variables $\{X_j\}_{j=1}^N$ and they are mutually independent. Also, I define $Z = f(X_1,\cdots,X_N)$ for some function $f()$. And I want to know that if it is possible that $X_j$ is independent of $X_k$ conditioning on $Z$ for any $j\ne k$.
I have asked a similar question where $N=2$ and $f(X_1,X_2) = X_1+X_2$, and the statement is false. I want to know if the statement is possibly true for general $N$ and some function $f(\cdot)$. Here I assume $\{X_j\}$ are not constant random variables.
Answer: Yes, it's possible.
Suppose $X_i$ are Rademacher variables ($\pm 1$ with equal probability) and $Z=\sum_i X_i^2$. Then $Z$ is constant, so conditioning on it has no effect.
Less trivially, suppose $Z=\prod_i X_i$ and $N>2$. For any specific $j, k$, $$P(Z=1|X_j,X_k)=1/2$$
so the distribution of $(X_j,X_k)|Z$ is the same as their unconditional distribution.  In this situation, any $N$ of $(X_1,X_2,\dots,X_N,Z)$ are mutually independent but the full set is not.
As a slight extension, suppose $X_i\sim N(0,1)$, and $Z=\prod_i \mathrm{sign} X_i$. By the same argument as before, $Z$ is independent of any set of fewer  than $N$ $X_i$s.
I can't think of an example where the $X_i$ are all continuous and $Z$ is a continuous, non-constant function of all of them. I'd be a bit surprised if there was one, but not very surprised.


Lumen - Change default Storage path

Question: I'm trying to find out how to change the default storage location (including it's subfolders) on a Lumen project. For several reasons, given the current configuration of the production web server, Lumen throws a permission denied exception when trying to write logs or compile Blade views.
The only alternative, without involving the sysadmin, is to move the storage folder to a tmp folder on the webserver.
On laravel there seems to be a method called "useStoragePath", but it doesn't seem to be available on Lumen (5.2.x).
The default paths seem to be "hardcoded", I found this:
Project\vendor\laravel\lumen-framework\src\Application.php

/**
     * Get the storage path for the application.
     *
     * @param  string|null  $path
     * @return string
     */
    public function storagePath($path = null)
    {
        return $this->basePath().'/storage'.($path ? '/'.$path : $path);
    }

And for the logs (same file):
/**
     * Get the Monolog handler for the application.
     *
     * @return \Monolog\Handler\AbstractHandler
     */
    protected function getMonologHandler()
    {
        return (new StreamHandler(storage_path('logs/lumen.log'), Logger::DEBUG))
                            ->setFormatter(new LineFormatter(null, null, true, true));
    }

Bottom line: Is there any clean way of overriding the default storage path keeping in mind this restrictions?:

It should not involve the sysadmin (sym links, changing permissions, etc.)
Not tampering with the vendor folder.
Answer: On Line 286 of vendor/laravel/lumen-framework/src/helpers.php:
if (! function_exists('storage_path')) {
    /**
     * Get the path to the storage folder.
     *
     * @param  string  $path
     * @return string
     */
    function storage_path($path = '')
    {
        return app()->storagePath($path);
    }
}

The key here is this line:
if (! function_exists('storage_path'))

That means if a function named storage_path hasn't already been defined, then Lumen will use its own implementation.
All you have to do is simply write your own function that returns your own custom path.
Because Lumen has far fewer rules than Laravel, how you do this is entirely up to you. That said, I would suggest doing it the following way:

Place a file called helpers.php under your app directory
Add any and all custom helper functions into this file including your own storage_path implementation
Make sure this file is loaded before Lumen itself. In order to do that, you need to place your require statement before composer's autoloader. This can be done at the very first line under bootstrap/app.php:
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__ . '/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

....

Comment: how to set it into `/public`?

Lumen - Change default Storage path


JQuery Onclick Menu Slide

Question: I have the following menu which is working:
https://jsfiddle.net/5g111cyx/
But ofcourse this is an amateur version. I need the code to handle the div menu's once I add or remove menu's automatically, instead of having to change this code every single time:
$('#1').click(function () {
    $('#sub2').hide(150);
    $('#sub3').hide(150);
    $('#sub1').slideToggle(150);
});

How would I go about it in a simple, yet effective way?
Answer: Please use this
$('#1,#2,#3').click(function () {
    var isActive = $(this).next("div").hasClass('active');
    $(".menu").each(function(){
        $(this).slideUp(150);
        $(this).removeClass('active')
    });
    if(! isActive ){
        $(this).next("div").slideToggle(150);
        $(this).next("div").addClass('active');
        $(this).siblings().next("div ul").hide(150);
    }
});

DEMO1
UPDATED CODE
$(document).ready(function () {
    $('#1,#2,#3').click(function () {
        var isActive = $(this).next("div").hasClass('active');
        $(".menu").each(function(){
            $(this).slideUp(150).removeClass('active');
        });
        if(! isActive ){
            $(this).next("div").slideToggle(150).addClass('active');
            $(this).siblings().next("div ul").hide(150);
        }
    });
});

DEMO2
Comment: I have updated the code and made some HTML alterations. See the "DEMO"
Comment: @RonBrouwers I have updated the code as per your need. Please see the latest change by clicking "DEMO".
Comment: Thanks, it works but it doesn't hide all other open divs when you open more than one. How would I go about that?
Comment: Nice, thanks a lot. Although there is still one thing that I would like to know. I also want to hide the div that is currently open, onclick. So I can toggle one div. When I click an open div now, it closes and immediately opens again.
Answer: Try this code.

$('div.show').click(function(){
  $('.menu').hide('slow');
  var idattr = $(this).attr('id');
   $('#sub'+idattr).slideToggle(150);
    $('#sub'+idattr).addClass('active')
});

Menu Div 1

Div 1 Test 1

Div 1 Test 2

Div 1 Test 3

Menu Div 2

Div 2 Test 1

Div 2 Test 2

Div 2 Test 3

Menu Div 3

Div 3 Test 1

Div 3 Test 2

Div 3 Test 3

JQuery Onclick Menu Slide


How do I pass *args to my timeit.Timer object?

Question: I originally made a custom function for timing functions that looks like this:
def timefunc(function, *args):
    start = time.time()
    data = function(*args)
    end = time.time()
    time_taken = end - start
    print "Function: "+function.__name__
    print "Time taken:",time_taken
    return data

Now, having learned about the timeit module, I want to implement the same thing using that. I just can't figure out how to do it while sending it the function and *args arguments.  I have already figured out that I have to do this in the setup arg:
"from __main__ import function"

But I can't figure out what to do about *args, since both the 'stmt' and 'setup' arguments are strings, how can I pass the variables?
Comment: I think you can do `*(args + [arg1, arg2])`.
Answer: Starting with Python 2.6 the timeit module besides a string also accepts a callable as stmt. With that in mind you can do this:
import timeit

def timefunc(function, *args):
    def wrap():
        function(*args)
    t = timeit.Timer(wrap)
    return t.timeit(100)

def test(arg):
    foo = arg

print(timefunc(test, 'bar'))


Removing object from array and replacing it with object from another array

Question: The problem I have encountered is as follows: I have created two array  representing docking spaces for ships. The first array ship object be saved in the array and if there is no space then it will be added to a waiting list array. But when I remove an object from the first array the object from the waiting list array is not removed and added.
The dock can accommodate three sizes of ship; cargo, container and super-container. The rows are made up of 5 small and 3 medium and 2 large. A cargo ship (small) can berth in any available space. A container ship (medium) can berth in the medium space and large, but not in small spaces. A super-container can only fit in large space.
So if I enter shipName3 and Super-Container for example and there is already two Super-Container's it adds to the waiting list but when I remove a Super-Container from the dock it does not remove a ship from the waiting list and add it to the dock  Can you help? Here's my dock method:
import java.util.*;

public class Main {

static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];

public static void main(String[] args) {
    menu();
}

public static void menu() {

    Scanner scan = new Scanner(System.in);

    while (true) {

        System.out.println("Choose an option: 1-3");
        System.out.println("1. Dock");
        System.out.println("2. Undock");
        System.out.println("3. Status");

        int menu = scan.nextInt();
        switch (menu) {
            case 1:
                System.out.println("1. Dock");
                dock();
                break;
            case 2:
                System.out.println("2. Undock");
                undock();
                break;
            case 3:
                System.out.println("3. Status");
                printDock();
                printWaitingList();
                break;
            case 4:
                System.out.println("4. Exit");
                System.exit(0);
            default:
                System.out.println("No such option");
                break;
        }
    }
}

public static void dock() {

    System.out.println("Enter ship's name: ");
    String name = scan.nextLine();

    System.out.println("Enter ship's size: ");
    String size = scan.nextLine();

    System.out.println("Enter the ships dock:");
    //Check if the dock number is valid
    int i = Integer.valueOf(scan.nextLine());
    if (i >= 0 && i < 10 && dock1[i] == null) {
        int c = 0;
        int co = 0;
        int sco = 0;
        for (int j = 0; j < dock1.length; j++) {
            if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
                c++;
            }
            if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
                co++;
            }
            if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
                sco++;
            }
        }

        if (c < 10 && co < 5 && sco < 2) {
            //Add ship to the dock
            dock1[i] = new Ship(name, size);
            System.out.println("Enough space you can dock");
            System.out.println("Ship has been docked");
        } else {
            System.out.println("You cannot dock");
            waitingList(name,size);
        }

    } else {
        System.out.println("Couldn't dock");
        waitingList(name, size);
    }

}

public static void undock() {
    System.out.println("Status of ships: ");
    printDock();
    System.out.println("Enter ship's name to undock: ");
    String name = scan.nextLine();
    System.out.println("Enter ship's size to undock: ");
    String size = scan.nextLine();
    for (int i = 0; i < dock1.length; i++) {
        if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
            dock1[i] = null;
            System.out.println("Ship removed");
           //break;
            ///HERE CHECK IF SHIP IN DOCK
            for (int j = 0; j < dock1.length; j++) {
                if (dock1[j] == null) {
                    //Add ship to the dock
                    dock1[j] = new Ship(name, size);
                    System.out.println("Move ship from waiting list to dock 1");
                    break;
                } else {
                    System.out.println("No space in dock1");
                    return;
                }
            }
        } else {
            System.out.println("Ship not docked here");
            break;
        }

    }

}

public static void waitingList(String name, String size){
    System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
    for (int i = 0; i < dock1.length; i++) { //waitingList?
        if (waitingList[i] == null) {
            //Add ship to the dock
            waitingList[i] = new Ship(name, size);
            System.out.println("Enough space added to waiting list");
            break;
        } else {
            System.out.println("No space on waiting list, ship turned away");
            return;
        }
    }

}

public static void printDock() {

    System.out.println("Docks:");

    for (int i = 0; i < dock1.length; i++) {
        if (dock1[i] == null) {
            System.out.println("Dock " + i + " is empty");
        } else {
            System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
        }
    }
}

private static void printWaitingList() {

    System.out.println("Waiting List:");

    for (int i = 0; i < waitingList.length; i++) {
        if (waitingList[i] == null) {
            System.out.println("Dock " + i + " is empty");
        } else {
            System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
        }
    }
}
}

Ship class
public class Ship {

private String shipName;
private  String shipSize;

public String getShipName() {
    return shipName;
}

public void setShipName(String shipName) {
    this.shipName = shipName;
}

public String getShipSize() {
    return shipSize;
}

public void setShipSize(String shipSize) {
    this.shipSize = shipSize;
}

public Ship(String shipName, String shipSize) {
    this.shipName = shipName;
    this.shipSize = shipSize;
}
}

I put my attempt in the undock method.
Comment: @S.smith94 when you will remove object from an array then you have to add elements from waiting list to array if objects are present in waiting list and if there is space in array? correct me if i am wrong
Comment: where is the error method name ?
Comment: The problem is in the undock class but there is no error message it just does not move the object
Comment: @S.smith94 at the same time you have to remove object from waiting list
Comment: yes I need to remove it from the waiting list array and add to dock1 array
Comment: ///HERE CHECK IF SHIP IN DOCK
            for (int j = 0; j < dock1.length; j++) { dock1 is also in inner loop should it be waitingList
Comment: I have tested both waitingList and dock1 for that bit but it doesn't fix the problem
Comment: @S.smith94 have you tried my answer?
Comment: Just trying it now
Answer: Please check your undock method in that you are removing from dock1 array and again you are adding to same object to dock1 array but there is no code to remove object from waitingList array simply update your loop in undock method as mentioned below
for (int i = 0; i < dock1.length; i++) {
        if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
            dock1[i] = null;
            System.out.println("Ship removed");
            // break;
            /// HERE CHECK IF SHIP IN DOCK
            for (int j = 0; j < waitingList.length; j++) {
                if (dock1[i] == null) {
                    // Add ship to the dock
                    dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
                    System.out.println("Move ship from waiting list to dock 1");
                    waitingList[j]=null;
                    break;
                } else {
                    System.out.println("No space in dock1");
                    return;
                }
            }
        } else {
            System.out.println("Ship not docked here");
            break;
        }

    }

I have changed inner loop iteration so it will loop to the size of waitingList array because we need to remove object from waitingList aray and add to dock1 array.Also i am runtime getting the shipname and shipsize from waitingList array so that it will add object from waitingList to dock1 array. I have tested code to my machine working here hope it will help you.
Comment: @S.smith94 check elements in array
Answer: In your undock method, you remove the ship at the i'th position in dock1 array by setting it to null. This is ok but then you have a for loop that runs through all of the ships in dock1 looking for one with a null valued one. You aready know the one you just removed is null because you just set it to that value. Then you set it equal to a new ship that has the exact name and size of the one you removed (essentially putting the ship back). Instead, you want the for loop to traverse your list of waiting ships to find one that matches the space of the ship you just removed.
Replace:
for (int j = 0; j < dock1.length; j++) {
    if (dock1[j] == null) {
        //Add ship to the dock
        dock1[j] = new Ship(name, size);
        System.out.println("Move ship from waiting list to dock 1");
        break;
     } else {
         System.out.println("No space in dock1");
         return;
     }
 }

with
for (int j = 0; j < waitingList.length; j++) {
    if (waitingList[j].getShipSize() <= size) {
        //Add ship to the dock
        dock1[i] = waitingList[j];
        System.out.println("Move ship from waiting list to dock 1");
        return;
    }
}
System.out.println("No space in dock1");
return;


Variance within each cluster

Question: I have done some clustering to a matrix with 30 random variables , each variable has 13000 observations ). i got 10 clusters
and now i need to test how good the clustering is by calculating the variance in each cluster.
does anyone knows how can i calculate the variance?
i can easily calculate the variance of each column in my matrix (e.g the variance of each random variable) but i want to calculate the variance of the whole cluster.
does anyone know how it can be done?
e.g.
<code>data <- data.frame(x=c(2,2,2,3,7),
               y=c(30,40,40,30,10),
               z=c(1,2,3,4,5),
               cluster=c('a','a','c','a','c'))

candidates <- dlply(data,.(cluster),function(data){
 laply(data[,-4],var)
})
</code>
This gives variance per column for each cluster label (a,c). I don't think it's the right approach.
Comment: By the term "multivariate variance within a cluster" we usually mean the sum of diagonal elements (the trace) of the covariance matrix computed for that cluster.
Comment: "Variance" is a function of one variable, so I'm not clear what you mean by "variance of a cluster". You could find various measures of the distance between points, calculated in various ways. Is that what you had in mind?
Answer: According to the Hastie equation 14.31 (see also Halkidi et al. 2001), the within-cluster variance $W(C_{k})$ of a cluster $C_{k}$ is defined (for the Euclidean distance) as $\sum_{x_{i}\in{C_{k}}}\|x_{i}-\bar{x}_{k}\|^2$ , where $\bar{x}_{k}$ is the mean of cluster $C_{k}$ (also called the cluster centroid, its values are the coordinate-wise average of the data points in $C_{k}$), and {${x_{1}, ..., x_{N}}$} is the set of observations (they are vectors, i.e., one coordinate per dimension). In plain English, the cluster variance is the coordinate-wise squared deviations from the mean of the cluster of all the observations belonging to that cluster. The total within cluster scatter (for the entire set of observations) is simply $W=\sum\limits_{k=1}^K\sum_{x_{i}\in{C_{k}}}\|x_{i}-\bar{x}_{k}\|^2$ for K clusters and N observations with $K<N$. The goal of a clustering algorithm such as K-means is to minimize this quantity (or to maximize the between-cluster variance $B$). The total point scatter in the data set (the information) $T$ is equal to $W+B$. When clustering, we just make sense of the information originally present by decreasing $W$ and increasing $B$ as much as possible, however, $T$ remains constant, there is no information loss (as opposed to dimensionality reduction techniques such as PCA, for instance).
Comment: This is picky, but in the previous answer I would not call W(c_k) the "within-cluster variance" since it does not involve dividing by the degrees of freedom. HTF call it the scatter, but do not call it a variance.

Variance within each cluster


vim indentation correction not working correctly

Question: I'm using vim to edit files that use a programming language where the end of line is not marked with ;. This causes problems when I try to fix indentation in vim. If I put a ; at the end then vim is able to correctly fix the indentation, but since this programming language doesn't have a ; at the end of a statement the indentation isn't correct after vim tries to fix it.
Here is the code correctly formatted:
if imageFound("foo.bmp")
{
    clickButton("button1.bmp")
    clickButton("button2.bmp")
}

If I do =G then in will turn into this, which is incorrectly formatted:
if imageFound("foo.bmp")
{
    clickButton("button1.bmp")
        clickButton("button2.bmp")
}

However, if I put a ; at the end of one of the lines the line underneath it will be correctly formatted.
if imageFound("foo.bmp")
{
    clickButton("button1.bmp");
    clickButton("button2.bmp")
}

How can I make vim correctly fix the formatting without having to put a ; at the end of lines?
Answer: :set cindent cinoptions=+0.


Getting KeyError in my django code

Question: I'm new to both Django and Python so please forgive me if I come off as annoying....I'm just very much misinformed!
Error Code: http://i.gyazo.com/68d88cabf536b129dc37cde6c3ae319c.png
I've googled about this 'KeyError' and it seems to be related to clean(). However, the example my lecturer gave me worked ok without it but when I tried to recreate what he gave me I kept getting this error.
A bit of info: I had originally had a ForeignKey for the user for each submission so I changed it to a simple form to fill in (not a permanent solution) but I still get a KeyError.
Here is my models, views and forms:
http://pastebin.com/rAX5PDHQ
Sorry if I left something out. I'll respond ASAP if you all need more info.
Again, sorry if this is a silly question. But I'm utterly lost to be honest.
Thank you!
PS Sorry I really tried the code formatting but I kept getting an error saying it was incorrect thought the preview said it was ok. And I can't post more than one link.
Answer: You don't have a field named user in your form. Try changing the relevant line to:
 bd = BloodData  (respondent=cd['respondent'],

in your "storeBloodData" view.
Comment: Sorry, I forgot to say thanks for your reply! I'd overlooked exactly what you said, tis all fixed now. :)
Answer: The problem seems to be in your view storeBloodData,at this point.
bd = BloodData  (respondent=cd['user'],

The form has no field named 'user'.You may replace it with a relevant field present declared in the form.
Also, it is better to use DICT.get(key)when you are not sure if the dict contains that particular key or not. This way you'll simply be returned None when the key is absent and you'll be able to dodge KeyError.
Comment: Sorry, I forgot to log in and say thank you! That worked indeed!

Getting KeyError in my django code


Is it ok just to play the Melody instead of the main grand Staff?

Question: As A total novice I'm attempting to play the look of love by Bacharach. I have the music in front of me and I notice a Treble Clef above the Grand Staff.
I quickly Google this and find it is the melody and the part the singer will use. I notice its's a series of single notes.
I then look at the Grand Staff and see that it is full of chords wit the odd single note.

Going through this top Clef I quickly can make it the notes and recognize the song quite easily. Why does the main body seem different to it?
I notice in the time signature that there are chords and slurs what are they telling me?
Is it ok for me just to learn to play the top clef as I haven't learned any chords yet or should I be trying to attempt the main body and leave it till I've learned some chords?
Answer: "Is it ok" questions make little sense if you don't specify an objective you want or need to meet.
It won't do in an entrance exam.  You are not likely to get standing ovations for it from an audience, either.  If you want to play the melody to a music recognition system, it might actually be the better option compared to the full score.
If you want to prompt a singing pupil for their line, it might make sense to just do the melody line in the right hand at first, and once they got it, the full score, possibly ultimately even omitting the melody line that the singer is supposed to provide themselves.
Answer: One question at a time, please!

Of course the top line (treble clef usually) will only have one note at a time - it's difficult to sing more! So this line is, as you say, the melody line, which portrays exactly what the singer is expected to sing. You can merely play that line of music on an instrument, and it will sound like the tune - because it is the tune (albeit at a different pitch on some instruments, but that's a different story for another time).

Usually, the lower two lines contain all the accompaniment needed to sing/play over. I say usually, as sometimes the melody itslef is still played in that middle line - although if a vocalist is singing, s/he won't want that same melody bashed out - but usually, all the harmonies, bass line, fill-ins etc. are included.
That's it for no. 1. Please post a screenshot to explain no.2. And no.3? Yes, certainly. It'll sound rather bare, but that's what it is - only part of the jigsaw.
Comment: There's no time sig., and no slurs. The lines are ties from the previous bar.
Comment: Number 2 I've realised this actually isn't the signature but a chord? can someone tell me what the dots are?
Answer:
It would be rather boring if the piano just copied exactly the tune that the singer is singing.  So it may have some more complex features added to the melody.
There isn't a time signature there.  Presumably that was on the first line.  It's got a key signature (F major or D minor), and some ties, presumably to the previous line as Tim says.
As a beginner, it's very common to start on just the treble clef.  Once you are happy with that, try the bass clef.  Then finally put the two together.

PS. The dots tell you that each dotted note is one-and-a-half times as long as normal.
Comment: D minor........


Jquery variable to php variable in laravel

Question: if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            $.ajax({
                type: "POST",
                url: "/gethamsters",
                data: {
                    x: position.coords.latitude,
                    y: position.coords.longitude
                },
                success: function (data) {
                    console.log(data);
                    hamsters = data;
                }
            });
        });
    }
    </script>
    @foreach ($hamsters as $hamster)

{{ HTML::image($hamster->foto, $hamster->titel, array( 'width' => 200, 'height' => 200 )) }}

<?php echo substr($hamster->titel, 0, 20); ?>

<?php echo substr($hamster->beschrijving, 0, 50); ?>

<?php echo 'id . ' class="btn btn-primary" role="button">Meer
info
 ';?>

    @endforeach

As you can see I got data from my jquery result and I want it to pass it into the $hamsters variable in my php code. How can I do that?
Comment: you can't. php is executed on the server, js in your browser.
Answer: Since we need to clearify what is happening where lets step back back to the basics here:

the Client requests GET /hamsters
the Server creates and sends response.
the Client receives response and parses page and runs any javascript on (or linked by) the document  - and can request additional resources with AJAX.
the Client POSTs /gethamsters with x, y coordinates via AJAX.
the Server processes POST /gethamsters request and returns a response to client.


Error: length(cols) > 0 is not TRUE on SparkR agg function

Question: I try to group a dataframe by a certain column:
>SparkR::agg(SparkR::groupBy(df, "column_1"))

Why do I get the following error:
Error: length(cols) > 0 is not TRUE

Answer: I found out that this kind of error (see also this one) relates to the parameters provided to the function (here: agg). I missed specifying the output column:
SparkR::agg(SparkR::groupBy(df, "column_1"), "column_1")


Spawning WSGI example (practical approach to WSGI)

Question: I'm trying to understand how WSGI works. I know I could read the specs, but I'd still want to know how do I create a spawning application? A complete "hello world".
Could someone show me an example?
With everything, file naming, creating the module, running it. Every and each step. Thanks.
(NB: while spawning seems a great piece of software, it has a stupid name: I cannot find anything successfully on the web on the matter, because everything related to "spawning" also relates to "multithreading" or "IPC").
Answer: From what I can see in the documentation, Spawning just runs stock WSGI apps, which means that you just write a WSGI script and then invoke Spawning against it:
spawn helloworld.simple_app
spawn helloworld.simple_app middleware.Upperware

As always, make sure you have installed any modules it depends on, such as paste.deploy.
Comment: I did read the documentation and I did experimented around, but I can't figure out how to write it exactly. Please improve your answer.
Comment: Save the first snippet under "An example WSGI application" as helloworld.py, the second snippet as middleware.py, and run the above commands.
Comment: The things I've tried give me: "ImportError: No module named paste.deploy", including that example.
Comment: There's no "paste.deploy" on pypi. I did install paste with easy_install and now it only says: "ImportError: No module named deploy", in an endless loop, like it did earlier with "paste.deploy".
Comment: I've fixed it by looking on the GIT repository of spawning, last log says it depends on "pastedeploy". Please add this to your response as well as the second comment, so I can accept your answer. Thanks!


google charts grafico

Question: Estou a chegar um json onde guardo os seguintes campos, mas o gráfico gera-me cores iguais e não devia
$table = array()
$rows = array();
$table['cols'] = array(
    array('label' => 'Nome', 'type' => 'string'),
    array('label' => 'valor', 'type' => 'number'),
   );
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
    $temp = array();
    $temp[] = array('v' => (string) $row['Nome']);
    $temp[] = array('v' => (float) $row['valor']);
    $rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;

// Carregue o API Visualization e o pacote piechart.
google.load('visualization', '1', {'packages': ['corechart']});

// Defina um callback a ser executado quando o API de visualização do Google é carregado.
google.setOnLoadCallback(drawChart);

function drawChart() {
    var jsonData = $.ajax({
        url: "getdados.php",
        dataType: "json",
        async: false
    }).responseText;

    // Coloque aqui as configurações do gráfico, acesse a documentação para mais opções
    var options = {'title': 'valores',
        'width': 1000,
        'height': 680,

        visibleInLegend: true,
        is3D: true,
    };

    // Create our data table out of JSON data loaded from server.

    var wrapper = new google.visualization.ChartWrapper({
        chartType: 'ColumnChart',
        dataTable: jsonData,
        options: options,
        containerId: 'chart_div'
    });
    wrapper.draw();

    var formatter = new google.visualization.NumberFormat(
            {prefix: '€ ', negativeColor: 'red', negativeParens: false});

    formatter.format(wrapper, 1);
    //Desenha o gráfico

}

Answer: Opa, beleza?
Cara, pelo que vi tu só precisa incluir um array de cores no teu objeto "options":
var options = {'title': 'valores',
         width: 1000,
         height: 680,
         colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'],
         visibleInLegend: true,
         is3D: true,
    };

Comment: fica a vermelho pois a forma esta como estou agrupar os dados. tenho de adaptar o meu codigo para ficar assim .http://www.webcodefree.com.br/blog/?s=Google+Chart+API
Comment: Passe o JSON que o getdados.php retorna por favor.
Comment: aqui esta {"data ":[{"ref":"ACD PESS","valor":"2.9300"},{"ref":"ACD TRAB","valor":"222.9900"},{"ref":"AUTO","valor":"1460.1000"},{"ref":"DIVERSOS","valor":"125.6800"},{"ref":"MR HABITA\u00c7AO","valor":"68.2300"},{"ref":"MR INDUST\/COMER","valor":"210.3500"},{"ref":"MULTI","valor":"16.4300"},{"ref":"PROT JURIDICA","valor":"5.4900"}]}

google charts grafico


JPQL / Criteria API Order By MAX OneToMany association

Question: I have the following data model: Customer with OneToMany relationship to Order.
@Entity
public class Customer{
    ...

    private Long id;

    @OneToMany
    private Collection<Order> orders;

    ...
}

@Entity
public class Order{
    ...
    private Long id;

    private Date orderDate;

    @ManyToOne
    private Customer customer;

    ...
}

I want to list top 10 Customers based on latest orderDate. So, a customer who has placed an order on the most recent date should appear on top of the list and so on.
Is it possible to do this using a single JPQL or Criteria API?
Comment: Just to mention: I ended up with using JPA's native SQL approach to solve this problem. Not sure if that's best approach however given the situation it's definitely a viable one.
Answer: In HQL:
Query query = session.createQuery("select Customer c JOIN c.orders order ORDER BY order.orderDate DESC")
query.setMaxResults(10);

And some suggestions about what you write and your code:

Avoid EAGER. Every *ToOne relationship in JPA do an EAGER fetching. Change the fetchType to LAZY if is this possible.
Native query only in the last case. In specific cases they are very useful. But, to do a simple query, you you will gain limitations if you want to work with more than one database at once (common scenario for integration tests). For example, to make this simple query that limits the amount of information, each database uses a different way to accomplish this (limit, rownum, top, etc.). Using HQL / Criteria, you do not have to worry about this.


After run sudo and/or su or su - command, the command prompt not loaded, however the switch user is successful

Question: I saw a maybe similar thread but not sure there the issue is the same:
su command not responding?
I have an Ubuntu 20.04 LTS baremetal server.
After run sudo and/or su or su - command, the command prompt not loaded, not responding:
<code>user@server:~$ sudo su -
<here hang, no command prompt>
</code>
However the switch user is successful, because when I press ctrl+c I get back the root shell, BUT no aliases loaded at all.
If I do direct root login to the server, I get back the command prompt.
In the logs I don't see any weird things.
Compared to other servers in my environment also no difference.
Wonder how to troubleshoot sudo?
I've tried to comapre with sudo -V, sudo -l with other servers but I think I need to see some debug log what is happening when ran sudo and press enter.
UPDATE:
Some small update, if I run manually the .bashrc at least it loads the aliasses.
Comment: I would try `sudo 'su -' ` because `-` could be interpreted as an argument
Comment: In addition to the above comment from myself, have you tried `su -l` since it's just an alias, for `-` or `--login`, out of the [man page](https://man7.org/linux/man-pages/man1/su.1.html)
Comment: su -l not doing anything either, the quotes gave me back this:
sudo: su -: command not found
Answer: Seems like in my environment the history suppose to keep the IP and machine ID of the remote host, but when I do local shell, it cannot lookup for both of them so it was just hang there.


I have done a Hayes Mediation analysis with 2 mediators. My indirect effect is very small but significant. How do I interpret this?

Question: I looked at the Effect of ADHD on Global Seasonality Score (GSS), mediated by both Sleep onset time on Free days and Sleep duration on Free days (N= 1738).
The indirect effect of ADHD on seasonality through mediator Sleep onset time (free days) = c, c =0.003 (0.001 - 0.007)
Effect of second mediator sleep duration (free days) on GSS was not significant.
c =0.000 (-0.003 - 0.002) Sleep duration (free days)
My question is, even though effect of ADHD on seasonality through mediator Sleep onset time (free days) is very small, it is significant. c =0.003 (0.001 - 0.007) .
How do I interpret this? What can I say about the effect size of this mediator?
Answer: The value of the unstandardized indirect effect $I_u$ depends on the scales of the predictor (ADHD) and the dependent variable (GSS). It is hard to tell whether 0.003 is large or small. It is better to calculate the standardized indirect effect $I_s$ (e.g., Cheung, 2009). Specificity, $I_s = I_u\frac{s_x}{s_y}$, where $s_x$ and $s_y$ are the standard deviations of $x$ and $y$, respectively.
If the standardized indirect effect is reasonably large, you may interpret it as with an indirect effect. If the standardized indirect effect is small, you may conclude that the indirect effect is trial even though it is statistical significant.
Reference
Cheung, M. W.-L. (2009). Comparison of methods for constructing confidence intervals of standardized indirect effects. Behavior Research Methods, 41(2), 425–438. http://doi.org/10.3758/BRM.41.2.425


Qual a relação entre o ajax do Primefaces e os eventos

Question: Diante de certos problemas durante meus desenvolvimentos me surgiu a seguinte dúvida por exemplo.
Quando utilizo a tag ajax no Primefaces, tem a propriedade event onde passamos eventos, então me surgiu um certo questionamento.
Certa vez precisei dar um jeito de ao clicar em checkbox selecionar todos, utilizei o evento click e a função me retornava um evento via parâmetro desta função.
Agora trabalhando com datatable com propriedade de editar os dados nela própria, eu utilizei eventos do tipo rowEditInit e rowEditCancel, pois o tabela criada contem um botão para editar os dados e outro para deletar, e logico que pensei, se a pessoa esta editando, seria bom bloquear o botão excluir, claro que isso vai de pensamento para pensamento e isso não esta me discussão.
E ai tentei usar a passagem de parâmetro nesta função de habilitar e desabilitar o botão mas não encontrava o evento, então me surgiu a duvida, estes eventos são do Jquery, são do Primefaces?
Onde estão documentados? Vi no manual o rowEdit, rowEditInit e rowEditCancel mas não tem quais os parâmetros a serem trabalhados.
Tenho esta dúvida e também uma forma de deixa para demais colegas de fórum conhecerem pois acho que isso pode ajudar.
Answer: Sua pergunta é muito pertinente, pois o primefaces é um framework de componentes que ao ser renderizado pelo JSF resulta em html, js e jquery no browser do cliente.
Portanto na prática os eventos podem ser do componente padrão html, do JQuery ou até mesmo adicionados pelo próprio primefaces.
Você pode usar qualquer um desses eventos junto a tag ajax, porém é sempre uma boa prática utilizar apenas aqueles que estão listados na documentação dos componentes.
No caso dos eventos rowEdit, rowEditInit, rowEditCancel, eles são Ajax Behavior Events fornecidos pelo primefaces, o melhor local para encontrar a lista de eventos, parametros e métodos da Client Side API é no user guide oficial do primefaces, nesse endereço existem todas as versões: http://www.primefaces.org/documentation.html
Os eventos citados recebem como parametro de listner a classe: org.primefaces.event.RowEditEvent
Comment: Obrigado pela resposta, eu percebi algo neste sentido, mas devido a falta de experiencia procurei opinião dos colegas do SO.


SHA1 bit-oriented test vector gives wrong digest under openssl

Question: So I came accross this list of test vectors to test the validity of a SHA1 implementation (which you can find at the bottom of http://csrc.nist.gov/groups/STM/cavp/secure-hashing.html)
The majority of the test vectors called "short" (because their size is less than the block size), pass. However, for all the long test vectors, openssl outputs a digest that is different from the one expected.
Example :
Msg = d372b4bf97daa3be77e0d78c123c7bb39dde10c82824c83f2250308320391247da419a167686b7320a5dc49b5cfc686eec76bb7034edaaeb2e029cb91791569e739c1bdb518418ffd07f0001e0

Expected MD = c60a02fffa45deccb075e386be3aa9313c2df4f2

Openssl output = 77 2d ff f3 54 31 2c df 93 e1 94 2f 10 91 f7 f8 78 61 91 c1

N.B : The test vectors are made for bit-oriented implementation. What I understand is that this kind of implementation can calculate the digest of messages that have a size which is not necessarily a byte multiple.
Anyone have a clue why this is happening?
Answer: You answered your own question, you're trying to verify the bit mode, but OpenSSL only supports byte mode.  Or, at least, they've only ever been issued a FIPS CAVP certificate for byte mode: http://csrc.nist.gov/groups/STM/cavp/documents/shs/shaval.html#2465
SHA-1    (BYTE-only)
SHA-224  (BYTE-only)
SHA-256  (BYTE-only)
SHA-384  (BYTE-only)
SHA-512  (BYTE-only)

If you need a library which has been certified as providing correct answers for BIT values, search that list for "SHA-1 (BIT)".  There are a couple, no idea how many of them are consumable API, though.
Or, byte align your data.
Answer: So in response to your comments, I believe the crucial difference in output when you are using the NIST test vectors is that the specified length is very important when doing bit-oriented output. With byte-oriented output, if the NIST message was 98, you can feel confident that the correct input to your SHA algorithm is the bytes b10011000. However if it were bit oriented, it could have len = 6 for example, in which case the correct input to your algorithm is b100110. Or len = 7 with b1001100.


Check users country

Question: I'm trying to figure out how I can check the users country, and then execute specific code based on the result of the users country that I define. Any ideas?
Comment: Are you assuming internet access on the part of the user? In that case, you could do an IP lookup and try to match the region
Comment: Does your code run as a program *on* the users computer?
Comment: Yes, I've compiled it with Py2Exe.
Comment: Yes, the user will be required to have internet access. I'm unsure about how I would go about that.
Comment: You can make a popup that asks the user to select their country from a fixed list.  Or have them input their phone number and parse out the calling code.
Comment: Good idea djechlin. However I'd rather no user-input be needed from the user for this task.
Answer: You could do something like this:
Get user's external ip using a service:
f = urllib.urlopen("http://www.canyouseeme.org/")
html_doc = f.read()
f.close()
m = re.search('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)',html_doc)
ip = m.group(0)

then use http://pypi.python.org/pypi/pygeoip/ to figure out a users country
geoip = pygeoip.GeoIP("GeoIPCountry.dat", pygeoip.STANDARD)
result = geoip.record_by_addr(ip)

Comment: Thanks Francis, I'll look into it in more detail. However I have a question. Wouldn't it be more simple to use a domain such as http://whatismycountry.com/ and then find the string on the site and match it with a predefined string.
Comment: IP's are pretty easy to match w/ regular expressions. country names would be much harder to parse out of the other text on the page.
Answer: Since you're only asking for ideas, you could check the language and/or timezone environment variables. The problem is that neither of these is guaranteed to be accurate - it wouldn't be surprising to find a computer in the Philippines set for en_US in America/New York.
Comment: Yes, I've thought about this. It would seem more realistic to match the IP with the region as InspectorG4dget stated. I'm just unsure about how I can go about doing that.
Comment: Then you're most likely looking for the GeoIP module at this point. Unfortunately, I can't find a good online doc for it right now, though I can find plenty of "hey, look at the cool thing I did!" blog posts extolling it's virtues...
Comment: Thanks, John. I'll take a look at the module.

Check users country


Nested tree list with a directive in angular

Question: I'm having trouble with a nested list Directive using Angular.  Each time I try to run my code the browser crashes when I call the directive recursively.
I'd like to output a new list item if the children property in the data has items in it.
Here's a fiddle to my code, I removed the directives call to itself so that it does not crash the browser.  http://jsfiddle.net/8p3bf4ec/
JS:
var jsonData = {
    "title": "Home",
    "author": "Mary",
    "children": [
        {
            "title": "Clothing",
            "author": "Robert",
            "children": [
                {
                    "title": "Shirts",
                    "author": "Bill",
                    "children": []
                }
            ]
        },
        {
            "name": "Electronics",
            "author": "William",
            "children": []
        }
    ]
};

angular.module('myApp', []);

angular.module('myApp').directive('itemList', function() {
    return {
        scope: true,
        templateUrl: 'itemListTemplate.html',
        controller: function($scope) {
            $scope.nodes = jsonData;
            console.log($scope.nodes);
        }
    };
});

Template:

    <item-list></item-list>

Comment: Usng `ng-repeat="node in nodes"`, the root of your `jsonData` should probably be an array -- `var jsonData = [ { ... } ];` Otherwise, it's iterating the root object's values -- `"Home"`, `"Mary"`, etc.
Comment: render your directive element on some condition `` , as your calling it inside your template recursively..and directive is compiling infinite times..that's why browser is getting hanged..
Comment: @JonathanLonowski I'd like it to be an array at the root but it's not and unfortunately it's not something I have control over.
Comment: @Mdd The directive could itself wrap the data in an Array -- `$scope.nodes = angular.isArray(jsonData) ? jsonData : [ jsonData ];`
Comment: @JonathanLonowski Thanks, I had not realize that.  I'm just starting out with Angular and directives are still pretty new to me but it seems like a good way to re-make a reuseable list.
Answer: It is because you infinitely iterate through jsonData instead of each node's children. I guess you should not use directive here at all because there is not much logic and it adds unnecessary complexity. Just use ng-include instead of directive. Something like this:


Connect HTML form to Database

Question: I need to connect the form to a database that I already have, but it is not connecting and I can't seem to find the problem. I the error that is showing up mostly is the "mysqli" error but I can't find the reason behind it
--order.php--
<!DOCTYPE html>

        <title>Checkout</title>
        <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
        <link rel="stylesheet" href="styles.css"/>

Bill To

                    <form action="order.php" method="POST">
                    <input type="text" id="FirstName" name="FirstName" placeholder="First Name" style="width:350px; background-color:pink;">

                    <input type="text" id="Surname" name="Surname" placeholder="Last Name" style="width:350px;background-color:pink;">

                    <input type="text" id="HouseName" name="HouseName" placeholder="House Name" style="width:350px;background-color:pink;">

                    <input type="text" id="StreetName" name="StreetName" placeholder="Street Name" style="width:350px;background-color:pink;">

                    <input type="text" id="Locality" name="Locality" placeholder="Locality" style="width:350px;background-color:pink;">

                    <input type="text" id="MobileNumber" name="MobileNumber" placeholder="Mobile Number" style="width:350px;background-color:pink;">

                    <input type="text" id="Email" name="Email" placeholder="Email Address" style="width:350px;background-color:pink;">
                    <input type="submit" name="submit" value="Register"/>
                    </form>

                    <?php

                        if(isset($_POST['submit']))
                        {
                        $FirstName=$_POST['FirstName'];
                        $Surname=$_POST['Surname'];

                        $result="INSERT INTO users (FirstName,Surname) VALUES ('$FirstName','$Surname')";
                         mysqli_query($conn,$result);
                        }
                    ?>

--connect.php-- This is the code that is in connect.php
<?php
    $user = 'root';
    $pass ='';
    $host = 'localhost';
    $db = 'webassignment';

    $conn = new mysqli($host, $user, $pass, $db);

  if ($conn -> connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }
?>

Comment: Did you include `connect.php`? You are open to SQL injections. Please add what the `the "mysqli" error` is.
Comment: Could you also tell what is the error coming ?
Answer: I've found the problem in the order.php the code is
  <?php
                        $conn = new mysqli("localhost","root",'','webassignment',3306);

                       if (!$conn)
                        {
                           die('Could not connect: ' . mysql_error());
                        }

                        if(isset($_POST['submit']))
                        {
                        $FirstName=$_POST['FirstName'];
                        $Surname=$_POST['Surname'];
                        $HouseName=$_POST['HouseName'];
                        $StreetName=$_POST['StreetName'];
                        $Locality=$_POST['Locality'];
                        $MobileNumber=$_POST['MobileNumber'];
                        $Email=$_POST['Email'];
                        }

                        $result="INSERT INTO users (FirstName,Surname,HouseName,StreetName,Locality,MobileNumber,Email) VALUES ('$FirstName','$Surname', '$HouseName','$StreetName','$Locality','$MobileNumber','$Email')";

                        if($conn->query($result))
                        {
                            //echo "worked";
                        }else{
                            //echo "Error: " .$result ."
". $conn->error;
                        }

                    ?>

Answer: First, run only the connect.php file to check if the connection can be established successfully.
if ($conn -> connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }
else
    echo 'Success';

In order.php I can't find anywhere that you have called the connect.php file. So, the $conn variable is of no use there.
Call it using include or require_once function.
Answer: edit code in connect.php to be like this
$conn = mysqli_connect($host, $user, $pass, $db);

if(mysql_connect_errno()){
echo "can't connect" . mysqli_connect_error();
}

and in order.php put this code under <?php
require_once 'connect.php';

Connect HTML form to Database


Endomorphism ring of Prüfer group

Question: It is claimed in Wikipedia that the ring of endomorphisms of the Prüfer $p$-group is given by the p-adic integers, but I want to know how to prove it
So far I have if $\phi \in End_{\mathbb{Z}}(\mathbb{Z}_{p^\infty}, \mathbb{Z}_{p^\infty})$ then $\phi (\langle \frac{1}{p^k} \rangle ) = \langle \frac{1}{p^l} \rangle $ because the image of a submodule is a submodule, then $l \leq k$ because the number of elements of $\phi (\langle \frac{1}{p^k} \rangle )$ doesn't exceed $p^k$.
So ,if we consider $\phi ( \frac{1}{p}  )$ is equal to $0$
or $\frac{a}{p}$ with $(a,p) =1$ .  If it is $\frac{a}{p}$, $\phi $ is determined because   $\phi ( \frac{1}{p^k }  )= \frac{b}{p^k}$ with $a \equiv b$ mod $p$, otherwise we do the same with $\phi ( \frac{1}{p^2 }) $ , it cannot be $\frac{a}{p^2}$ because it contradicts that $\phi ( \frac{1}{p}) =0 $ so is $0$ or $\frac{a}{p}$ and we continue the process.
With this I think that all the endomorphisms are determined but that's all.
Thank you in advance.
Answer: Since this hasn't been answered so far (and if you hadn't done it already on your own), I am gonna try to delineate a much more general result towards this direction.
The key word you're looking is called Matlis' Theorem.
I presume you're familiar with some categorical notions like inverse (projective) limit, direct (inductive) limit (if not is a good chance to try :)). In every book of modern abstract algebra you can find the aforementioned explicitly written with many examples. For the moment you can think of them as a kind of generalized intersections and unions respectively, where simultaneously we preserve the structure of the underlying material (modules, groups, rings...). In fact those ideas behind the limits generalize the ideas of products and coproducts, pullbacks and pushouts, equalizers and coequalizers and other related notions. For the moment we are working out in a category of modules, so keep in mind that the above limits do exist indeed (that is, categories of modules are complete and co-complete, i.e. bicomplete).
We are seeking of an isomorphism of rings

$$ End_{\mathbb{Z}}(\mathbb{Z}_{p^{\infty}}) \cong \hat{\mathbb{Z}}_p.$$

Where the right-hand side denotes the $p$-adic integers, or maybe better in our case the inverse limit of the inverse system $\{\mathbb{Z}/{(p)}^n,\psi_{m,n}\}_{n \in \mathbb{N}}$, which is called the $p$-adic completion of $\mathbb{Z}$. The definitions and theory behind the aforementioned can be found in almost any book of abstract algebra nowadays as well. To this end, we're gonna need some tools and comments, which I introduce below, and a good reference to find their proofs is Rotman's book "An Introduction to Homological Algebra".

Proposition:
If $\{M_{i},\psi_{i,j}\}_{i \in \mathbb{N}}$ is an inverse system of left $R$-modules, then there is a natural isomorphism
$$ Hom_R(A, \varprojlim M_i) \cong \varprojlim Hom_R(A, M_i),$$
for every left $R$-module $A$.

Similarly one can define the dual notion of inverse systems, and deal with direct systems instead and an analogous proposition exists.

Proposition:
If $\{M_{i},\psi_{i,j}\}_{i \in \mathbb{N}}$ is a direct system of left
$R$-modules, then there is an isomorphism
$$ Hom_R(\varinjlim M_i, A) \cong \varprojlim Hom_R(M_i, A).$$
for every left $R$-module $A$.

Now think of the case where we have as our material the family of cyclic groups $\{ \mathbb{Z}/(p)^n \}_{n \in \mathbb{N}}$, for some fixed $p$ prime. But once we look on it with the homomorphisms
$$ \psi_{m,n}: \mathbb{Z}/(p)^m \rightarrow \mathbb{Z}/(p)^n , \,\, m \geq n, $$
$$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, a+(p)^m \mapsto a+(p)^n,$$
which give the above inverse system  $\{\mathbb{Z}/{(p)}^n,\psi_{m,n}\}_{n \in \mathbb{N}}$, with the corresponding inverse limit being $p$-adic integers $\hat{\mathbb{Z}}_{p}$ as I said earlier, and by just think the homomorphisms $$\gamma_{n+1,n} : \mathbb{Z}/p^n\mathbb{Z} \rightarrow \mathbb{Z}/p^{n+1}\mathbb{Z},$$
induced by multiplication by $p$, we form the direct system $\{\mathbb{Z}/{(p)}^n,\gamma_{m,n}\}_{n \in \mathbb{N}}$ whose direct limit is the Prüfer group, that is $\varinjlim \mathbb{Z}/{(p)^n} \cong \mathbb{Z}_{p^{\infty}}$.
Now, after the prologue, Matlis proved himself that there is the following isomorphism (proof can be found in Lam's book Lectures on Modules and Rings)

Theorem:
Given a local commutative Noetherian ring $(R, \mathfrak{m})$, the endomorphism ring $End_R(E)$, is isomorphic to $\hat{R}$, the $\mathfrak{m}$-adic completion of $R$.

Where by $E$ we denote the injective hull of the quotient $R/ \mathfrak{m}$, as  $R$-module and usually is referred as the standard module.
Let's see now, how does this apply to our case. Firstly, we have the following fact

The Prüfer group $\mathbb{Z}_{p^{\infty}}$, is the injective hull of the cyclic groups $\mathbb{Z}_{p^{n}}$, for every $n \geq 1$.

The fact that is injective module (here as abelian group), follows directly, since it is direct summand of the divisible group $\mathbb{Q}/\mathbb{Z}$ (see structure theorem of divisible abelian groups), hence is itself divisible which implies injectivity since $\mathbb{Z}$ is a principal ideal domain. To see that is the smallest such an injective module we exploit its presentation
$$\mathbb{Z}_{p^{\infty}}= <a_0,a_1,a_2,...| \,\, pa_0=0, \, pa_{n+1}=a_n, \,\, n\geq 1>,$$
indeed, if $D$ is another abelian divisible group such that $\mathbb{Z}_p\subseteq D$, we can construct $x_1,x_2,\ldots\in D$ such that $px_1=\overline 1$, and $px_{n+1}=x_n$, hence it is not hard to see that the subgroup generated by $\bar 1$ and the $x_i\,'s$ is isomorphic to $\mathbb{Z}_{p^{\infty}}$.
Having all the above in mind we can replace in Matlis theorem our data. So we have
$$\,\,\,\, End_\mathbb{Z}(\mathbb{Z}_{p^{\infty}})=Hom_\mathbb{Z}(\mathbb{Z}_{p^{\infty}},\mathbb{Z}_{p^{\infty}}) \cong Hom_\mathbb{Z}( \varinjlim \mathbb{Z}/{(p)^n}, \mathbb{Z}_{p^{\infty}}) \cong \varprojlim Hom_\mathbb{Z}(\mathbb{Z}/{(p)^n},\mathbb{Z}_{p^{\infty}}) \stackrel{(*)}{\cong}  \varprojlim \mathbb{Z}/{(p)^n} \cong \hat{\mathbb{Z}}_p.$$
Note that $(*)$ is the only subtle point, since if you check Matlis' Theorem you'll see that is proven for local rings and apparenly $\mathbb{Z}$ isn't such a ring. In that case we can apply the theorem after localizing our ring over a prime ideal. In our case we just simply have the ideal $(p)$ for the fixed prime which gives the local ring $\mathbb{Z}_{(p)}$ . So the isomorphism follows.
(My answer is extended since I've no idea what you know or not, because many things are introductory if you know them already, you can just skip them.)
Cheers!
Comment: Sorry for the late reply. In the final $(\ast)$ part, can we argue like the following? Note that any abelian group morphism $f: \mathbb{Z}/(p^n) \rightarrow \mathbb{Z}/(p^\infty)$ actually has image in $\mathbb{Z}/(p^n)$, hence $$ \mathrm{Hom}_{\mathbb{Z}} (\mathbb{Z}/(p^n),\mathbb{Z}/(p^\infty)) = \mathrm{Hom}_{\mathbb{Z}} (\mathbb{Z}/(p^n),\mathbb{Z}/(p^n)) = \mathbb{Z}/(p^n).$$ And then the result follows.
Comment: This is a great answer, +1.

Endomorphism ring of Prüfer group


iterate through an array of vector in c++

Question: I am trying to iterate through my vector array, but I cannot seem to get it to work, my error is at the second for loop and the error message is the follow:

expected primary expression before 'double'

I have looked through on how to iterate a regular vector, but how do I iterator a vector array?
I followed this structure:
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  for (int i=1; i<=5; i++) myvector.push_back(i);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

I can't seem to get my vector array version to work.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main(int arc, char *argv[])
{
   vector<double> vector[7];

   double num[7];
   ifstream infile("data.txt");
   string temp;

   for(int i = 0; i <= 6; i++)
   {
      infile >> temp;
      cout << temp << ' ';
   }
   cout << endl;

   while(infile >> num[0] >> num[1] >> num[2] >> num[3] >> num[4] >> num[5] >> num[6])
   {
      for(int i = 0; i <= 6; i++)
      {
         vector[i].push_back(num[i]);
      }
   }
   cout << endl;

   for(int i = 0; i <= 6; i++)
   {
      // error on this line
      // not sure what is wrong before vector<double>:: iterator it = vector[i].begin()
      for(vector<double>::iterator it = vector[i].begin(); it != vector[i].end(); ++it)
      {
         cout << ' ' << *it;
      }
   }
   return 0;
}

Comment: Calling a vector variable "vector" is *not* a good idea. Give it a name that isn't taken, and the problem will go away.
Comment: `vector my_vector[7];` Try to avoid `using namespace std` to prevent this from happening.
Comment: Also for each vector you push back only one number, is that what you really want? i.e. 7 vectors for 7 doubles.
Comment: @Beta, after changing the name "vector" to "v" it did the trick. Thanks. I did not even consider that, it's like doing int int = 5.
Comment: c++11 `for(double d:v)//stuff;` ftw
Answer: On this line of code
for(vector<double>::iterator it = vector[i].begin(); it != vector[i].end(); ++it)

vector is not a type, it's a variable.  Names in local scopes hide names in global scopes.
You could instead write
for(::std::vector<double>::iterator it = vector[i].begin(); it != vector[i].end(); ++it)

or
for(auto it = vector[i].begin(); it != vector[i].end(); ++it)

but a better solution is to not use the same name for multiple different things.
Answer: #include <iostream>
#include <fstream>
#include <vector>

using std::ifstream;
using std::vector;
using std::cout;

int main(int arc, char *argv[])
{
   const size_t data_size = 7;
   ifstream infile("data.txt");
   vector<double> input;
   double num;
   while ((infile >> num) && (input.size() <= data_size))
   {
      input.push_back(num);
   }
   for (vector<double>::iterator it = input.begin(); it != input.end(); ++it)
   {
      cout << ' ' << *it;
   }
   return 0;
}

Use minimal variables and get the job one. Also don't name your variables after standard library functions, classes, structs, etc. and avoid using directives like using namespace std; and prefer using declarations.
Comment: *"don't name your variables after standard library functions, classes, structs"* - Why? Given that the standard library uses a whole lot of names (and many of them being very general ones), this advice is extremely counter-productive. What do think namespaces are for?
Comment: @ChristianRau: I understand that namespaces effectively hide these names, but readability is hampered when uses _exactly_ the same name. This, perhaps, is the reason we see custom written vectors to have names like EAVector, etc. with a prefix to differentiate from standard containers. When this is the case for even classes, variables of the same name as its class is even more confusing when 1000s of loc.
Answer: You can simply traverse a vector of array like this
for (int i=0; i<myvector.size(); i++)
    {
        for (int j=0; j<myvector.size(); j++)
            {
                cout<<myvector[i][j]<<endl;
            }
    }


Is it possible to control CPU cores?

Question: If I own quad core processor, can I "isolate" or totally control 1 core from other cores?
The fourth core job is to serve only and only for allocated thread and nothing else.
What I want is to do thread that job is get to get numbers from memory, from always same physical adresses and calculate them how I want and put them back to the same place. (I will disable virtual memory)
Thank you for your answers.
Comment: I'll use the OS which is best choice for this job
Comment: taskset lets you specify which core.  Running without VM is hard.  What OS will you use?
Comment: No matter actually,  I have OS X, windows, freeBSD and linux.
Answer: On linux, you can use the sched_setaffinity function to do this.  Set the affinity for the special thread to 8 (i.e. 0b1000) and the other threads to 7 (i.e. 0b0111).
You're probably SOL if you really want to switch off virtual memory or anything like that.  However, you may be able to write a kernel driver whose job is to expose the relevant section of physical memory to your user program.
Comment: Will this method ensure that other part of OS will not be able to use  that core?
Comment: @user3521129 No it won't. If you want absolutely nothing to touch that core, I believe you need to write your own OS. There might to disable the core in the BIOS and expose it to a driver. But that's out of my league.
Comment: @user3521129: I don't know what you're doing, but I probably wouldn't worry about that at this stage.  If it turns out to be a problem, though, you might try horsing around with kernel settings regarding which processors handle interrupts from which devices.

Is it possible to control CPU cores?