Use user's session id number to find its number in a field with multiple numbers separated by commas

Question: I have a database setup (please see the sample image below) that shows each teacher's (tutor's) class they have created along with the teacher's id. In addition there are two other fields: register_stud_ids and register_tut_ids that can have one or more numbers in their field separated by commas.
I have no problem using the code below to get the resulting web page specific to that user based on their session login number if there is only one number in either field, but when there are two or more numbers in either field, the resulting web page is not specific to that user, it just shows the else of the if then... statements I have.
So, my question is, how do I change the code below to get the user's session login number from the list of numbers in either the register_tut_ids field or the register_stud_ids field?
data table example image
if ($getrow['register_tut_ids'] == $_SESSION['ses_idno'] OR $getrow['tut_id'] == $_SESSION['ses_idno'] && $_SESSION['u_type'] == 't')
else if ($getrow['register_stud_ids'] == $_SESSION['ses_idno'] && $_SESSION['u_type'] =='s')
Comment: Bad database design
Comment: Masivuye, since you are a developer can you please help this non developer understand why you wrote "Bad database design" and as a developer, how can the code be change to do what I asked?
Answer: I suggest that you update your Database structure to the following:
+----------+--------+------------+
| class_id | tut_id | student_id |
+----------+--------+------------+
|        1 |      2 |          1 |
|        1 |      2 |          2 |
|        1 |      2 |          3 |
|        2 |      2 |          4 |
+----------+--------+------------+

See how a specific class or tutorial can have multiple students?
This makes querying for data easy. Simply use a WHERE clause in your SELECT statement with the conditions you want to be fulfilled. If you get back a result then you have a matching record otherwise just do the else part.
Comment: Lucky, I see what you are saying, but wouldn't that increase the number of rows and thus over time cause a slow down?
Comment: Dont even worry about that. As they say premature optimisation is an evil (i even wont call what you are doing  an optimisation) Just make sure that you have your indexes defined correctly and you will be pleasantly surprised by how much computers in general can handle. If your application becomes popular then you will be able to scale your mysql deployment easily. The way you are doing things right now will cause more trouble in any case.
Comment: Thank you Lucky. I will definitely follow your advise.


Long file path returning 404 for "hello.htm"

Question: I have a long file path that works on my server, but a simliar path returns a 404 error when it is on my clients (IIS6) server (http://ddmat.com/).
Here's the functioning file path on my server:
http://www.forgefx.com/projects/ddmat/install/Application Files/McCurdys_1_0_0_0/Content/FBX/CCAE1B33/Roof-sectionB-02.fbm/hello.htm
My guesses:

Maybe the file path is too long?
Maybe the ".fbm" in the directory path is invalid?

Sorry for the vauge problem description.  Please let me know what additional info I can provide that'd be helpful.
Update:
The problem happens even in short paths, with no spaces:
http://www.myserver/test.folder/hell.htm
Thanks,
Adam
Answer: I'm interested in finding out the cause of this also. So I did some research online. I found this article. I think it might help answering this issue.
http://support.microsoft.com/kb/315122
Answer: The problem is the space in "Application Files". You should URL-encode the link (substitute the space with %20 in this case):
http://www.forgefx.com/projects/ddmat/install/Application%20Files/McCurdys_1_0_0_0/Content/FBX/CCAE1B33/Roof-sectionB-02.fbm/hello.htm
Update:
Two things:

Perhaps your client forgot to install/enable static content on IIS. It's a feature that must be explicitly enabled on the server. See this blog post: Don't forget to check "Static content service" in IIS7 installation (it's Vista related: here the Windows Server 2008 procedure: http://www.trainsignaltraining.com/windows-server-2008-iis7 )

It would be very strange, because it's not the default for .htm, but maybe your client's IIS/website configuration doesn't allow the htm mimetype. See this support article: IIS 6.0 does not serve unknown MIME types


Can i use a centralized external config file for c#?

Question: I found an article on using external config files here.  While I was able to extract my config settings, I was unable to put them in a central location.
When i tried to do something like this:
<code>  <connectionStrings configSource="C:/dev/Configs/ConnectionStrings.config" />
</code>
It causes a type initializer exception.  If i put the file in a folder under the bin directory, it's ok.  Problem is, I want to keep the config files central to all apps so i can reuse it in a lot of places.
Is it just not doable?
Answer: I ended up using Symbolic Links.  I created a subfolder under each app that symlinked back to the master config folder.  All apps share the same Connection Strings now.


Favicon não funciona no IE

Question: Boa tarde a todos.Estou fazendo uns testes de layout HTML. Entrei no IE para ver como estava e reparei que o código <link rel="shortcut icon" href="img/body/icon-amova.png"/> não estava funcionando no IE 10.
Pesquisei em uns artigos:
https://tableless.com.br/favicons/
https://forum.imasters.com.br/topic/360525-resolvido%C2%A0favicon-ico-n%C3%A3o-funciona/
E alterei meu código para
 <link rel="icon" href="img/body/icon-amova.ico" type="image/x-icon"/>

Repare que alterei a extensão do arquivo e ele funciona perfeitamente nos outros navegadores, mas mesmo asssim, não funciona no IE 10.
Depois encontrei uma resposta aqui no SO
Favicon não aparece
E alterei meu código para:
<link rel="icon" href="http://localhost/amova/img/body/icon-amova.ico" type="image/x-icon" sizes="32x32"/>

Repare que usei o caminho completo, coloquei a tag sizes, limpei informações de cache. Mas nada mudou.
Alguma outra sugestão?
Comment: Ja verificou se o caminho esta correto? Limpa o cache dos outros navegadores e vê se continua aparecendo
Comment: @LennonS.Bueno o caminho está correto pois nos outros navegadores está normal. Limpei o cache de todos os navegadores mas no IE não aparece.
Comment: Estou usando o xampp. Será que pode ser isso? Só no IE que não funciona.
Comment: Você tem certeza que é realmente um arquivo .ico? só renomear não basta
Comment: @LennonS.Bueno, o arquivo estava correto eu exportei pelo corel
Answer: Coloque o seguinte código dentro da  do seu html:
<!DOCTYPE html>

       <link rel="icon" href="img/body/icon-amova.ico" type="image/x-icon" />
       <link rel="shortcut icon" href="img/body/icon-amova.ico" type="image/x-icon" />

        Conteúdo do seu site...

Sua imagem deverá ser realmente um arquivo .ico não basta apenas renomeá-lo.
Caso não funcione tente utilizar um arquivo .png no lugar do arquivo de ícone.
Comment: Funcionou... depois que coloquei os dois caminhos como você postou. Porque será que isso acontece? O IE é muito bugado.. mds
Comment: Vou testar aqui...
Comment: Eu acredito que para usar .ico você tem que usar rel="shortcut icon", mas não lembro exatamente como funciona. Depois faça alguns testes removendo apenas um link para ver se funciona.

Favicon não funciona no IE


maven dependency management from parent pom overrides ${project.version}

Question: I have a parent pom with a dependency management like this:
<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.group.id</groupId>
        <artifactId>art1</artifactId>
        <version>1.0</version>
      </dependency>
      <dependency>
        <groupId>com.group.id</groupId>
        <artifactId>art1</artifactId>
        <version>1.0</version>
      </dependency>
</dependencyManagement>

The artifacts art1 and art2 are submodules from the same module and they inherit from the parent pom where the dependency management is.
The dependencies from art1 looks like:
<dependency>
  <groupId>com.group.id</groupId>
  <artifactId>art2</artifactId>
  <version>${project.version}</version>
</dependency>

For now I tought that if the project version of art1 was 0.5 the version of art2 in the dependency of art1 would be 0.5
But it seems that the dependencyManagement override the ${project.version}
Can you tell me if I am right?
Answer: Yes, you are right. Specified versions in dependency management from parent pom will have "priority" to transitive dependencies.
This is one of the purposes of dependencies management: user can "force" somehow the versions of dependencies in a single place.
Comment: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
Comment: Can you like some documentation about this purpose? Then I can accept your answer. Thank you!
Comment: As a best practice, you should specify all your dependencies versions in parent pom, dependency management section. It will be much simpler to change a version, since you know all dependencies versions are declared in one single place.


How to find strongest path between two nodes in a directed graph in matlab or ucinet?

Question: Suppose the matrix below as a directed graph adjacency matrix with 3 nodes.
A=[.35 .076 .12;.0054 .83 .09; .31 .92 .019]

How can I find the strongest path between two specific nodes in matlab or ucinet?
I need some way to tell matlab that find every possible paths between two nodes, then sum up the weights of edges in each path and find the maximum weighted path, then show that path.
For example if we consider marix A and want to find the strongest path from node 1 to node 3, we have two possible paths: one direct path from node 1 to node 3 and one path from node 1 to node 2 and node 2 to node 3. in the first path we have A(1,3)=.12 and for second path we have A(1,2)+ A(2,3)= .076+.09=.166, so the second path is strongest path from node 1 to node 3, and we have it as 1-2-3. Is there any way to do something like this in matlab or ucinet?
Big thanks in advance
Answer: To find strongest path between two nodes in a directed graph in MATLAB, you can use Graph::longestPath in the Symbolic Math Toolbox (note that the Dijkstra algorithm to find the shortest path graphshortestpath is in the Bioinformatics Toolbox)
Comment: Note that it is necessary for the graph to be directed acyclic (http://en.wikipedia.org/wiki/Directed_acyclic_graph), otherwise there could be a path with infinite weight.


Como somar valores de um model e inserir o resultado em outro utilizando Django?

Question: Possuo esse model que tem como objetivo cadastrar os serviços disponíveis e seus respectivos valores:
class Servico(models.Model):
    nome = models.CharField('Nome do serviço', max_length=255)
    preco = models.DecimalField('Preço do serviço', decimal_places=2)
    data_cadastro = models.DateTimeField('Data de cadastro',auto_now_add=True)

    def __str__(self):
        return self.nome

Criei outro model chamado venda, onde poderá ser cadastrados vários serviços para uma única venda. Eu gostaria de inserir a soma dos preços dos serviços dentro de valor_total
class Venda(models.Model):
    FORMPAG_CHOICES = (
        ('CC', 'Cartão de Crédito'),
        ('CD', 'Cartão de Crédito'),
        ('D', 'Dinheiro'),
        ('T', 'Transferência (Entre contas/PIX)')
    )

    forma_pag = models.CharField('Forma de pagamento', max_length=2, choices=FORMPAG_CHOICES)
    cliente = models.ForeignKey(Cliente, verbose_name='Cliente', on_delete='models.PROTECT')
    servicos = models.ManyToManyField(Servico, verbose_name='Serviços prestados')
    data_cadastro = models.DateTimeField('Data da venda',auto_now_add=True)
    valor_total = # É aqui onde quero inserir o valor total da venda

Comment: Model.py cadastra no banco, o que vc qr fazer é realizado via forms.py e com javascript. Como faz um tempinho que mandou essa pergunta, atualiza a pergunta com o que vc conseguiu até agora.
Answer: Talvez criar uma property no model de Venda para sempre calcular isso pra ti. Algo tipo abaixo:
class Venda(models.Model):
  # ...

  @property
  def valor_total():
    servicos = self.servicos.all() # aplicar filtros padroes se precisar
    preco_total = 0.00
    for servico in servicos:
       preco_total += servico.preco
    return preco_total

o @property é praticamente para conseguir chamar venda.valor_total e nao precisa chamar venda.valor_total()
Espero que isso já ajude.
Comment: Só não entendi como é inserido no banco :/
Comment: Teria que inserir no valor de cada serviço. Esse metodo ai é realmente só para pegar agora para inserir teria que salvar nos preços de cada serviço, que dai quando pegar já pega certinho.


SSL error whith LetsEncrypt and Nginx

Question: I configured my Nginx server with certbot and LetsEncrypt.The OS is Ubuntu 16.04 and There was no errors in the process, But when I access it from browser it shows these errors:
In Firefox :

Secure Connection Failed
  An error occurred during a connection to hamclassy.ir. Cannot
  communicate securely with peer: no common encryption algorithm(s).
  Error code: SSL_ERROR_NO_CYPHER_OVERLAP

In Chrome :

This site can't provide a secure connection
  hamclassy.ir uses an unsupported protocol.
  ERR_SSL_VERSION_OR_CIPHER_MISMATCH

my Nginx config is :
server {
  listen 80 default_server;
  listen [::]:80 default_server ;#ipv6only=on;

  server_name hamclassy.ir;
  root /var/www/hamclassy;
  index index.html;

  location /test.html {
    alias /var/www/hamclassy/test.html;
  }

  listen [::]:443 ssl ;#ipv6only=on; # managed by Certbot
  listen 443 ssl; # managed by Certbot
  ssl_certificate     /etc/letsencrypt/live/hamclassy.ir-0002/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/hamclassy.ir-0002/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

--- Edited ---
And this is my options-ssl-nginx.conf file :
# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file.

ssl_session_cache shared:le_nginx_SSL:1m;
ssl_session_timeout 1440m;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";

-----Edited -------
There is an error when I want to connect by OpenSSL
 # openssl s_client -connect hamclassy.ir:443 -tls1_2
CONNECTED(00000003)
139650936854168:error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number:s3_pkt.c:362:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 5 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1522776319
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---

And
openssl s_client -connect hamclassy.ir:443
CONNECTED(00000003)
140618586904216:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:s23_clnt.c:769:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 305 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1522782522
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

Comment: You have restricted the server to a set of ciphers but the tls version you are using requires others. You need to post the content of `/etc/letsencrypt/options-ssl-nginx.conf` or any other file that contains config options relating to ssl
Comment: @Drifter104 Thanks for the answer, I added the .conf file
Comment: Now please try less options:  `openssl s_client -connect hamclassy.ir:443`
Comment: @kubanczyk  , result added
Comment: As Drifter104 say, the problem seems your cipher list configuration, `Cipher    : 0000` is that you get no cipher `("0000").` Try with the configuration recommended in https://cipherli.st/
Comment: @Federico I changed the config to cipherli recommendation but the problem still existes.
Answer: # host hamclassy.ir
hamclassy.ir has address 22.214.171.124

As you can see on http://22.214.171.124 your website hides behind a CloudFlare's frontend. ("Frontend" is a synonym of "reverse proxy".) You need to either disable CloudFlare or go to their user interface and configure https proxying properly.

SSL error whith LetsEncrypt and Nginx


How to solve $uu_{x_1}+u_{x_2}=1$ with characteristic method?

Question: $$uu_{x_1}+u_{x_2}=1\text{ with initial condition }u(x_1,x_1)=\frac{1}{2}x_1$$
I have problem to use following characteristic method to solve it.
Let $$x(s) = (x_1(s), x_2(s))$$$$z(s) = u(x(s))$$$$p(s) = (u_{x_1}(x(s)), u_{x_2}(x(s))$$$$F(x,z,p) = zp_1 + p_2 - 1 = 0$$
Assume, $$\frac{dx}{ds} = F_p = (z,1) $$$$\frac{dz}{ds} = F_p \cdot p = 1$$$$\frac{dp}{ds} = -F_x - F_z p = 0 - p_1(p_1,p_2) = - (p_1^2,p_1p_2)$$
Now, we can have, $$z(s) = s + c_0$$$$\dot x_1 = s + c_0 \Rightarrow x_1 = \frac{1}{2}s^2 + sc_0 + c_1$$$$\dot x_2 = 1 \Rightarrow x_2 = s + c_2$$
I'm stucked here. I don't know what to do next.
Answer: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx_2}{dt}=1$ , letting $x_2(0)=0$ , we have $x_2=t$
$\dfrac{du}{dt}=1$ , letting $u(0)=u_0$ , we have $u=t+u_0=x_2+u_0$
$\dfrac{dx_1}{dt}=u=t+u_0$ , letting $x_1(0)=f(u_0)$ , we have $x_1=\dfrac{t^2}{2}+u_0t+f(u_0)=\dfrac{x_2^2}{2}+(u-x_2)x_2+f(u-x_2)=x_2u-\dfrac{x_2^2}{2}+f(u-x_2)$ , i.e. $u-x_2=F\left(x_1-x_2u+\dfrac{x_2^2}{2}\right)$
$u(x_1,x_2=x_1)=\dfrac{x_1}{2}$ :
$F(x_1)=-\dfrac{x_1}{2}$
$\therefore u-x_2=-\dfrac{x_1}{2}+\dfrac{x_2u}{2}-\dfrac{x_2^2}{4}$
$4u-4x_2=-2x_1+2x_2u-x_2^2$
$(2x_2-4)u=2x_1+x_2^2-4x_2$
$u=\dfrac{2x_1+x_2^2-4x_2}{2x_2-4}$
Answer: $uu_{x_{1}} + u_{x_{2}} = 1, u(x_{1}, x_{1}) = \frac{1}{2} x_{1}$
Let
\begin{cases}
      x(s) = (x_1(s), x_2(s))\\
      z(s) = u(x(s))\\
      p(s) = (u_{x_1}(x(s)), u_{x_2}(s))
\end{cases}
Need to solve the equation:
\begin{cases}
    \frac{dx_1}{ds} = z(s) \\
    \frac{dx_2}{ds} = 1 \\
\end{cases}
Observe that,
\begin{cases}
     \frac{dz}{ds} = 1
\end{cases}
Therefore, we have
\begin{cases}
     \frac{dx_1}{ds} = z(s) \\
        \frac{dx_2}{ds} = 1 \Rightarrow x_2 = s + c_0 \\
        \frac{dz}{ds} = 1 \Rightarrow z = s + z(0)
\end{cases}
where we let $x_1(0) = x_2(0) = c_0. $ and $z(0) = \frac{1}{2} c_0$
\begin{cases}
    \frac{dx_1}{ds} = z(s) \\
    z(0) = \frac{1}{2} c_0 \\
    z = s + z(0) \\
    x_1(0) = c_0
\end{cases}
$\Rightarrow x_1 = \frac{1}{2} s^2 + \frac{1}{2}c_0s + c_0$
Combine above, we now have
\begin{cases}
    x_1 = \frac{1}{2} s^2 + \frac{1}{2}c_0s + c_0 \\
    x_2 = s + c_0
\end{cases}
$\Rightarrow$
\begin{cases}
    s = \frac{2x_1 - 2 x_2}{x_2 - 2} \\
    c_0 = \frac{x_2^2 - 2 x_1}{x_2 - 2}
\end{cases}
$\text{Therefore, for point } (x_1,x_2) \in \mathbb{R}^2 \text{are at the line } x_{c_0}(s) \text{ coefficient } c_0 = \frac{x_2^2 - 2 x_1}{x_2 - 2} \text{ and parameter is } s = \frac{2x_1 - 2 x_2}{x_2 - 2} \text{, that is, } x_{c_0}(s) = (x_1,x_2).$
$\text{Also, we know that } u(x_1, x_2)=z(x_{c_0}(s) = s + \frac{1}{2}c_0 \text{. Then, } u(x_1,x_2) = \frac{x_1 - 2 x_2 + \frac{1}{2} x_2^2}{x_2 - 2} $
Comment: @lisyarus I need my eyes checked, I read the solution incorrectly. Apologies to the person who posted the solution.
Comment: @Mattos Why? $u(x_1,x_1)=\frac{x_1-2x_1+{1\over 2}x_1^2}{x_1-2}={1\over 2}x_1\frac{x_1-2}{x_1-2}={1\over 2}x_1$, as desired.
Comment: Your solution doesn't satisfy the initial condition.


Is there any Shell script to replace values of File1.dat to file2.dat with out changing the file format for each line

Question: I have a file1.dat and a file2.dat containing values. I want to replace the values of the file2.dat with the file1.dat in the first column by changing the file format and data.
I tried this awk command, but problem is its changing the file format and the entire first column is getting changed.
awk 'NR==FNR{a[NR]=$0;next}{$1=a[FNR]}1' file1.dat file2.dat > result.dat

File1.dat (input):
A123456789      1      C      HIE   1   48.343 23.545 32.02 1.00 0.00        H
A875678235      3      C      PHE   1   48.343 23.545 32.02 1.00 0.00        C
A907654234      4      N      ALA   1   48.343 23.545 32.02 1.00 0.00        N
A907863544      5      B      VAL   1   48.343 23.545 32.02 1.00 0.00        B

File2.dat (input):
987654321
567890123
098765432
890765348

Desired output:
A987654321      1       C     HIE   1  48.343 23.545 32.02 1.00 0.00         H
A567890123      3       C     PHE   1  48.343 23.545 32.02 1.00 0.00         C
A098765432      4       N     ALA   1  48.343 23.545 32.02 1.00 0.00         N
A890765348      5       B     VAL   1  48.343 23.545 32.02 1.00 0.00         B

Comment: The challenge is reading a line at a time from two different files.  It would probably be easier you could use a programming language like Perl, C, or Java.  One option with bash is `read -r`: https://unix.stackexchange.com/questions/26601/how-to-read-from-two-input-files-using-while-loop
Comment: I see you add the picture because you want to use color to make it easier to understand. But you need at least to post it as text as well.
Comment: Welcome to Stack Overflow. SO is a question and answer page for professional and enthusiastic programmers. Add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself.
Comment: It seems for me that simple change `$1=a[FNR]` => `$1="A"a[FNR]` should help.
Answer: If you want to keep the first character of column1 (the A) in the first file and assuming
it's okay to use tabs to separate the fields:
awk -v OFS='\t' '
  NR==FNR{ a[FNR]=$1; next }
  { $1=substr($1,1,1) a[FNR] }1
' file2.dat file1.dat > result.dat

Comment: Awesome, so much simpler than I thought
Comment: It's not so much different to the original script :)
Comment: Its just printing the second file values alone with concating the first character in the field of file1.
Comment: @HemanthTanna Did you switch the arguments, i.e. `file1.dat file2.dat` instead of `file2.dat file1.dat`?
Comment: To be clear, that's not working `with out changing the file format for each line`, it's replacing all chains of white space in the input with single tab chars. If the output matched the input than it'd be because all white space in the input happened to be individual tab chars but at least some of the sample input text posted such as `48.343 23.545 32.02 1.00 0.00` is clearly blank-separated, not tab-separated.
Comment: Yes, `assuming it's okay to use tabs to separate the fields`.
Comment: That might be a reasonable approach if you also set FS to `\t` because if you do that and all field-separating spaces are `\t`s then no harm done even if there are blanks within fields but if you don't do that and there are blanks in the file (as it looks like from the posted example) then you'd be changing the formatting by setting OFS alone to `\t`.
Comment: @HemanthTanna from [your comment](https://stackoverflow.com/questions/61444739/is-there-any-shell-script-to-replace-values-of-file1-dat-to-file2-dat-with-out-c#comment108696830_61445616) it sounds like you have carriage returns (`CR` aka `\r` aka `control-M`) in your input, see https://stackoverflow.com/q/45772525/1745001. Swapping the order of the input files wouldn't produce the symptoms you describe but control-Ms would.
Answer: This might work for you (GNU parallel):
parallel  echo {=1 's/^(.)\S+/$1$arg[2]/' =} :::: file1 ::::+ file2

Join the two input file by using the ::::+ operator and replace the last part of the first field by the file2 argument.
Alternative using cat & sed:
cat -n file2 | sed -E 's#\t(.*)#s/[0-9]+/\1/#' | sed -Ef - file1

Prepend line numbers to values in file2 and then replace the introduced tab and the following value by a sed command that replaces the first occurrence of multiple integers by that value. This command is piped into a second invocation of sed that acts on file1. The overall result is a sed command that replaces the first number in each line in file1 by the number in the same line in file2.
Answer: These will both work with whatever spaces you have in your input as they don't change any of those spaces or make any assumptions about what they are:
$ paste file2 file1 | sed 's/\([^\t]*\)\t\(.\)[^[:space:]]*/\2\1/'
A987654321      1      C      HIE   1   48.343 23.545 32.02 1.00 0.00        H
A567890123      3      C      PHE   1   48.343 23.545 32.02 1.00 0.00        C
A098765432      4      N      ALA   1   48.343 23.545 32.02 1.00 0.00        N
A890765348      5      B      VAL   1   48.343 23.545 32.02 1.00 0.00        B

or if you prefer an awk solution:
$ awk 'NR==FNR{a[NR]=$1;next} {print substr($0,1,1) a[FNR] substr($0,length($1)+1)}' file2 file1
A987654321      1      C      HIE   1   48.343 23.545 32.02 1.00 0.00        H
A567890123      3      C      PHE   1   48.343 23.545 32.02 1.00 0.00        C
A098765432      4      N      ALA   1   48.343 23.545 32.02 1.00 0.00        N
A890765348      5      B      VAL   1   48.343 23.545 32.02 1.00 0.00        B

The problem  you were having is that any time you modify a field (e.g. $1) awk reconstructs the record which, with the default FS and OFS, replaces all contiguous chains of white space with a single blank char. If you modify the record ($0) instead of any specific field that doesn't happen.


How to use Fruity Compressor in FL Studio?

Question: I often use Fruity Compressor in many of my sounds or elements, but I don't think I actually know the complete functions of the knobs in Fruity Compressor.
If anyone is using FL Studio here, can you please tell me how Fruity Compressor works and how Multiband Compressor is different?
Answer: What you're really asking is: "how does a compressor work?" -- there are lots of great YouTube videos that explain the basic concepts, including all the controls in Fruity Compressor, so I would start there.
If you like learning by experimentation, though, it might be more instructive to use Fruity Limiter instead (using the compressor controls by clicking the "COMP" button at the bottom of the window) because it allows you to see visually over time how it reacts to an input signal.
In general, for compressor plugins that don't have "multiband" in their name, or do have "wideband" in their name, that means they work such that the compressor's gain reduction applies to the entire frequency spectrum, just like a regular volume/gain control does. A multiband compressor (in FL, Fruity Multiband Compressor and Maximus) applies gain reduction to certain ranges of frequencies independently from each other, which is more like applying an EQ to the signal.
Comment: @EmanuelGomez You're welcome


Poisson convergences of series of random variable

Question: Let $X_i$ be independent Poisson with mean $\lambda_i$. Show that
i)$\sum_1^\infty\lambda_i<\infty$ implies $\sum_1^\infty X_i$ converges almost surely to a finite limit.
ii)$\sum_1^\infty\lambda_i=\infty$ implies $\sum_1^\infty X_i=\infty$ almost surely
I could prove (i) by using Kolmogorov one series lemma just setting $Y_i=X_i-\lambda_i$, but I could not prove the second part. Any help/hint/solution for (ii) is appreciated. Thanks in advance
Comment: Have you tried [Borel-Cantelli](http://en.wikipedia.org/wiki/Borel%E2%80%93Cantelli_lemma)?
Comment: we could solve it by Kolmogorov 2-series theorem, i ll write answer soon
Answer: Assume that $\sum_{i=1}^{+\infty}\lambda_i$ is infinite. Then we can construct inductively an increasing sequence of integers $\left(n_k\right)_{k\geqslant 1}$ such that for each $k\geqslant 1$,
$$\tag{*}\sum_{i=n_k+1}^{n_{k+1}}\lambda_i\geqslant k.$$
This can be done by exploiting the fact that for each $k$, $\lim_{N\to +\infty}\sum_{i=n_k+1}^N\lambda_i=+\infty$.
Now define $Y_k:=\sum_{i=n_k+1}^{n_{k+1}}X_i$. In order to show that $\sum_{i=1}^{+\infty}X_i$ diverges almost surely, it suffices to prove that the sequence $\left(Y_k\right)_{k\geqslant 1}$ does not converge to $0$ almost surely. Define $A_k:=\left\{Y_k\geqslant 1\right\}$. Then the sequence $\left(A_k\right)_{k\geqslant 1}$ is independent and $$\sum_{k=1}^{+\infty}\mathbb P\left(A_k\right)=\sum_{k=1}^{+\infty}\left(1-\exp\left(-\sum_{i=n_k+1}^{n_{k+1}}\lambda_i\right)\right)
\overset{\mbox{ by }(*)}{\geqslant}\sum_{k=1}^{+\infty}\left(1-\exp\left(-k\right)\right) =+\infty.$$


How do I change ownership/permissions of a mounted virtualbox shared folder in Debian?

Question: I'm trying to mount a shared folder and use it as the mysql datadir.
Having succesfully mounted and setup my datadir config, mysqld fails because it lacks the appropriate permissions
I have it mounted to /var/lib/mysql and earlier attempts with /srv/sql ran into the same issue:
drwxr-xr-x  1 root    root     272 Feb 27 12:22 mysql

Trying to run chown -R mysql:mysql /var/lib/mysql makes no difference, as does creating a subfolder and trying to use that.
Here's the mysql entries in syslog:
Feb 27 12:22:23 tomjn-debian-dev-vm mysqld_safe: Starting mysqld daemon with databases from /var/lib/mysql
Feb 27 12:22:23 tomjn-debian-dev-vm mysqld: 130227 12:22:23 [Warning] Setting lower_case_table_names=2 because file system for /var/lib/mysql/ is case insensitive
Feb 27 12:22:23 tomjn-debian-dev-vm mysqld: 130227 12:22:23 [Note] Plugin 'FEDERATED' is disabled.
Feb 27 12:22:23 tomjn-debian-dev-vm mysqld: #007/usr/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
Feb 27 12:22:23 tomjn-debian-dev-vm mysqld: 130227 12:22:23 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: 130227 12:22:24  InnoDB: Initializing buffer pool, size = 8.0M
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: 130227 12:22:24  InnoDB: Completed initialization of buffer pool
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: 130227 12:22:24  InnoDB: Operating system error number 13 in a file operation.
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: InnoDB: The error means mysqld does not have the access rights to
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: InnoDB: the directory.
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: InnoDB: File name ./ibdata1
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: InnoDB: File operation call: 'open'.
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld: InnoDB: Cannot continue operation.
Feb 27 12:22:24 tomjn-debian-dev-vm mysqld_safe: mysqld from pid file /var/run/mysqld/mysqld.pid ended
Feb 27 12:22:39 tomjn-debian-dev-vm /etc/init.d/mysql[5085]: 0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
Feb 27 12:22:39 tomjn-debian-dev-vm /etc/init.d/mysql[5085]: #007/usr/bin/mysqladmin: connect to server at 'localhost' failed
Feb 27 12:22:39 tomjn-debian-dev-vm /etc/init.d/mysql[5085]: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Feb 27 12:22:39 tomjn-debian-dev-vm /etc/init.d/mysql[5085]: Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
Feb 27 12:22:39 tomjn-debian-dev-vm /etc/init.d/mysql[5085]:

The VM itself has debian 6 with apache/php/mysql installed with minimal changes ( I changed my.cnf to use a different datadir then changed it back ). Host machine is OS X Mountain Lion and Virtualbox 4.2.6 with the additions/extensions installed and the USB addon
Answer: please try to mount the shared folder manually using the mysql user id:
Here is an example:
$ id mysql
uid=105(mysql) gid=112(mysql) groups=112(mysql)

then you would do:
$ sudo mount -t vboxsf share_name -o rw,dmode=777,gid=112,uid=105 /var/lib/mysql

Comment: Yes, i think that is a different issue. The uid and gid are constant on the system. Also "dmode=777" from the mount command, gives read-write permissions to everyone. You can try to automate the mount by editing /etc/fstab, so you don't need to run the command every time you boot the VM.
Comment: Thanks, this mounted the folder, and it appears to have given it the right permissions according to `ls -al`, will the command to mount be the same or will I need to figure out the gid every time? mysqld starts from the looks of it but talks about upgrade of tables necessary, but I think that's a different issue


Writing interesting accompaniment rhythms

Question: I've noticed a lot of music by New York composers use very interesting and varied, unpredictable accompaniment patterns (syncopation, rests, variation, counter-melodies etc) for their songs (like in Broadway songs and some Jazz etc). This doesn't seem very prevalent in the classical school of thought where often the left hand just matches the rhythm of the right-hand or else, plays a relatively repetitive structure.
Here's a specific example: You'll Be Back (piano accompaniment)
This song pretty much inspired my interest in jazzy, broadway-ish music and I think it's my favourite and most interesting to my ears. The sheet music can be found on the internet
Some basic observations I've made about this song: a mixture of straight and swing eighths, and triplets, progression of simple to complex, answer-and-call things/countermelodies, chromatic passing notes but no passing chords per se, highly melodic bassline and sometimes even upper and inner-lines, constantly changing rhythm and inversions with a fair number of gaps/rests with no accompaniment at all, The last section ("da-da-da") had a kind of polyrhythm pattern (straight upbeat groove in right-hand over a swing downbeat groove in the left) which represents a peak in complexity, balance- busy, dense sections are followed up by quieter ones, unpredictability
As for specific questions I have about this song, what is the motivation or theory behind the I, I7 chord progression (G to Gdominant7)? And what is the purpose in using the note D quickly (eighth note) to often transition to the next chord?
I̶ ̶w̶a̶s̶ ̶w̶o̶n̶d̶e̶r̶i̶n̶g̶ ̶i̶f̶ ̶t̶h̶e̶r̶e̶ ̶a̶r̶e̶ ̶a̶n̶y̶ ̶g̶o̶o̶d̶ ̶r̶e̶s̶o̶u̶r̶c̶e̶s̶ ̶o̶r̶ ̶b̶o̶o̶k̶s̶ ̶t̶h̶a̶t̶ ̶t̶e̶a̶c̶h̶ ̶w̶r̶i̶t̶i̶n̶g̶ ̶a̶c̶c̶o̶m̶p̶a̶n̶i̶m̶e̶n̶t̶ ̶p̶a̶t̶t̶e̶r̶n̶s̶/̶r̶h̶y̶t̶h̶m̶s̶ ̶i̶n̶ ̶a̶ ̶m̶o̶r̶e̶ ̶u̶n̶p̶r̶e̶d̶i̶c̶t̶a̶b̶l̶e̶ ̶N̶e̶w̶ ̶Y̶o̶r̶k̶i̶a̶n̶ ̶s̶t̶y̶l̶e̶?̶ ̶T̶h̶e̶ ̶b̶o̶o̶k̶s̶ ̶o̶n̶ ̶a̶c̶c̶o̶m̶p̶a̶n̶i̶m̶e̶n̶t̶ ̶w̶r̶i̶t̶i̶n̶g̶ ̶I̶'̶v̶e̶ ̶m̶a̶n̶a̶g̶e̶d̶ ̶t̶o̶ ̶f̶i̶n̶d̶ ̶a̶r̶e̶ ̶t̶o̶o̶ ̶s̶i̶m̶p̶l̶i̶s̶t̶i̶c̶ ̶a̶n̶d̶ ̶f̶o̶l̶l̶o̶w̶ ̶c̶l̶a̶s̶s̶i̶c̶a̶l̶ ̶t̶h̶i̶n̶k̶i̶n̶g̶.̶
Could I have any general (or specific) advice on how to train/study to be able to write accompaniments like this?
Comment: isn't it much faster if I just look up the sheet music? I would think the more concepts my brain can absorb in a shorter time period, the larger my library of tools would be
Comment: Sheet music is great but being able to transcribe music yourself gives you a different appreciation of what exactly is going on in the music. For example, if there is a very quick melodic run which could be either fast triplets or fast semiquavers, looking up the sheet music would give you the answer immediately but trying to slow down the song and exactly work out the rhythm will give you a whole new perspective on the music and make it easier for you to pick out that particular sound in other works.
Comment: This applies to working out jazz/prog/whatever rhythms too - and once you get a base understanding, you'll be able to feel what rhythms feel right in the song you're writing as you'll be much more familiar with the feel and sound of the rhythms.
Comment: In terms of the I -> I7 progression (G -> G7), this is then followed by an inverted C chord. G -> C is a perfect cadence in C major, so it can be analysed as a mini modulation to C before it's clear that we are in fact in G. More likely though is that the song seems to use the G Mixolydian mode rather than the regular major scale, which G7 is a part of (G mix = C maj).
The G -> G7 -> C -> D -> G progression is a variation on I -> IV -> V -> I progression, and the quick  C -> D suspends the C for a beat or so longer than expected for rhythmic interest rather than having a full bar of C then D.
Comment: Thanks, i never knew about that mini-modulation concept, i'd be interested to learn more about it. Also, the C chord always has the note A in the bass so could it also be considered Amin7?
Comment: Edit: the C chord is often followed Amin7, and instead of going G-G7-C-Amin7-D->repeat it sometimes does another cycle Em-G-Cadd2-C-Amin7-D-> repeat. The quick Am7s remind me of Raindrops Keep Falling On My Head, but I don't understand these progressions except for the vague resemblences to I-IV-V, but there seems to be a lot of other stuff going on
Answer: It sounds to me like you're asking to be trained to be creative. You're going after something 'interesting and varied, unpredictable'. Nobody can really train you to be those things. Training is for learning the established knowledge. In order to be interesting, varied and unpredictable you have to take the established knowledge and go beyond it, extend it or add your own flair.
I'd say continue to study the basics - theory, critical listening, playing your instrument, etc. You need that base to stand on and draw from. Then take a leap and write down what you hear in your mind or better yet, what you feel in your gut. You can trust yourself. Delight yourself and you will delight your listeners, or at least some of them.
Answer: Many years ago, I asked the same thing and the suggestion was to look at many scores and see what has been done. I took the International Encyclopedia of Music (it has several hundred piano scores from easy to Beethoven Sonatas and Lizst Etudes.) I found only a few basic styles, block chord, arpeggios (Alberti bass), countermelody (imitative or else), boom-chick style (root and fifth on the beats and chords off the beat like typical country bass and guitar).
The trick is to vary each style; classical piano music always makes (usually small) changes with every repeat with big changes to signal important section transitions. A good source of how to vary accompaniment for the same dance styles is available on Todotango.com. There is lots of sheet music from the 1800s to the 2000s with tangos, milongas, and waltzes.
The Library of Congress and some college libraries have lots of sheet music online (all fairly old as it's before copyright.) IMSL and others have some classical stuff. All the stuff there is adaptable to any style. The only thing I've noticed is that even repetitive music rarely has exact repeats; the idea seems to be to allow the listener to know that changes are happening.


Strict warning and views - site not working

Question: I am using drupal 6 and after moving to php 5.4 or 5.5 from 5.3, I am getting error <code>"strict warning: Declaration of views_plugin_style_default::options() should be compatible with views_object::options() in.... views_plugin_style_default.inc on line 24."</code>
I tried updating views but does not help. It is not just about warning - Views do not work at all. What can be done in this case? Besides switching to 7.x - it is not an option for me. Thank you.
Answer: There is a patch, it can be found here: https://www.drupal.org/node/893128
I used this one: https://www.drupal.org/files/issues/893128-61.views_.strict-warnings-method-declarations-php-5-4.patch but it did not fix everything. In the end I fixed some items manually similar to what is done in the patch where I replace the function arguments that are the problem from $argument to &$argument. (or sometimes the other way around).
Did you already try the latest dev version, because a patch for the issue I mentioned was committed recently, but I don't think a new version was released since then.
Comment: @Bala, thanks for the help, I have edited my answer. May I ask why you downvoted my answer immediately, it was meant as help. the fact I mentioned there is a patch might encourage someone to go look in the issue queue on drupal.org :)
Comment: Hi daften downvote not from me, now your answer looks good!


$T_0$-Identification of a topological space

Question: In Willard's General Topology, section 13.2.c, for any topological space $X$ is defined a quotient space $X/\sim$ such that $x \sim y$ iff $cl(\{x\})=cl(\{y\})$ where $cl(.)$ is the topological closure.
Then it is stated that the quotient space $X/\sim\, = \widetilde X$ is a $T_0$ space.
The proof of this statement has been given in my instructor's lecture notes and it follows the following line of reasoning:
Let $[x]\neq [y]$ be two elements of $\widetilde X$. Then either $x \notin cl\{y\}$ or vice versa.
Suppose $x \notin cl(\{y\})$. Now we know that $X \backslash cl(\{y\})$ is open in X. Also, it is a saturated subset of $X$ and  $x \in X \backslash cl(\{y\})$.
Therefore,  $\varphi(X \backslash cl\left(\{y\})\right)$ is open in $\widetilde X,\,$ where $\varphi :X \rightarrow \widetilde X$ is the canonical mapping. This is due to the fact that open sets in quotient space, carrying the final topology w.r.t. the canonical mapping, are in one-one correspondence with open saturated subsets of the original space.
Further, $[x] \in \varphi(X \backslash cl\left(\{y\})\right)$ but $[y] \notin \varphi(X \backslash cl\left(\{y\})\right)$. Hence, $\widetilde X$ is a $T_0$ space.
My doubts are:
1) How do we know that $X \backslash cl(\{y\})$ is a saturated subset?
2) What is the actual form of $[x]$? I have managed to prove that $[x] \subset cl(\{x\})$ (quite trivial) but it seems to be a dead end.
Answer: $O=X\setminus \overline{\{y\}}$ is saturated:
If $z \in O$ and $z' \sim z$, we have to show that $z' \in O$ as well. (This is the definition of being saturated in this context).
So $z \in O$ impies $z \notin \overline{\{y\}}$ and $z \sim z'$ means $\overline{\{z\}} = \overline{\{z'\}}$. Now, $z' \notin \overline{\{y\}}$, or else $\{z'\} \subseteq \overline{\{y\}}$ and hence $\overline{\{z'\}} \subseteq \overline{\{y\}}$, but then also $z \in \overline{\{z\}} = \overline{\{z'\}} \subseteq \overline{\{y\}}$ which is a contradiction. So $z' \in O$, as required.
So when $x \notin \overline{\{y\}}$, $x \in O$ and $O$ is saturated so $\phi[O]$ is open in $X{/}\sim$ and contains $[x]=\phi(x)$ but not $[y]=\phi(y)$( because if $[y] \in \phi[O]$, this would mean that some $z$ with $z \sim y$ would be in $O$, but this cannot be as $z \in \overline{\{z\}} = \overline{\{y\}}$ which is disjoint from $O$ by definition). This thus shows the $T_0$-ness of the quotient.
The actual form of $[x]$ doesn't really matter: it's just the set of all $y$ that have the same closure as $\{x\}$, by definition. The idea is to identify all points that are in exactly the same open sets: if $x \sim y$ and $x \in O$ then $y \in O$, and if $y \in O$ then $x \in O$, for any open set. So we can never distinguish $x$ and $y$ by using open sets.
A simple example: $X=\{1,2,3,4\}$, $\mathcal{T}=\{\emptyset,\{1,2\},\{3,4\},X\}$. The quotient relation identifies $1$ and $2$, and $3$ and $4$, and the resulting quotient space is a two point discrete space (indeed $T_0$). Leaving out $\{3,4\}$ as an open set, gives the same quotient two-point set but with a Sierpiński topology instead. Try it out.
Comment: woww...thanks for such a clear answer!


Lilypond spacing between lyrics and next system

Question: I'm trying to improve the legibility of my scores by increasing the basic-distance between systems. There needs to be some whitespace between the last verse and the next system below.
Here's what I've tried so far
nonstaff-unrelatedstaff-spacing.basic-distance = #18

=> does not work between systems, but only staves in the same system.
system-system-spacing.basic-distance = #14

=> increases the basic distance between the staves that are facing each other across systems, but does not include the lyrics between them. I would thus have to increase the distance depending on the number of verses.
I am also not sure, where to put the lines. Mostly I've placed them in a \paper block at the top of the file
\paper {
  system-system-spacing.basic-distance = #18
}

but I have also tried putting them in layout in the lyrics' context
\score {
  \layout {
    \context { \Lyrics
      \override VerticalAxisGroup.nonstaff-unrelatedstaff-spacing.basic-distance = #18
    }
  }
  %{ … %}
}

this did not yield any noticeably different results from the above examples.

Any pointers would be welcome, all this seems like an oversight to me but I am starting to get the feeling that nobody has thought about this so far. I'd be happy to help filing an issue with the dev team, should it come to that.
edit: Using padding instead of basic-distance solved the problem.
Comment: Possible kludge: add a whitespace-only line above and below the existing text block.
Answer: If something like what you have posted is not working, it may be because your instructions are attempting to reference a part of your score that you haven't spelled out (that is, while you may be attempting to put space between systems, with lyrics below them, maybe your score isn't structured that way).
For instance: (code here: http://lilybin.com/36udgm/1)
\version "2.18.2"
\paper {
  system-system-spacing = #'((padding . 20))
}
melody = \relative c' {
  \repeat unfold 12 {
    b'4 b b b
  }
}
words = \lyricmode {
  \repeat unfold 12 {
    Lor -- em ip -- sum
  }
}
\score {
  <<
    \new ChoirStaff <<
      \new Voice = "sing" { \melody }
      \new Lyrics \lyricsto sing \words
      \new Lyrics \lyricsto sing \words
      \new Lyrics \lyricsto sing \words
      \new Lyrics \lyricsto sing \words
      \new Voice = "sing" { \melody }
    >>
      \new Lyrics \lyricsto sing \words
      \new Lyrics \lyricsto sing \words
      \new Lyrics \lyricsto sing \words
      \new Lyrics \lyricsto sing \words
  >>
}

Is this what you are trying to achieve?
Comment: I think I see what you mean. It has to be independent of the number of verses. I'll compile a visual example to illustrate.
Comment: After playing around with your example I realised that my mistake has been to use `basic-distance` instead of `padding`, works perfectly now, thank you.
Comment: @JoëlMeyer-Hamme - Try reading through here: http://lilypond.org/doc/v2.18/Documentation/notation/flexible-vertical-spacing-paper-variables#structure-of-flexible-vertical-spacing-alists for an explanation on the other options --- I have always used `padding` because I don't understand their definitions of most of the others.
Answer: Just for completeness, here are all the parameters for that function, with their default values:
system-system-spacing =
  #'((basic-distance . 12)
     (minimum-distance . 8)
     (padding . 1)
     (stretchability . 60))


Can I recover my raid after blown backplane / mobo?

Question: We had a catastrophic server failure the other day. The server was the head to our NAS. Multiple disk shelves were attached via SAS (SFF-8088 to a HP Smart Array RAID Card). Also connected to the RAID card was a shelf of disks on the head server itself, the backplane was connected to the RAID card via SFF-8484 on both ends.
I can't get any power to the backplane and/or mother board. The power supply has been replaced and the PSU blades were tested and appeared to work in another server. However in this server I get nothing. So no power as it stands. We stuck the RAID card in another HP server (different model!) and the RAID card was recognized. The external disk shelves were then connected via 8088 and the RAIDS for the shelves were brought back up and no issue.
However, the RAID groups from the disks within the failed servers shelf, cannot be loaded from our replacement server.
We tried taking one of our new disk shelves, putting the original drives from the failed server in it (the two we care about anyways, which are backed up via DD images), and connecting it to the new NAS head via the 8088 connection. No dice. It sees the shelf and the drives, but it's all different porting and whatnot.
My thinking is, well we don't have a replacement backplane/mobo. If I could just get the drives to be seen at the right port number on the RAID card (the 8484 port) at the correct bays (bay 1 and bay 2, or whatever), the HP Smart Array will see a backplane at the correct port, and the correct disks in the correct positions within that shelf.
Through some googling I found this!
http://www.monoprice.com/Product?c_id=102&cp_id=10254&cs_id=1025413&p_id=8198&seq=1&format=2
Our new disk shelf is 8087 internal to an expander card, and 8088 out the back. Obviously I cant go 8484 from the new shelfs backplane to the RAID card, however, I thought perhaps going 8088 out the back of the shelf, to 8484 on the RAID card would show the shelves/disks in the right spot!
However in the red text on the website, it indicates it's a directional cable and the 8484 portion can only be connected to the backplane, not the host.
My question is this. Can I recover this data without ordering a replacement server, using a few parts, cables and elbow grease? Does there exist a cable that will connect the 8088 end to my new disk shelf, and the 8484 end to my RAID card. If so, will me theory of the correct port on the card being used and correct drive positioning in the new shelf bring the RAID back up?
Thank you for your input!
EDIT 1 - Hardware Information.

Failed NAS Head Server - HP DL185 (generation 5, I think? Maybe?)
RAID Controller SmartArray P800. , I cannot recall the specific model, I know it's HP and the software is Smart Array or whatever. Something that would of shipped with a DL185 and has atleast SFF-8088/8484 ports on it.
New temp shelf, SansDigital 24 bay SATA/SAS, model no. ES424X6+BS. (cannot recall model at this time).

Please let me know if you need any more info. I'm not at work right now or over the weekend so it might be a little while.
Random note, is it possible to change the port/drive positions the HP RAID controller looks at for a certain RAID group? For example the failed RAID that I can't get connected was on port "3I", at drives 1 and 2. Is it possible to change that information on an HP RAID card so that it looks for that RAID on port "2E" for example?
Comment: Please specify the **model**, **generation** and **manufacturer** of the server, as well as the RAID controller.
Comment: Updated the best I could at this time, @ewwhite
Answer: For lack of better information (like the actual models of your server(s)), I'll give a generic answer.
This sounds like it could be a G5 ProLiant server... Perhaps a DL360 G5 or DL380 G5 with a Smart Array P800 RAID controller.

Given this, all G5 and newer HP ProLiant 300-series servers contain onboard RAID controllers. Also, disk array metadata is stored on the drives, not the controller. So you can move physical disks together and retain the data contained within. There are rules for this, though.
The disks inside the server are part of an internal "drive cage" (not "shelf"). If you moved things to a different server model, there could be an issue there.
Please fill in more details so I can provide a better answer.
Comment: Thanks for the input! The server is older, if I can recall correctly, I know for a fact it's an HP DL185, I can't remember if it's a G5 or something to that effect however. The drives im trying to recover where in the drive bays on the failed NAS head itself, the rest of the drives were in separate drive shelves attached via SAS (8088). I'll post some more details in an edit to my question.
Comment: How many disks were in the server? How many were in the external enclosure? What operating system and RAID configurations did you have?
Comment: Also, what server model did you TRY to move things to?
Comment: There were 12 disks in the failed server, 10 in one array, 2 in the array im trying to recover. I don't spend alot of time in the data center. I believe on in the rack there was about 4-6 disk shelves totaling somewhere in the neighborhood of 48-64 disks. The original operating system was Server 2003 "Storage Edition" if I recall. The RAID groups were mostly RAID 6's if I recall. I'm not the primary administrator of this system. Unfortunately he is gone for awhile on vacation so I am trying to get my lost data back fast. Sorry for the lack of extreme familiarization!
Comment: The new server is an HP, I couldn't tell you the exact model. I think I remember hearing someone say it was in the 300s. The main guy working on this got some stuff up and running, then took off and I am now trying to figure some ideas to get my data back, seeing to as it's mission critical and very hindering to not have it for the next two weeks. Eek!
Comment: Fire the sysadmin ;) - Should this be your problem?
Comment: Haha. First time we've ever had something go belly up like this. We're a small operation, shouldn't be my problem, but waiting slows us down, kind of have to informally shoulder this if I want it done quickly. I suppose something like this was bound to happen. The timing is pretty terrible though. Tomorrow I go in. I'll get specific model numbers for everything and edit my main post. I really appreciate your insights ewwhite!
Comment: I edited my main post with some model information on the new shelf and RAID card.
Comment: @0xhughes What about the new server?
Comment: I'll have that model no. tomorrow. Good news, I was able to recover data off of the two disk RAID 1 pair that had three HP Smart Array Logical Volumes on it! It seems HP stores the logical volumes as raw physical blobs of data floating around in RAID array disk space. So using a hex editor, I was able to locate the master boot record of the volume I wanted, calculate the NTFS volume start sector, then point the mount command at it by specifying the NTFS volume starting byte offset. This method won't work for the other 10 disk RAID 6 containing 7 terabytes of data. Eek.


Repeated measures ANOVA modeling question

Question: I have a (to me) complex experimental design I'm working on pre-registering and I want to make sure I'm approaching the model correctly. I've attempted to offer an illustration of the design below.
I have two experimental conditions that are manipulated prior to the administering of the repeated measures, so I think it would be accurate to describe this as a nested design. I'm primarily interested in the main effects at Time 1 and the over time interactions for the groups that change. My question is, since I'm using repeated measures, can I just "lump" the between subjects groups together (so four levels) or is it better to enter two separate between subjects factors (each with two levels) into the model. I've attempted to simulate the data, but that's not helping me clarify.
Is it also appropriate to do planned contrasts here since I have specific comparisons I want to make?
Comment: Thank you! Yes, you are interpreting the design as I have it.

The participants come to the lab and are put into an experiment where they are in Condition A (observing someone in conversation) or Condition B (participating in the conversation). Then they receive Time 1 DV measures.

Then they either stay in their initial Condition or change to the opposite condition. After this second stimulus exposure they receive the same measures as Time 1 for Time 2 (this is the repeated measure).
Comment: Hi, welcome to CV! Can you clarify what "manipulated prior to the administering of the repeated measures" means? Does this mean you have no data prior to any experimental manipulation, but two measures per participant that were both taken after the respective (A or B) manipulations?
Answer: OK! I admit I'm slightly unsure about this so maybe wait if you get another answer, but since you currently have no answers, I'll have a go.
So you have in some sense 4 different groups: A to A, B to B, A to B and B to A, right? But only 2 different manipulations, A and B.
If you are confident that changing (vs. not changing) condition, and the order or A vs B (for those who changed condition) have no effect on your DV, and that changing and order have no effect on the effect of condition on DV, you can probably just have a 2x2 between (condition) - within (time) ANOVA.
You could check for the potential effect of change by creating a binary variable of change vs. no change (those staying in A or in B would receive value "no" and those changing between conditions receive value "yes") and putting this variable and its interaction with condition into the model. If its main effect and interaction are non-significant, you could remove it and use the 2x2 anova as your main model / the model you report.
Yes you can do planned contrasts after the omnibus ANOVA. Especially if you have pre-registered the contrasts you check - it's great that you're going to pre-register!
Comment: Ah, thank you so much! I appreciate your time and feedback and will also add that tag to (hopefully) get some more thoughts, but your feedback follows my speculating. Really appreciate you!
Comment: Thanks!! I think the order of change will matter. So, I think I either have to specify the between subjects variable as one predictor (with four levels) or two predictors (each with two levels). The two predictors with two levels seems the better approach, but the issue I'm running into in my simulated data is that since I don't expect change between Time 1 and Time 2 for A to A, B to B participants, this will produce a nonsignificant omnibus model and it would be inappropriate to interpret the interactions. I thought it might be ok to go this route if I pre-register the planned comparisons?
Comment: As the order only concerns participants in the change groups, it might be OK to check the possible effect of order for this subgroup (A->B + B->A) only. And I think the 4-level predictor as the between factor would work quite nicely for the main analysis.
Comment: Re: planned comparisons, it is actually OK to check (theoretically predicted) planned comparisons also in the absence of a significant omnibus interaction, see [here](https://stats.stackexchange.com/questions/9751/do-we-need-a-global-test-before-post-hoc-tests) and [here](https://stats.stackexchange.com/questions/602608/factorial-regression-without-significant-interaction-can-i-consider-contrasts), so you don't have to worry about the omnibus test :)
Comment: Sorry for the many comments, but if you edit in "anova" tag you might get more people to see your question and get more advice.
Comment: Glad to hear that :) Good luck!


JavaScript SetInterval não funcionando... em que errei?

Question: Como podem ver no meu código abaixo, eu precisei transformar minha imagem em link por JavaScript ao invés de usar o método simples por HTML (por razões específicas), porém eu preciso que leve um intervalo de 3 segundos para a função arrancar, mas não consegui... sabem me dizer no que eu errei?
aqui

Comment: Na verdade só usou a função errada. Primeiro veja a documentação do [addEventListener](https://www.w3schools.com/jsref/met_element_addeventlistener.asp) e depois verifique se isso te ajuda https://pt.stackoverflow.com/q/23861/57801
Comment: Você tem razão, sintaxe errada! como falou o @dvd
Answer: Sintaxe errada. Não use setInterval (irá executar o código infinitas vezes), use setTimeout (executa só 1 vez):

document.getElementById('cima').addEventListener('click', function() {
   setTimeout("location.href = '#subir'", 3000);
});
aqui

Comment: Não porque setInterval é contínuo, enquanto setTimeout só executa 1 vez.
Comment: Poxa, exatamente! Obrigado. Já volto pra selecionar como a resposta correta :)
Comment: @Everson Obg Everson.


Apache HTTPD - Segmentation fault when loading mod_jk module

Question: I just set up mod_jk with my Apache httpd 2.0.52 installation, but now when I try to start Apache, it has a segmentation fault. I've checked that I am using the mod_jk compiled for 2.0.x.. built against the same version I have, in fact. I've also verified that the path I'm giving to LoadModule is correct, and the permissions and the ownership of the file are the same as the rest of the modules'. When I remove the "LoadModule" command for mod_jk from my httpd.conf, there is no segmentation fault.
Nothing shows in Apache's error logs. I have tried restarting the server with this module using both service httpd restart and httpd.
These are the last few lines returned of strace httpd -X:
gettimeofday({1292100295, 434487}, NULL) = 0
socket(PF_INET6, SOCK_STREAM, IPPROTO_IP) = -1 EAFNOSUPPORT (Address family not supported by protocol)
socket(PF_NETLINK, SOCK_RAW, 0)         = 3
bind(3, {sa_family=AF_NETLINK, pid=0, groups=00000000}, 12) = 0
getsockname(3, {sa_family=AF_NETLINK, pid=22378, groups=00000000}, [12]) = 0
time(NULL)                              = 1292100295
sendto(3, "\24\0\0\0\26\0\1\3\307\342\3M\0\0\0\0\0\305\333\267", 20, 0, {sa_family=AF_NETLINK, pid=0, groups=00000000}, 12) = 20
recvmsg(3, {msg_name(12)={sa_family=AF_NETLINK, pid=0, groups=00000000}, msg_iov(1)=[{"<\0\0\0\24\0\2\0\307\342\3MjW\0\0\2\10\200\376\1\0\0\0"..., 4096}], msg_controllen=0, msg_flags=0}, 0) = 664
recvmsg(3, {msg_name(12)={sa_family=AF_NETLINK, pid=0, groups=00000000}, msg_iov(1)=[{"\24\0\0\0\3\0\2\0\307\342\3MjW\0\0\0\0\0\0\1\0\0\0\10\0"..., 4096}], msg_controllen=0, msg_flags=0}, 0) = 20
close(3)                                = 0
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
--- SIGSEGV (Segmentation fault) @ 0 (0) ---
+++ killed by SIGSEGV +++
Process 22378 detached

Has anyone had a similar problem using Apache 2.0.52 with mod_jk? I might try downloading and building the source for the Apache server and mod_jk myself if there isn't a discovered fix for this.
Answer: Is this a precompiled mod_jk that you found? If so, then it's simple enough to just grab the latest source for mod_jk and compile it, I suspect this is where your problem is - I've compiled mod_jk against the vendor supplied (Red Hat) Apache a lot of times without segfaults.
Make sure httpd-devel is installed (Red Hat/CentOS)
Unpack the real JDK to some path, like /usr/local/jdk1.6.0_18/
Grab the "tomcat-connectors" source from tomcat.apache.org and compile it:
cd tomcat-connectors-1.2.28-src/native
./configure --with-apxs=/usr/sbin/apxs --with-java=/usr/local/jdk1.6.0_18 --enable-prefork
make
cp apache-2.0/mod_jk.so /etc/httpd/modules/

Your modules should now work as expected.


syntax error, unexpected ',', expecting => (SyntaxError) => ruby

Question: Good evening.
I develop a program in ruby language and when I put the comma "," I get an error and I couldn't solve it, please help me.
require "net/http"
require "colorize"
puts "+================================+".red
puts "|        ABDO[panel-scan]        |".green
puts "+================================+".red
pages = {'admin.php','loginpage.php','index.php','login.php'}
print "Enter url site : "
site = gets.chomp
for i in pages
    url = URI(site)
    web = Net::HTTP.get_response(url + i)
    puts "[-] #{url}#{i} ".blue + " | ".red + web.code + " | ".red + web.message
    if web.message == 'ok'
        puts "[^_^] admin panel Found ".yellow
    end
end

The error is:
syntax error, unexpected ',', expecting => (SyntaxError)
pages = {'admin.php','loginpage.php','index.php','...
                    ^

Thank you.
enter image description here
enter image description here
Comment: It's not Python :) You should use square brackets for array
Answer: Curly brackets ({}) are used in Ruby to define a Hash which is a data structure with keys and values.
In your example, it looks like you want to define an Array which is a data structure that acts like a list of values. To define an array in Ruby, use square brackets ([]) instead, like this:
pages = ['admin.php', 'loginpage.php', 'index.php', '...']

Comment: Firstly Ruby parser check syntax, then run the script. So you fix syntax, and now some other error
Comment: I can't use square brackets because it will generate a new error which is:   :85:in `require': cannot load such file -- colorize (LoadError)
 from :85:in `require'
 from c:/Users/Abdullah Abdulkadir/Desktop/course/hack web/scan.rb:2:in `'
Comment: That error is totally unrelated to the first error. It tells you that this line `require "colorize"` is not able to load `colorize`. Did you have the `colorize` gem installed? If that error persists, I suggest opening a new question for it, because it is unrelated to the syntax error from this question.


Mean number of offsprings at time n

Question:
Definition for expected value: $\mu= \sum_{k=0}^{\infty}kp_{k}$

In a text, the author mentioned that

for a time n-1 where the offspring is $X_{n-1}=m$, the mean number of offsprings at time n is $m\mu$

Would someone give me why this is the case?
Answer: Guide:
Let the number of offspring by the $i$-th offspring in the $(n-1)$-th generation be $Y_i$ where $i \in \{1,\ldots, m\}$.
Then the number of offspring in the $n$-th generation is $\sum_{i=1}^m Y_i$.
Compute it's mean by using linearity of expectation. Can you complete the task?
Comment: I do not have a background in probability but I'm familiar with the linearity principle so it does look doable.
Comment: layman terms: You have exactly $1$ sibling and each of you are expected to have $3$ kids each. how many grandson do your parents  expect to have
Comment: The expected number of grandsons to exist is six.
Comment: the working is the same. just more algebra =)
Comment: In your third line, should we replace "individual" in "Then the number of individual in the n-th..." with "off springs"?
Comment: sure, thanks. I have changed individual to offsprings.
Comment: Also, number of offsprings in the (n-1)-th generation.
Comment: Hmmm... the next generation comes from current generation. If we were to describe the current generation as "offsprings", then I think I have to used "offsprings of offsprings"?
Comment: I didn't realise you edited the 2nd sentence. Now, "n-th generation" makes sense.

Mean number of offsprings at time n


Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

Question: They are algorithms for the young generation garbage collection.
The second one (UseParNewGC) gets activated automatically with the concurrent tenured generation garbage collection (see Java Concurrent and Parallel GC) but, is there a difference between the two parallel algorithms?
Answer: After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003

Young generation garbage collection algorithms
The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.
The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.
The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).

From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics  while UseParNewGC doesn't.
Comment: Slightly more up to date link http://www.fasterj.com/articles/oraclecollectors1.shtml
Comment: @phunehehe Thanks for the link! It's very helpful.
Answer: Parallel GC

XX:+UseParallelGC    Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
XX:+UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)

UseParNewGC

UseParNewGC
  A parallel version of the young generation copying collector is used
  with the concurrent collector (i.e. if -XX:+ UseConcMarkSweepGC is
  used on the command line then the flag UseParNewGC is also set to true
  if it is not otherwise explicitly set on the command line).

Perhaps the easiest way to understand was combinations of garbage collection algorithms made by Alexey Ragozin

    Young collector
    Old collector
    JVM option

    Serial (DefNew)
    Serial Mark-Sweep-Compact
    -XX:+UseSerialGC

    Parallel scavenge (PSYoungGen)
    Serial Mark-Sweep-Compact (PSOldGen)
    -XX:+UseParallelGC

    Parallel scavenge (PSYoungGen)
    Parallel Mark-Sweep-Compact (ParOldGen)
    -XX:+UseParallelOldGC

    Serial (DefNew)
    Concurrent Mark Sweep

-XX:+UseConcMarkSweepGC

-XX:-UseParNewGC

    Parallel (ParNew)
    Concurrent Mark Sweep

-XX:+UseConcMarkSweepGC

-XX:+UseParNewGC

    G1
    -XX:+UseG1GC

Conclusion:

Apply -XX:+UseParallelGC when you require parallel collection method over YOUNG generation ONLY, (but still) use serial-mark-sweep method as OLD generation collection
Apply -XX:+UseParallelOldGC when you require parallel collection method over YOUNG generation (automatically sets -XX:+UseParallelGC) AND OLD generation collection
Apply -XX:+UseParNewGC & -XX:+UseConcMarkSweepGC when you require parallel collection method over YOUNG generation AND require CMS method as your collection over OLD generation memory
You can't apply -XX:+UseParallelGC or -XX:+UseParallelOldGC with -XX:+UseConcMarkSweepGC simultaneously, that's why your require -XX:+UseParNewGC to be paired with CMS otherwise use -XX:+UseSerialGC explicitly OR -XX:-UseParNewGC if you wish to use serial method against young generation
Comment: Must be `-XX:-UseParallelGC`.
Comment: Note: Conclusion #1 is not correct anymore. Applying `-XX:+UseParallelGC` leads to use parallel GC for both, young and old GC for modern JVMs. See https://bugs.openjdk.java.net/browse/JDK-6679764?focusedCommentId=12410139&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-12410139
Answer: UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".
See Java GC FAQ, question 22 for more information.
Note that there are some known bugs with UseParNewGC
Comment: Do you know which known bugs or which JVM version has them?
Answer: Using -XX:+UseParNewGC along with -XX:+UseConcMarkSweepGC, will cause higher pause time for Minor GCs, when compared to -XX:+UseParallelGC.
This is because, promotion of objects from Young to Old Generation will require running a Best-Fit algorithm (due to old generation fragmentation) to find an address for this object.
Running such an algorithm is not required when using -XX:+UseParallelGC, as +UseParallelGC can be configured only with MarkandCompact Collector, in which case there is no fragmentation.
Comment: This is a really good insight. Did you perform any tests to confirm it?
Answer: I will try to answer this question using official Oracle docs:
What is the purpose of -XX:+UseParNewGC
The purpose of this argument is to enable the use of parallel threads for GC in the young generation.

 -XX:+UseParallelGC v/s -XX:+UseParNewGC

-XX:+UseParallelGC is parallel collector and -XX:+UseParNewGC is parallel young generation collector.
Parallel young generation collector is similar to the parallel garbage collector in intent and differs in implementation. Unlike the parallel collector (XX:+UseParallelGC) this parallel young generation collector can be used with the concurrent low pause collector that collects the
tenured generation.

 When -XX:+UseParNewGC should be enabled/used?

By default this option is disabled and it is automatically
enabled when you set the -XX:+UseConcMarkSweepGC option. Using the
-XX:+UseParNewGC option without the -XX:+UseConcMarkSweepGC option was deprecated in JDK 8.

 In Summary
The whole purpose of this argument is to enable the use of parallel threads for GC in the young generation. In Java 8 use of this argument without the use of CMS collector (-XX:+UseConcMarkSweepGC) is deprecated and with Java 9 this argument itself is deprecated because this argument can only be used with CMS collector and CMS collector itself was deprecated in Java 9.
Answer: The CMS collector is designed to eliminate the long pauses associated with the full GC
cycles of the throughput and serial collectors. CMS stops all application threads during
a minor GC, which it also performs with multiple threads. Notably, though, CMS uses
a different algorithm to collect the young generation (-XX:+UseParNewGC) than the
throughput collector uses (-XX:+UseParallelGC).
Instead of stopping the application threads during a full GC, CMS uses one or more
background threads to periodically scan through the old generation and discard unused
objects. This makes CMS a low-pause collector: application threads are only paused
during minor collections, and for some very short periods of time at certain points as
the background threads scan the old generation. The overall amount of time that application threads are stopped is much less than with the throughput collector.


Ajax Callback only works after second click

Question: I created a custom form with a textbox and a button. When the user clicks on that button, an ajax call should take place.
When I click on that button for the first time, a page refresh takes place. Only when I click on the button for the second time, my ajax-function is called.
I don't know what I'm doing wrong, so I would be greatful for any suggestion.

function buildForm(array $form, FormStateInterface $form_state)
{
    //Oorspronkelijk staat van formpost:
    $_SESSION['formpost'] == 'rrn_nok';

    array_push($form['#attributes']['class'], 'col-12');

    $form["foutmeldingen"] = array(
        '#type' => 'container',
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['group_rrn'] = array(
        '#type' => 'container',
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['group_rrn']['rijksregisternummer'] = [
        '#type' => 'textfield',
        '#required' => TRUE,
        '#title' => 'Rijksregisternummer',
        '#attributes' => [
          'data-inputmask-mask' => '999999-999-99',
          'class' => ['js-webform-input-mask'],
        ],
    ];
    $form['group_rrn']['rijksregisternummer']['#attached']['library'][] = 'webform/webform.element.inputmask';

    $form['group_rrn']['actions'] = array(
        '#type' => 'button',
        '#value' => 'Ga verder',
        '#attributes' => array('class' => array('btn', 'btn-primary')),
        '#ajax' => [
            'callback' => '::ajaxRijksregisternummer',
            'event' => 'click',
            'wrapper' => 'aanvraag',
            'progress' => array(
                'type' => 'throbber',
                'message' => 'Even geduld',
            ),
        ],
    );

    $form['group_form'] = array(
      '#type' => 'container',
      '#prefix' => '
',
      '#suffix' => '
',
  );

    $form['group_form']['landen'] = array(
      '#type' => 'textfield',
      '#title' => 'Kies land(en)',
      '#autocomplete_route_name' => 'tools.reisdocumentenautocomplete',
      '#autocomplete_route_parameters' => array(),
      '#description' => "Typ de beginletters van het land en kies uit de lijst. Voor meerdere landen typ je een ',' en herhaal dezelfde werkwijze.",
    );

    $form['group_form']['startdatum'] = [
      '#type' => 'date',
      '#title' => 'Kies startdatum',
      '#date_format' => 'd-m-Y',
      '#attributes' => [
        'min' => format_date(strtotime("+7 day", time()), 'html_date'),
        'data-inputmask-mask' => '99-99-9999',
        'class' => ['js-webform-input-mask'],
      ],
    ];

    $form['group_form']['einddatum'] = [
      '#type' => 'date',
      '#title' => 'Kies einddatum',
      '#date_format' => 'd-m-Y',
      '#attributes' => [
        'min' => format_date(strtotime("+7 day", time()), 'html_date'),
        'data-inputmask-mask' => '99-99-9999',
        'class' => ['js-webform-input-mask'],
      ],
    ];

    $form['group_form']['bestelling'] = array(
      '#type' => 'checkboxes',
      '#options' => array(
        'Dit Rijksregisternummer' => 'Dit Rijksregisternummer',
        'Partner' => 'Partner',
        'Kinderen' => 'Kinderen',
        'Andere PTL' => 'Andere personen ten laste'),
      '#title' => 'Bestelling',
    );

    $form['group_form']['email'] = array(
      '#type' => 'email',
      '#title' => 'Jouw e-mailadres',
    );

    $form['group_form']['telefoon'] = array(
      '#type' => 'textfield',
      '#title' => 'Jouw telefoonnummer',
      '#maxlength' => 10,
    );

    $form['group_form']['partner_rrn'] = array(
      '#type' => 'hidden',
      '#attributes' => array('id' => 'edit-partner-rrn'),
    );
    $form['group_form']['fed'] = array(
      '#type' => 'hidden',
      '#attributes' => array('id' => 'edit-fed'),
    );

    $form['group_form']['actions'] = array(
      '#type' => 'button',
      '#value' => 'Verzenden',
      '#attributes' => array('class' => array('btn', 'btn-primary')),
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'event' => 'click',
        'progress' => array(
            'type' => 'throbber',
            'message' => 'Even geduld',
        ),
        '#validate' => array('myformname__do_validate'),
    ],

  );

    return $form;
}

This is the CallBack function:
function ajaxRijksregisternummer($form, $form_state) {
    $response = new AjaxResponse();
    $rijksregisternummer = $form_state->getValue('rijksregisternummer');
    if(ReisdocumentenForm::isCorrectRijksregisternummer($rijksregisternummer)){
        $member = '';
        if(ReisdocumentenForm::isMemberApiCall($rijksregisternummer, $member)){
          $_SESSION['formpost'] = 'rrn_ok';
          $form['group_form']['email']['#required'] = TRUE;
          $response->addCommand(new CssCommand('#controle-rrn', ['display' => 'none']));
          $hasPartner = $member['hasPartner'];
          $federatie = $member['federation'];
          $partner = '';
          if($hasPartner == 'true'){
            $partner = $member['partnerInfo'];
          }
          $response->addCommand(new InvokeCommand(NULL, 'AjaxCallBackShowAanvraag', [$hasPartner, $partner, $federatie]));
        } else {
            $markup = '

Foutmelding
Dit formulier is enkel voor leden van ons ziekenfonds.

';
            $response->addCommand(new AppendCommand('#edit-foutmeldingen', $markup));
        }
    }
    else {
        $markup = '

Foutmelding
Geen correct rijksregisternummer.

';
        $response->addCommand(new AppendCommand('#edit-foutmeldingen', $markup));
    }
    return $response;
}

Kind regards!
Comment: Where is the rest of the code?
Comment: This looks like the button doesn't have ajax javascript attached the first time you click. Check this with the browser debugging tools why the ajax library is not properly loaded and attached. If the ajax libraries and settings are not present at all then provide more info how the form is embedded in the page. Might be a defective block plugin or template.
Comment: I added the extra code.
Comment: I mean, your form build code. What is the aanvraag wrapper?
Comment: I edited my post again, and added the full buildform function. Please let me know if more info is needed.
Comment: My only guess is that "$rijksregisternummer = $form_state->getValue('rijksregisternummer');
    if(ReisdocumentenForm::isCorrectRijksregisternummer($rijksregisternummer)){" is false the first time - I think you would have to step through with xdebug to confirm that.
Comment: @Kevin, thx for the reply. It seems that the debugger doesn't even go into the ajaxRijksregisternummer function when I click on the button for the first time. All it does is a refresh of the page, but the value of the input field remains.
Comment: Hi, I think the problem was caching of the block in which the form was loaded. I disabled the caching of that block, and that seems to solve to problem.
Answer: I found the solution for my problem. It was not the form, but the block in which the form was loaded, that was the problem. I disabled the caching and now it works as expected.
/**
 * Provides a 'ReisdocumentenBlock' block.
 *
 * @Block(
 *   id = "ReisdocumentenBlock_block",
 *   admin_label = @Translation("ReisdocumentenBlock socmut"),
 *   category = @Translation("socmut")
 * )
 */
class ReisdocumentenBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     */
    public function build()
    {
        $form = \Drupal::formBuilder()->getForm('Drupal\tools\Form\ReisdocumentenForm');
        return $form;
        }
    }

    /**
     * Disable caching for ajax problem with form
     */
    public function getCacheMaxAge() {
        return 0;
    }
}

I'm still curious to know that maybee I can solve this with a certain cache context instead of disableing all the cache?


Cannot divide multiple context values in Elasticsearch watcher

Question: I have created a watch in Elasticsearch to alert me if the ratio of http errors is greater than 15% of total requests over 60 minutes.
I am using chain inputs to generate the dividend and divisor values for my ratio calculation.
In my condition I am using scripting to do the division and check if it is greater than my ratio.
However, whenever I use 2 ctx parameters to do the division, it always equals to zero.
If I play with it and only use one of ctx param, then it works fine.
It seems that we cannot use 2 ctx params in a condition.
Does anyone know how to get around this?
Below is my watch.
Thanks.
<code>{
  "trigger" : {
    "schedule" : {
      "interval" : "5m"
    }
  },
  "input" : {
    "chain":{
      "inputs": [
      {
        "first": {
          "search" : {
            "request" : {
              "indices" : [ "logstash-*" ],
              "body" : {
                "query" : {
                  "bool":{
                    "must": [
                      {
                      "match" : {"d.uri": "xxxxxxxx"}
                      },
                      {
                      "match" : {"topic": "xxxxxxxx"}
                      }
                    ],
                    "filter": {
                      "range": {
                        "@timestamp": {
                          "gte": "now-60m"
                        }
                      }
                    }
                  }
                }
              }
            },
            "extract": ["hits.total"]
          }
        }
      },
      {
        "second": {
          "search" : {
            "request" : {
              "body" : {
                "query" : {
                  "bool":{
                    "must": [
                      {
                      "match" : {"d.uri": "xxxxxxxx"}
                      },
                      {
                      "match" : {"topic": "xxxxxxxx"}
                      },
                      {
                      "match" : {"d.status": "401"}
                      }
                    ],
                    "filter": {
                      "range": {
                        "@timestamp": {
                          "gte": "now-60m"
                        }
                      }
                    }
                  }
                }
              }
            },
            "extract": ["hits.total"]
          }
        }
      }
      ]
    }
  },
  "condition" : {
    "script" : {
      "source" : "return (ctx.payload.second.hits.total / ctx.payload.first.hits.total) == 0"
    }
  }
}
</code>
Answer: The issue comes in fact from the fact that I was doing an integer division to get to a ratio in the form of 0.xx.
I reversed the operation and it is working fine.


Tcp Server deixa de "responder"

Question: É o seguinte eu tenho andado a ver 2 tutorial de como fazer um tcp Server e um tcp Client.
Eu tive a seguir tudo passo passo mas por alguma razão quando inicio o server ele deixa de responder, mas quando o client connecta ele da um update mostra e numa textbox "New Message: Hello From Client". Depois disso só se eu connectar outra vez é que ele volta a responder mas logo a seguir ele deixa de responder. Isto só aconteçe com o server.
<code> private void BtnStart_Click(object sender, EventArgs e)
    {
        TcpServerRun();
        Thread tcpserverRunThread = new Thread(new ThreadStart(TcpServerRun));

    }

    private void TcpServerRun()
    {
        TcpListener tcplistener = new TcpListener(IPAddress.Any, Convert.ToInt32(TxtBoxPort.Text));
        tcplistener.Start();
        updateUI("listening");

        while (true)
        {
            TcpClient client = tcplistener.AcceptTcpClient();
            updateUI("Connected");
            Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
            tcpHandlerThread.Start(client);
        }
    }
    private void tcpHandler(object client)
    {
        TcpClient mClient = (TcpClient)client;
        NetworkStream stream = mClient.GetStream();
        byte[] messagem = new byte[1024];
        stream.Read(messagem, 0, messagem.Length);
        updateUI("New Message: " + Encoding.ASCII.GetString(messagem));
        stream.Close();
        mClient.Close();
    }

    private void updateUI(string s)
    {
        Func<int> del = delegate()
        {
            TxtBoxLog.AppendText(s + System.Environment.NewLine);
            return 0;
        };
        Invoke(del);
    }
</code>
Answer: Seu servidor fica sem responder pois está escutando/aguardando uma nova conexão. Este método é chamado Blocking Mode das sockets.
Caso você precise efetuar alguma tarefa enquanto o servidor escuta por uma nova conexão existem duas maneiras de cumprir esta tarefa:
1) Criar uma thread separada para escutar por conexões. Desta forma a thread principal fica liberada para efetuar outras tarefas enquanto a thread de escuta fica parada em "tcplistener.AcceptTcpClient()".
2) Existe a possibilidade de você programar uma socket em modo "Non-Blocking", desta forma nenhuma chamada a API de Sockets bloqueia a sua aplicação, mas é necessário tratar os retornos para identificar quando realmente há uma conexão disponível. É a forma mais utilizada em servidores TCP, mas a sua implementação mudaria bastante em relação com o que está feito hoje.
Espero ter conseguido ajudar.

Tcp Server deixa de "responder"


Gravar sessão com JavaScript usando cookie e um botão

Question: Montei um banner, onde eu preciso que quando o usuário entrar no site e clicar no botão GOT IT ele desapareça e quando o usuário entrar novamente no site ou carregar outro link não apareça mais. Desaparecer eu consegui, mas gravar o usuário com cookie não, achei um exemplo (abaixo) mas não entendi a implementação!!!
OBS: Lembrando que nunca expira
COOKIE
// Create a cookie
$.cookie('the_cookie', 'the_value');

// Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });

// Read a cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null

// EDIT
// Attaching to a button click (jQuery 1.7+) and set cookie
$("#idOfYourButton").on("click", function () {
$.cookie('the_cookie', 'the_value', { expires: 7 });
 });

// Attaching to a button click (jQuery < 1.7) and set cookie
$("#idOfYourButton").click(function () {
    $.cookie('the_cookie', 'the_value', { expires: 7 });
});

HTML

We use cookies in order to improve your browsing experience on sugarcane.org, not to collect personal information. By continuing to use the site, you agree that it is OK. Read about our privacy policy.

        GOT IT

JAVASCRIPT

Comment: Vc quer um cookie com data de vencimento pra expirar? Se sim, quanto tempo?
Comment: não está  faltando o plugin jQuery Cookie?
Comment: @LeoCaracciolo Creio que sim, mas carregar plugin pra uma coisa tão simples que pode ser feita em JS puro acho desnecessário :D
Answer: Você pode usar localStorage que é um tipo de cookie e definir por quantas horas o banner não será exibido ao clicar no link para fechá-lo.
É preciso ocultar o banner no CSS, pois ele será exibido (ou não) na verificação do cookie:
.gotit{
   display: none;
}

E o código JavaScript:
$(document).ready(function(){

   // atribui o LS a uma vaviável
   var cookie = localStorage.getItem("banner");

   // verifica o cookie
   criaCookie();

   $(".gotit A").click(function(){
      $(".gotit").fadeToggle("slow");
      criaCookie(true);
   });

   function criaCookie(a){
      // pega a data atual
      var data = new Date();

      // variável para guardar a data atual
      var data_atual = data.valueOf();

      // adiciona 168 horas (7 dias) à data atual
      var data_pos = data.setHours(data.getHours()+168);

      if(a){
         // cria/redefine o LS com a data +168 horas
         localStorage.setItem("banner", data_pos);
      }else if(cookie < data_atual){
         // verifica se o LS é menor do que a data atual
         // ou se o LS for inexistente e mostra o banner
         $(".gotit").show();

      }

   }

});

Caso queira um cookie sem limite de tempo
O localStorage é infinito por padrão, ou seja, uma vez criado, ele só é removido se o usuário removê-lo do navegador ou pelo método localStorage.removeItem("banner").
A opção abaixo é quando clicar em GOT IT, o banner não aparecer mais no navegador onde o cookie foi criado:
$(document).ready(function(){

   // atribui o LS a uma vaviável
   var cookie = localStorage.getItem("banner");

   // verifica o cookie
   criaCookie();

   $(".gotit A").click(function(){
      $(".gotit").fadeToggle("slow");
      criaCookie(true);
   });

   function criaCookie(a){

      if(a){
         // cria o LS
         localStorage.setItem("banner", null);
      }else if(!cookie){
         $(".gotit").show();
      }

   }

});

Comment: Vou testar e ver se dá certo, mas só mais uma pergunta, se o cara deleter os cookies da máquina dele aparecer novamente né? Outra coisa, tem tempo infinito, tipo até ele apagar o cookie e entrar novamente na página?
Comment: Sim, se ele deletar vai aparecer novamente. Pode ser infinito sim. Aliás, o localStorage é infinito por padrão, mas vc pode colocar um tempo, como fiz na resposta.
Comment: legal, entãose eu deixa ali vazio é infinito?
Comment: Funcinou, mas só tem um problema tem que ser display:flex e não block tentei colocar .css('display', 'flex') junto com a linha do show mas não funcionou
Comment: Seria sem o show: `$(".gotit").css('display', 'flex') ;`. O .show() é display block.
Comment: vlw agora foi já dei uma up no seu post
Comment: Blz. Agora vc pode marcar ✔ em uma das respostas que resolveu a questão.
Answer: Sem plugin jquery cookie
$(document).ready(function(){

  if (document.cookie.indexOf("the_cookie3=") <=0) {
      $(".gotit").css('display', 'flex') ;
      //$('#gotit').show();
  }

  $(".gotit A").click(function(){
      $(".gotit").fadeToggle("slow");

        if (document.cookie.indexOf("the_cookie3=") <= 0) {
           alert("O cookie não existe vou criar");

           var date = new Date();

          //expira em 7 dias
          //date.setTime(date.getTime()+(7*24*60*60*1000));

          //expira em 30 segundos para usar como teste
          date.setTime(date.getTime()+(30*1000));

          var expires = "; expires="+date.toGMTString();
          document.cookie = "the_cookie3=the_value"+expires+"; path=/";

         }
  });
});

HTML colocar um div

Comment: Faltou só  a verificação quando abre a página, se vai mostrar ou não o banner.
Comment: vou dar um up no seu post tb pq funcionou mas só faltou o que o Sam disse ai e o tempo infinito
Comment: @Sam, certo, mas tem dificuldade em verificar se o cookie é valido?
Comment: humm... Eu não tenho experiência com esse tipo de cookie :/
Comment: opa, @Sam, eu não entendo onde o banner se encaixa, não há banner em lugar algum. Mas acho que a resposta agora atende o que vc falou no primeiro comentário
Comment: Ainda tá meio miado esse código rs... se já tem uma classe, pq colocar um id na div? E o banner vai aparecer só pra depois ser ocultado? :?/
Comment: @Sam, veja se ainda tá meio miado ou agora ficou meio latido :)
Comment: Agora ficou legal. Só esse `$('#gotit').show();` que não tem razão de existir. Mas ficou legal.
Comment: @Sam esquecimento
Answer: Talvez isso lhe ajude.

$(document).ready(function () {
$("a[href^='#']").click(function(){
    $.cookie("block", "none",{ expires: 9999999 });
    $(".gotit").css("display", "none");
});
var none = $.cookie("block");
$(".gotit").css("display", none);
});

We use cookies in order to improve your browsing experience on sugarcane.org, not to collect personal information. By continuing to use the site, you agree that it is OK. Read about our privacy policy.

    GOT IT

Comment: Você pode substituir o seguinte trecho $(".gotit").css("display", "none"); que esta dentro do CLICK, por $(".gotit").fadeOut(100); para desaparecer lentamente.