Erro na utilização do WS da Receita Federal, (Rejeição: Usar somente o namespace padrão da NF-e)

Question: Olá! Estou tentando acessar o serviço SOAP de homologação da Receita Federal para executar a consulta de status de serviço, já fiz todas as combinações possíveis (incluindo as presentes no último manual publicado) na construção de request SOAP e dados de mensagem sem sucesso, abaixo os recursos e resultados dos testes:
WSDL utilizado para a construção do cliente SOAP (origem: https://homologacao.nfe.fazenda.sp.gov.br/ws/nfestatusservico2.asmx?WSDL):
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" targetNamespace="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Serviço destinado à consulta do status do serviço prestado pelo Portal da Secretaria de Fazenda Estadual.</wsdl:documentation>
  <wsdl:types>
    <s:schema elementFormDefault="qualified" targetNamespace="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
      <s:element name="nfeDadosMsg">
        <s:complexType mixed="true">
          <s:sequence>
            <s:any />
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="nfeStatusServicoNF2Result">
        <s:complexType mixed="true">
          <s:sequence>
            <s:any />
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="nfeCabecMsg" type="tns:nfeCabecMsg" />
      <s:complexType name="nfeCabecMsg">
        <s:sequence>
          <s:element minOccurs="0" maxOccurs="1" name="cUF" type="s:string" />
          <s:element minOccurs="0" maxOccurs="1" name="versaoDados" type="s:string" />
        </s:sequence>
        <s:anyAttribute />
      </s:complexType>
    </s:schema>
  </wsdl:types>
  <wsdl:message name="nfeStatusServicoNF2Soap12In">
    <wsdl:part name="nfeDadosMsg" element="tns:nfeDadosMsg" />
  </wsdl:message>
  <wsdl:message name="nfeStatusServicoNF2Soap12Out">
    <wsdl:part name="nfeStatusServicoNF2Result" element="tns:nfeStatusServicoNF2Result" />
  </wsdl:message>
  <wsdl:message name="nfeStatusServicoNF2nfeCabecMsg">
    <wsdl:part name="nfeCabecMsg" element="tns:nfeCabecMsg" />
  </wsdl:message>
  <wsdl:portType name="NfeStatusServico2Soap12">
    <wsdl:operation name="nfeStatusServicoNF2">
      <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Consulta Status do Serviço</wsdl:documentation>
      <wsdl:input message="tns:nfeStatusServicoNF2Soap12In" />
      <wsdl:output message="tns:nfeStatusServicoNF2Soap12Out" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="NfeStatusServico2Soap12" type="tns:NfeStatusServico2Soap12">
    <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="nfeStatusServicoNF2">
      <soap12:operation soapAction="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2/nfeStatusServicoNF2" style="document" />
      <wsdl:input>
        <soap12:body use="literal" />
        <soap12:header message="tns:nfeStatusServicoNF2nfeCabecMsg" part="nfeCabecMsg" use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap12:body use="literal" />
        <soap12:header message="tns:nfeStatusServicoNF2nfeCabecMsg" part="nfeCabecMsg" use="literal" />
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="NfeStatusServico2">
    <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Serviço destinado à consulta do status do serviço prestado pelo Portal da Secretaria de Fazenda Estadual.</wsdl:documentation>
    <wsdl:port name="NfeStatusServico2Soap12" binding="tns:NfeStatusServico2Soap12">
      <soap12:address location="https://homologacao.nfe.fazenda.sp.gov.br/ws/nfestatusservico2.asmx" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

SOAP request gerado:
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:tns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2"
                 xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/">
    <soap12:Header>
        <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <versaoDados>3.10</versaoDados>
            <cUF>35</cUF>
        </nfeCabecMsg>
    </soap12:Header>
    <soap12:Body>
        <nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <consStatServ versao="3.10">
                <cUF>35</cUF>
                <tpAmb>2</tpAmb>
                <xServ>STATUS</xServ>
            </consStatServ>
        </nfeDadosMsg>
    </soap12:Body>
</soap12:Envelope>

XML da mensagem:
<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
    <consStatServ versao="3.10">
        <cUF>35</cUF>
        <tpAmb>2</tpAmb>
        <xServ>STATUS</xServ>
    </consStatServ>
</nfeDadosMsg>

XML de resposta do request:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>
        <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <cUF>35</cUF>
            <versaoDados>3.10</versaoDados>
        </nfeCabecMsg>
    </soap:Header>
    <soap:Body>
        <nfeStatusServicoNF2Result xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <retConsStatServ versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
                <tpAmb>2</tpAmb>
                <verAplic>SP_NFE_PL_008i2</verAplic>
                <cStat>587</cStat>
                <xMotivo>Rejeição: Usar somente o namespace padrão da NF-e</xMotivo>
                <cUF>35</cUF>
                <dhRecbto>0001-01-01T00:00:00+00:00</dhRecbto>
            </retConsStatServ>
        </nfeStatusServicoNF2Result>
    </soap:Body>
</soap:Envelope>

Nas tentativas de resolver o problema, inferindo que os namespaces adicionais no evelope SOAP fossem a causa, construi o request com os mesmos namespaces da resposta, alterando de:
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:tns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2"
                 xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/">

para:
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema">

Mas não obtive sucesso. Enfim, se alguém aqui já enfrentou este problema e puder compartilhar a solução seria ótimo!
Tecnologias utilizadas:
NodeJS
node-soap (github.com/vpulim/node-soap)
Código da chamada para o WS:
        var url = __server_settings.nfe.wsdl[__server_settings.nfe.environments.STAGING].service_status;

        var options = {
            envelopeKey: 'soap12',
            forceSoap12Headers: true
        }

        soap.createClient(url, options, function(err, client) {
            pfx_utils.extractPfxInfo(path.resolve(__server_settings.paths.CERTIFICATES, 'certificate.pfx'), '<password>', function (err, results, key, certificate) {
                if (err == null) {

                    client.setSecurity(new soap.ClientSSLSecurity(key, certificate));

                    var header = {
                        nfeCabecMsg: {
                            attributes: {
                                xmlns: 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2'
                            },
                            versaoDados: '3.10',
                            cUF: 35
                        }
                    };
                    client.addSoapHeader(header);

                    var data = {
                        consStatServ: {
                            attributes: {
                                versao: '3.10',
                                xmlns: 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2'
                            },
                            cUF: 35,
                            tpAmb: 2,
                            xServ: 'STATUS'
                        }
                    }

                    client.nfeStatusServicoNF2(data, function(err, result) {
                        console.log(result);
                    });
                } else {
                    console.log(__('Error extracting data from certificate!'));
                }
            });
        });

Grato!
Paulo Eduardo Ferreira Ventura
Answer: Finalmente resolvido, o XML correto:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:tns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2"
               xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/">
    <soap:Header>
        <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <cUF>35</cUF>
            <versaoDados>3.10</versaoDados>
        </nfeCabecMsg>
    </soap:Header>
    <soap:Body>
        <nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <consStatServ versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
                <tpAmb>2</tpAmb>
                <cUF>35</cUF>
                <xServ>STATUS</xServ>
            </consStatServ>
        </nfeDadosMsg>
    </soap:Body>
</soap:Envelope>

XML INCORRETO:
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:tns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2"
                 xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/">
    <soap12:Header>
        <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <versaoDados>3.10</versaoDados>
            <cUF>35</cUF>
        </nfeCabecMsg>
    </soap12:Header>
    <soap12:Body>
        <nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
            <consStatServ versao="3.10">
                <cUF>35</cUF>
                <tpAmb>2</tpAmb>
                <xServ>STATUS</xServ>
            </consStatServ>
        </nfeDadosMsg>
    </soap12:Body>
</soap12:Envelope>

O que fez com que a requisição falhasse foram a ordem das propriedades dispostas no cabeçalho do envelope SOAP, as ordens das propriedades área de dados da mensagem e o namespace da tag consStatServ que não havia sido informado. O erro apresentado me guiou a procurar o problema relacionando-o apenas aos namespaces (Rejeição: Usar somente o namespace padrão da NF-e), e foi reclamando sobre a frustração com um colega de trabalho que fui atentado a verificar a ordem das propriedades nas áreas de dados da requisição SOAP.
Cabeçalho SOAP errôneo:
<soap:Header>
    <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
        <cUF>35</cUF>
        <versaoDados>3.10</versaoDados>
    </nfeCabecMsg>
</soap:Header>

Cabeçalho SOAP CORRETO:
<soap12:Header>
    <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
        <versaoDados>3.10</versaoDados>
        <cUF>35</cUF>
    </nfeCabecMsg>
</soap12:Header>

Dados de mensagem errônea:
<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
    <consStatServ versao="3.10">
        <cUF>35</cUF>
        <tpAmb>2</tpAmb>
        <xServ>STATUS</xServ>
    </consStatServ>
</nfeDadosMsg>

Dados da mensagem CORRETA:
<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
    <consStatServ versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
        <tpAmb>2</tpAmb>
        <cUF>35</cUF>
        <xServ>STATUS</xServ>
    </consStatServ>
</nfeDadosMsg>

Eu poderia ter validado o XML utilizando o esquema fornecido pela SEFAZ, mas como o request é construído dinamicamente pela API que estou usando isso não foi possível.
The End! E que ninguém mais no mundo sofra por posições de elementos em um XML!
SOAP XML Property Order is Important


Is taking the median of a set of percentages statistically sound?

Question: I have several sets of data, unfortunately the data comes to me in a "summary" form. My job is to consolidate the several data sources into one general summary. I'm currently using the median to summarise the data, but I don't know if this is statistically sound. Here's a description of my problem:
There are $N_P$ samples, each with varying sample sizes, but all from a single population. Neither the sample size or the standard variation are known. Each sample can be divided into $N_Q$ disjoint groups (or qualities). From each sample, the only data that is known is what percent of the sample falls within a group (or category). For example, population $A$ contains, $x\%$ of $a$, $y\%$ of $b$ and $z\%$ of $c$.
The different samples are not disjoint, so a single item might be in several of the samples; but I don't know how much overlapping there is. There are 5-8 different samples with 5-7 categories. An example (smaller) table is the following.
<code>            cat. a    cat. b    cat. c
sample A    47.34%    30.05%    11.92%
sample B    41.60%    29.90%    11.90%
sample c    47.74%    29.67%    12.69%
--------    ------    ------    ------
median      47.34%    29.90%    11.92%
</code>
Now is it statistically sound to create this "median" summary, which takes each group from the different samples and finds the median? Maybe I should be using the mean? The problem I'm seeing is the "median sample" usually sums to less than 100%, even though the percentages from each sample sum to 100%. Should this matter?
<code>Sample sizes: 100k - 100m
Population size: ~1 billion
</code>
Comment: do you know the sample sizes... the range of them?  Small sample sizes wreak havoc on the mean... moreso than the median.
Comment: the sample sizes range from 1-100 million and the population size is upwards to 1 billion. But I have no knowledge of how disjoint the samples are from the total population.
Answer: What you are doing does not makes sense if your goal is to categorize what proportion of the entire population (sample A + sample B + sample C) is in category a, b, and c. Consider the following contingency table:
<code>   a  b  c             a    b    c
A  8; 1; 1         A  .8;  .1;  .1
B  7; 2; 1         B  .7;  .2;  .1
C  1; 13; 16       C  .03; .43; .53
</code>
Then, for example, the median of the category a probabilities is 0.7 and the mean is 0.51, but only 16/50 = 0.32 of the all the observations are in column a. Likewise, the median of the category c probabilities would be 0.1, but only 0.36 of the observations are in column c. Does the "median summary" you propose tell you anything meaningful in a situation such as this one? Unless you have the marginal counts of either the samples or the categories, or you are willing to make some assumptions about them, I don't think there is a whole lot you can do in this case.
Do you have any specific goals in mind? Also, how many categories and samples do you have?
Edit: Your sample/population phrasing is slightly confusing. It's better to say you "have 3 samples, each which be sub-divided into 3 categories a,b, and c." The phrase "sample population" is troublesome, as is your reference to two different "populations."
Comment: ok, what I'm really interested is if it's statistically sound to include the median row in the summary table at http://en.wikipedia.org/wiki/Usage_share_of_web_browsers I can go into more details if you want.
Comment: In that case you should be okay. You can consider each of the samples A,B,C to be experimental units, and each of the categories a,b,c to be some measurement taken on each sample (with the restriction the measurements sum to 1.) This could be helpful when you have a lot of samples, not so much when you have 3 or 5.
Comment: It's amusing that that site calculates the median (and goes to the trouble of labeling it as such and suggesting that they know the difference between the mean and the median) on just two points of data which results, actually, in the mean of the two values!
Comment: The table with 2 data sources, is one of the things I'm trying to correct. Some of the editors of the page are handling the data in a way that's statistically unsound, or at least I'm trying to prove that.


print individual field inside views-view.tpl.php

Question: I need to theme my view inside views template. Inside custom views-view.tpl.php template I can add individual fields inside loop:
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
//after a loop I can add any other field for custom theming like so:
<?php print $item['myfield2']; ?>

Question: How can I add another field before the loop is executed? I tried this:
<?php print $item['myfield3']; ?>
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

But the field3 is not rendered because the $item is not defined, I think.
I am not php programmer so I came up with a dumb workaround
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php endforeach; ?>
<?php print $item['myfield3']; ?>
//field is rendered
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

What is the correct way of displaying an individual field without putting it inside foreach loop?
Thank you
Answer: You are wise to admit it before someone else points it out:  "I am not php programmer." ;)  This is a pure PHP problem, having very little to do with Drupal.
Your foreach() loop defines the variables $delta and $item.  Unlike some other languages, they are still in scope when the loop finishes, keeping the values they had at the end of the loop.
You could do something like this (untested):
<?php
  $first_item = reset($view->style_plugin->rendered_fields);
  $last_item = end($view->style_plugin->rendered_fields);
  print $first_item['myfield1'];
  pring $last_item['myfield2'];
?>

After the foreach() loop, $item would be the same as $last_item.
The PHP docs are pretty good:  arrays
and array functions.


Skipping the sliding window

Question: Given [1,2,3,4,5,6,7,8,9,10], to get a sliding window of 3 items at a time to get:
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

From https://stackoverflow.com/q/42220614/610569, a sliding window of a sequence can be achieved with:
def per_window(sequence, n=1):
    """
    Returns a sliding window.
    From https://stackoverflow.com/q/42220614/610569
        >>> list(per_window([1,2,3,4], n=2))
        [(1, 2), (2, 3), (3, 4)]
        >>> list(per_window([1,2,3,4], n=3))
        [(1, 2, 3), (2, 3, 4)]
    """
    start, stop = 0, n
    seq = list(sequence)
    while stop <= len(seq):
        yield tuple(seq[start:stop])
        start += 1
        stop += 1

But if there's some constraints that I want to put in the sliding window, and I only want to get the windows where a certain element exist.
Let's say I only want the windows that contains 4, I could something like:
>>> [window for window in per_window(x, 3) if 4 in window]
[((2, 3, 4), (3, 4, 5), (4,5,6)]

But somehow the loop still has to process through the whole list of windows and check through the if conditions.
I could do some skipping by looking for the positions of 4 and limit the input to the per_window, e.g.
# Input sequence.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Window size.
n = 3
# Constraint.
c = 4
# Set the index to 0
i = 0
while i < len(x)-n:
    i = x.index(4, i)
    # First window where the constraint is met.
    left = i - (n-1)
    if left > 0:
        print (list(per_window(x[left:i], 3)))
    right = i + n
    if right < len(x):
        print (list(per_window(x[i:right], 3)))
    i = right

(Note the code above with the ifs don't work =( )
Instead of finding the index outside of the per_window function, is there another way to add such a constraint in the per_window function?

EDITED
After reading @RaymondHettinger's answer:
def skipping_window(sequence, target, n=3):
    """
    Return a sliding window with a constraint to check that
    target is inside the window.
    From https://stackoverflow.com/q/43626525/610569
    """
    start, stop = 0, n
    seq = list(sequence)
    while stop <= len(seq):
        subseq = seq[start:stop]
        if target in subseq:
            yield tuple(seq[start:stop])
        start += 1
        stop += 1
        # Fast forwarding the start.
        # Find the next window which contains the target.
        try:
            # `seq.index(target, start) - (n-1)` would be the next
            # window where the constraint is met.
            start = max(seq.index(target, start) - (n-1), start)
            stop = start + n
        except ValueError:
            break

[out]:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(skipping_window(x, 4, 3))
[(2, 3, 4), (3, 4, 5), (4, 5, 6)]

Answer:
Instead of finding the index outside of the per_window function, is there another way to add such a constraint in the per_window function?

Yes, you can add the condition just before the yield:
def per_window(sequence, target, n=1):
    start, stop = 0, n
    seq = list(sequence)
    while stop <= len(seq):
        subseq = seq[start:stop]
        if target in subseq:
            yield tuple(subseq)
        start += 1
        stop += 1

Comment: The answer given matches the question asked.  Also, it was clear that you already knew the path to further optimization by using *index()* to rapidly advance to the next possible matching subsequence.
Comment: Thanks @RaymondHettinger! Just need to confirm that that the "fast-forward" optimization isn't included. I was thinking whether I missed something =)
Comment: But that would still loop through every possible window, just that it doesn't yield if it fails the constraint, no? =(

Skipping the sliding window


redirect to profile page after registering

Question: I am making a program in where a form will be submitted, then the user will be redirected to the profile page. If one of the items is blank, the form will restart. However, the comment section  & password of the registration is not displayed in the profile page, and that the registration does not restart when one of the items is left blank. Furthermore, the gender should also be included in display in the profile page, however, i have no idea how, since that it is a radio option.
Is there a typo in it? And how do I display the information that I haven't displayed? Thanks
Code (registration):
<!DOCTYPE html>

        <form action="Profilepage.html">
            <fieldset form="signup" width=10px; style=border-style:solid; color : "black"; border-width:1px; padding:10px; text-align:left;">
                <legend>Register: </legend>

                *First Name:
                <input type="text" id="name1" name="name1"  required/>

                *Last Name:
                <input type="text" id="name2" name="name2"  required/>

*Your Gender:

                <input type="radio" id="male" name="gender" value="Male"  required/>
                Male

                <input type="radio" id="female" name="gender" value="Female"  required/>
                Female

                <input type="radio" id="prefernotsay" name="gender" value="Prefer not say"  required/>
                Prefer Not Say

                *Email Address:
                <input type="email" id="email" name="email"  required/>

                #Number:
                <input type="text" id="number" name="Number"  required/>

                *Your Password:
                <input type="password" id="pword" name="pword" required/>

                *Reasons for registering:

                <input type="textarea" textarea id="tArea" name="cmmnts" rows="4" cols="50" required/> </textarea>

                <input type="submit" value="Submit" onclick="passvalues()"/>

            </fieldset>
        </form>

Code (Profilepage):
<!DOCTYPE html>

First Name:

Last Name:

Email:

Why I support this campaign:

Comment: Pls read [How to Ask](https://stackoverflow.com/help/how-to-ask). You need to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). No one is going to sit and reads your whole code to debug it. You also need to give a title of the question which summarises the whole question is one line and **it should be in question format**.
Answer: **home.html**

    <!DOCTYPE html>

            <form action="profile.html">

                <fieldset form="signup" width=10px; style="border-style:solid; color : black; border-width:1px; padding:10px; text-align:left;">
                    <legend>Register: </legend>

                    *First Name:
                    <input type="text" id="name1" name="name1"  required/>

                    *Last Name:
                    <input type="text" id="name2" name="name2"  required/>

*Your Gender:

                    <input type="radio" id="radio" name="gender" value="Male"  required/>
                    Male

                    <input type="radio" id="radio" name="gender" value="Female"  required/>
                    Female

                    <input type="radio" id="radio" name="gender" value="Prefer not say"  required/>
                    Prefer Not Say

                    *Email Address:
                    <input type="email" id="email" name="email"  required/>

                    #Number:
                    <input type="text" id="number" name="Number"  required/>

                    *Your Password:
                    <input type="password" id="pword" name="pword" required/>

                    *Reasons for registering:

                    <input type="textarea" textarea id="tArea" name="cmmnts" rows="4" cols="50" required/> </textarea>

                    <input type="submit" value="Submit" onclick="passvalues()"/>

                </fieldset>
            </form>

**profile.hrml**

    <!DOCTYPE html>

First Name:

Last Name:

Email:

Why I support this campaign:

see what is the different between this code and your code I have set some comments there you have missed small parts in your code (you have done same mistakes in profile.html)
as well as dont use two body tag and you haven't close one body tag too
And if you want to get radio values you can simply use following code
   var radio= document.getElementById("myRadio").value

just make id="myRadio" use same ID for all the radio button then above code will get the clicked radio value
I have separate the code home.html and profile.html
You can test this creating two separate html file in same folder . Then copy and past the code to home.html and profile.html open the home.html in browser. after you input the value your page will be redirect to profile.html with the data that you input.
Answer: You have two  in your Code (registration),and your  can put in the head like

make sure that your html tags in your body like

    xxx

and if you want get your radio select result,try
let gender = ''
document.getElementsByTagName("gender").forEach((item)=>{
if(item.checked){
 gender = item.value;
});


How to add Organic Groups after Site has been created

Question: My site allows people from a certain class to upload their pictures on the website. It has various content types and views made but and I would like to install the Organic Groups module to allow multiple classes from my school to upload images.
Can I do that now or do I need to re-create the site from scratch?
Answer: It should not be necessary to re-create the whole site from scratch. After installing Organic Groups, you can mark an existing content type as "Group Content" if you want the nodes of that type to belong to a group:

Go to admin/structure/types.
Click on the "Edit" link next to the type you want to modify.
In the Organic groups tab, check the Group content checkbox. It will create a Groups audience field in your content type.

After that, you will need to assign each node to the appropriate group, in the Groups audience field.


Some IP addresses are unreachable due to invalid route

Question: I want to connect to remote machines. The problem is that I can connect to every machine except one. After some invertigation I found that problem is in route. Here is example:
PS C:\Users\Alex> tracert 172.17.56.66

Tracing route to 172.17.56.66 over a maximum of 30 hops

  1    31 ms     9 ms    12 ms  10.19.64.1
  2     9 ms    14 ms     8 ms  172.17.56.66

Trace complete.
PS C:\Users\Alex> tracert 172.17.56.68

Tracing route to 172.17.56.68 over a maximum of 30 hops

  1    13 ms     7 ms     7 ms  10.19.64.1
  2    10 ms     5 ms     4 ms  172.17.56.68

Trace complete.
PS C:\Users\Alex> tracert 172.17.56.70

Tracing route to 172.17.56.70 over a maximum of 30 hops

  1    <1 ms    <1 ms    <1 ms  192.168.0.1
  2     8 ms    41 ms     7 ms  18.104.22.168
  3    96 ms     1 ms     1 ms  192.168.1.1
  4     1 ms    <1 ms    <1 ms  10.90.40.41
  5     1 ms     1 ms     1 ms  10.90.40.34
  6     1 ms     1 ms     1 ms  10.90.40.32
  7     3 ms     8 ms     2 ms  10.90.35.80
  8     *        *     10.90.35.78  reports: Destination net unreachable.

Trace complete.

I don't know why it handles this IP differently. Here is my route print.
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.0.1    192.168.0.239     35
     10.19.84.212  255.255.255.252         On-link      10.19.84.214    311
     10.19.84.214  255.255.255.255         On-link      10.19.84.214    311
     10.19.84.215  255.255.255.255         On-link      10.19.84.214    311
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    331
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    331
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    331
     172.17.56.65  255.255.255.255     10.19.84.213     10.19.84.214     55
     172.17.56.66  255.255.255.255     10.19.84.213     10.19.84.214     55
     172.17.56.67  255.255.255.255     10.19.84.213     10.19.84.214     55
     172.17.56.68  255.255.255.255     10.19.84.213     10.19.84.214     55
     172.17.56.69  255.255.255.255     10.19.84.213     10.19.84.214     55
     172.17.56.72  255.255.255.255     10.19.84.213     10.19.84.214     55
     172.17.56.73  255.255.255.255     10.19.84.213     10.19.84.214     55
      192.168.0.0    255.255.255.0         On-link     192.168.0.239    291
    192.168.0.239  255.255.255.255         On-link     192.168.0.239    291
    192.168.0.255  255.255.255.255         On-link     192.168.0.239    291
        184.108.40.206        240.0.0.0         On-link         127.0.0.1    331
        184.108.40.206        240.0.0.0         On-link      10.19.84.214    311
        18.104.22.168        240.0.0.0         On-link     192.168.0.239    291
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    331
  255.255.255.255  255.255.255.255         On-link      10.19.84.214    311
  255.255.255.255  255.255.255.255         On-link     192.168.0.239    291
===========================================================================
Persistent Routes:
  None

So after I added it statically (based on 66 and 68 gateway)
route ADD -p 172.17.56.70 MASK 255.255.255.255 10.19.84.213

It worked. But why does gateway detect automatically in other cases, but in this one I should hardcode it?
Comment: I see you changed your question already, but I was able to see that somehow it picked up the wrong route in the first place. I didn't happen to notice if it was part of the static route or not, but the route looked wrong as it didn't match the other `172.17.56.0/24` routes. How it got that way? Not sure.
Comment: The routes on your local machine aren't relevant. It is the next machine, 10.19.64.1, which is routing the packets. You need to look at its routing table.
Comment: @Andrew sorry for inconvinience, I have just found my mistake myself and fixed it to make easier to determine real reason. I don't know but thanks to Abu I found that system says that these routes have been added manually while I'm sure I didn't do anything like it. Must examine my programs, for example I'm using OpenVPN and it cause it..
Answer: Your default Gateway is 192.168.0.1. So, if there is no Static route, the traffic will go over the default gateway, except for directly connected Networks. In your example above for 172.17.56.70, you want to send the traffic to a different gateway 10.19.84.213. The only way to do this is to add Static route. This is normal behavior.
Comment: You can run "netsh interface ipv4 show route" and check the Column "Type". If it says manual for 172.17.56.68, then it was done Manually.
Comment: But I didn't add any static route to `172.17.56.68`, why then it behaves differently?
Comment: If you look at the output of 'route print', it shows a Static Route for 172.17.56.68
Comment: Well, you are right so I mark an answer. However, I'm still confused why it worked automatically for one address but didn't for another. I didn't touch routes in any way, but there are static routes for 68 and they weren't for 70 until I added manually persistent route. Looks weird.
Comment: You are right, it says "manual". But how can I get source of this `manual` addition? Because I just rebooted my PC and my static route has just dissapeared while these guys are alive.
Comment: Can you share updated route table and ping?
Comment: Sorry, but I have just added this route back manually. I have also ran a script that search for `172.17.56.68` in all files on my system, if it is added via some sort of config I should find it. It may take several hours, so I'm back tommorow with results.
Comment: Well, I don't know. Here is complete list of files that contains `68` IP on my PC `C:\Users\Alex\.bash_history`
`C:\Users\Alex\.ssh\known_hosts`
`C:\Program Files\Git\etc\profile.d\aliases.sh`
`C:\Users\Alex\AppData\Local\Google\Chrome\User Data\Default\Preferences`
`C:\Users\Alex\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt`. Nothing like config or something... Route print that you demanded: [https://gist.github.com/Pzixel/c40dc44190a473b393b28615f9a1d925](https://gist.github.com/Pzixel/c40dc44190a473b393b28615f9a1d925)
Comment: Doesn't look like any of those are adding route. You can make it persistent if you don't want them to be removed after reboot.
Comment: it's seems that there is some remote server which configures routes on my PC. It should be OpenVPN. I considered that it have to be configured locally, but it seems that it persist its config remotely. It exaplains why I didn't find anything on my machine.
Comment: I should have asked this before, so this only happens when you connect to VPN?
Comment: I figured out that this routes appears when I connect to VPN only. So the answer is yes, I guess.
Comment: That is normal behavior of VPN clients, they add routes.
Comment: Yep, the question was why it does add it for some IPs and doesn't for others. And the answer seems to be "because VPN server is configured so". But I was expecting that it should be configured somewhere locally. So when I didn't find it i was so surprised that I asked this question.


How to get file content in java

Question: My question is how to get file content in class File (java)
for example, I have :
File folder = new File("BitTorrent");
for (final File SubFile : folder.listFiles()) {
    if (!SubFile.isDirectory()) {
        **// HOW TO READ ALL THE CONTENT OF SUBFILE WITHOUT USING ITS PATH.**
    }
}

What I mean is that are there any get method can do this. We can use these codes below instead, but I don't like that
Path p = Paths.get(file.getAbsolutePath());
byte[] fileArray = Files.readAllBytes(p);

Thanks for your help in advance.
Comment: Are we supposed to suggest other means to read files until there is one "you like"? Or will you explain what you actually want to achieve, and why you "don't like that"?
Answer: Without using the path of the file as here :
Path p = Paths.get(file.getAbsolutePath());
byte[] fileArray = Files.readAllBytes(p);

you can open a DataInputStream and read all the content in a byte array :
File folder = new File("BitTorrent");
for (final File SubFile : folder.listFiles()) {
    if (!SubFile.isDirectory()) {
        **// HOW TO READ ALL THE CONTENT OF SUBFILE WITHOUT USING ITS PATH.**
         byte[] bytes= new byte[(int)SubFile.length()];
         DataInputStream dataIs = new DataInputStream(new FileInputStream(SubFile));
         dataIs.readFully(bytes);
         // here bytes has the content
    }
}

How to get file content in java


Php and Ajax not showing results from SQL

Question: I created proba.html file, getuser.php, database called: 'mobilni', and table called: 'imena'. What is wrong with code, it is not showing results from table, only blank?
proba.html code:

<form>
<select name="okrug" onchange="showUser(this.value)">
  <option value="">Okrug:</option>
  <option value="Raski">Raski</option>
  <option value="Banatski">Banatski</option>
  <option value="Backi">Backi</option>
  <option value="Beogradski">Beogradski</option>
  </select>
</form>

Person info will be listed here...

getuser.php code:
<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','','mobilni');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"mobilni");
$sql="SELECT * FROM imena WHERE Okrug = '".$q."'";
$result = mysqli_query($con,$sql);

echo "

Ime
Okrug
Telefon

";
while($row = mysqli_fetch_array($result)) {
    echo "
";
    echo "" . $row['Ime'] . "	";
    echo "" . $row['Okrug'] . "	";
    echo "" . $row['Telefon'] . "	";
    echo "
";
}
echo "
";
mysqli_close($con);
?>

Comment: Please make some debugging effort - read logs, var_dump vars etc. No one will do it for you.
Comment: I tried that, but there is no any bug in logs.
Comment: Have you tested your query?, does it even return something?, try to debug and you'll narrow it down easily.
Comment: Try alert(str) in your ajax function. and echo $q; in your php, If you're getting these values then, check your sql query
Answer: Instead of
$q = intval($_GET['q']);

Try this:
$q = $_GET['q'];

See, if that helps.


Can Spearman rank correlation be extended to three dimensions?

Question: Why can we not define a 3D rank correlation as the elongation of the cloud as a proportion of the multidimensional variance as an extension of the 2D rank correlation case as suggested by @gung?
There are several attempted answers to a related question in Spearman's Rank-Order Correlation for higher dimensions. However, those answers appear to skirt the issue. This question is a cleanup and an attempt to collate other questions. Please hold off on changing this question at least until the matter is clarified. If this question is a duplicate, then the two questions it refers to are also duplicates. There have been several other questions posted on this site that could be answered by extending Spearman's rank correlation to 3D:
correlation among variable per observation
Aggregation of Correlations Coefficients (Spearman)
I do not see why it could not be done. Has it? If not, would someone please extend Spearman's rank to 3D, please?
Comment: Until you stipulate what property of multidimensional data you are attempting to characterize, this question appears to be too vague to be answerable.
Comment: Although I voted to reopen, I have no clue what you might mean by "the most logical": that looks like a subjective criterion.  Once again I would request that you attempt to describe what property of the distribution you are hoping to characterize.
Comment: Possible duplicate of [Spearman's Rank-Order Correlation for higher dimensions](http://stats.stackexchange.com/questions/189349/spearmans-rank-order-correlation-for-higher-dimensions)
Comment: Like @NickCox, I'm not sure what you're asking for here. Consider a simpler situation. Say you have multivariate normal data in 3D, what would you want to say then? Some people might want to know the 3x3 variance-covariance matrix, some might want to know the elongation of the cloud as the proportion of the multidimesional variance that is accounted for by the 1st principle component (ie, 1st eigenvalue / 3), some might want to know the determinant, etc. What is it you would want & why, then we can think of how to connect that to this context.
Comment: Unfortunately we don't find these questions to be precise. Each asks for an extension. The comments are cycling round and round quite what kind of extension you have in mind. For example, a fairly trivial answer is that you can easily have a matrix of Spearman correlations.
Comment: Sorry, but that doesn't seem to answer my question. If Spearman rank applies to any reduction of three variables, then it's equivalent to a single rank correlation between two beasts of some kind. Otherwise the question is just asking for a unicorn. Note that any distinction between dependent and independent is alien to the idea of correlation.
Comment: I just read the 2 linked Qs. Unfortunately, they don't help me understand what you're after. What I'm trying to find out is what kind of animal your possible $r_{3D}$ is. Without that, I don't see how this can be answered.
Comment: Like some of the other commenters, it is not clear to me what property of the joint distribution of 3 (or more) variates you are looking to characterize, but you might be looking for the notion of [conditional or partial (rank) correlation](https://www.jstor.org/stable/2333539).
Comment: I am not saying that. But covariance in 3D is a matrix not a scalar and I don't understand what kind of reduction to a scalar you seek.
Comment: I would edit that information (prominently) into the text of your question. I agree that that is the simplest & clearest possibility. However, I'm not sure if it would actually work (or at least is guaranteed to work) for Spearman's correlations b/c of the nonlinear transformation into ranks. W/ a small number of ordinal categories, it certainly does work for polychoric correlations, though--if you are willing to assume latent normality.
Comment: What is the correlation between?
Comment: @NickCox Between triple rankings, as per the links provided, or really among any other triple. Obviously, one can provide two independent variables to predict an dependent one in different three ways, and there may be other ways to understand this, for example, one dependent variable to predict two independent variables in three different ways, or reduce the dimensionality between either two dependent variables or two independent variables in six different ways.
Comment: @NickCox What might be best would be the most self-consistent way of obtaining a single rank correlation, or perhaps three rank correlations, if not self-consistent.
Comment: @NickCox When correlation refers to standardized covariance, which variable is conversationally considered to be dependent is arbitrary, irrelevant and not a detractor, as it changes nothing. So, you are saying that covariance cannot be standardized in 3D, do tell us why that is again?
Comment: Covariance in 2D is a matrix, and [extends logically to higher dimensions](https://en.wikipedia.org/wiki/Covariance_matrix).
Comment: @NickCox I am seeking 3D normalized covariance, see added formula in question above which is not meant to be correct, just to provide an indication that there is nothing extraordinary about adding a variable.
Comment: @gung There are two questions linked to in the text of my question. They are asking for something. What would you have me do?
Comment: @gung I sympathize, same problem I had. I would think that the elongation of the cloud as a proportion of the multidimensional variance would be the most logical extension. The other answers, for example, the matrix of Spearman's correlations would certainly be of interest as well. I think the problem here is that people asking these questions want *something* and we can give them something. If they knew exactly what they wanted, they would ask. I am rather fond of the first approach above, seems most interesting.
Comment: @whuber Question made more precise. I do not see that question answered elsewhere, but, do correct me if I am wrong.
Comment: Even in its extended form, it is unclear to me why this question is distinct from http://stats.stackexchange.com/questions/189349/spearmans-rank-order-correlation-for-higher-dimensions ... anything being discussed in the comments here as a possible answer would appear to be just as good an answer there, which suggests the threads are duplicate
Comment: @Silverfish For http://stats.stackexchange.com/questions/189349/spearmans-rank-order-correlation-for-higher-dimensions it is true that the answers are in the correct vein. The question here is clearly 3D, and is is distinct. That other questioner offers, "... since I cannot simply fix y and look upon it as data of the form $(x_i,z_i)$," which is not an actual 3D question. The other elephant in the room are the linked duplicate questions, which you and the other closure voters ignore. Respond to that issue constructively or withdraw your incomplete closure objection.
Comment: @Carl It seems to me (though clearly you see it otherwise) that this quote doesn't so much render the other question "not an actual 3D question", as explain why the OP on that question has resorted to seeking a 3D analogue to Spearman's rather than stuck to 2D. The heart of that question still seems to be "My question: is it also possible extend this to higher dimensions?"
Comment: @Silverfish I am trying to organize questions and answers. Before we dispose of this question, please answer as to "What should be done with the other questions?"
Comment: The question should be clear in edited form, vote to reopen and do answer what to do with the other, much less clear questions, without picking this question out of a cloud of clouded others, please.
Comment: @whuber Many thanks. "the most logical" deleted, however, the sentence now lacks motivation. I considered saying something like "the most self-consistent extension to the three dimensional case," which is what I meant by most logical, but, given that application contexts can be different, the mathematically obvious is not always the applicable case.
Comment: @tchakravarty I was thinking more along the lines of [total correlation](https://en.wikipedia.org/wiki/Total_correlation). A single correlation for the 3D case.
Comment: +1 Carl I like that you are trying to inquire after a challenging idea with this question. I think that the clarifications requested by the folks in the commentary are useful, but I like that you are just trying to push into new idea realm, and think we should have room for this on CV.
Answer: Since Spearman correlation in 2D is equivalent to the Pearson correlation between the ranks, and since the $R^2$ is (well, kind-of) the generalization of the Pearson correlation to multiple regression, maybe we can use the $R^2$ of the ranks?
I tried playing with this a bit in R, not sure I can come with any conclusive results.
Remember that Spearman will only find monotonic relations, so the function probably must also be monotonic in each dimension, e.g. $e^{x+y}$.
Here's a code example:
<code>x1 = seq(0.01, 10, 0.1)
x2 = seq(0.01, 10, 0.1)
grid <- expand.grid(x1=x1, x2=x2)
y = exp((grid$x1)/2 + (grid$x2)/2) + rnorm(length(grid$x1), 0, 100)

library(plotly)
z <- y2
dim(z) <- c(100, 100)
fig <- plot_ly(x= ~ x1, y= ~ x2, z = ~ z)
fig <- fig %>% add_surface()
fig
</code>

<code># Regular linear-regression
mod1 = lm(y ~ grid$x1 + grid$x2)
summary(mod1)$r.squared # [1] 0.4158116

# Linear regression of the ranks

n   <- length(grid$x1)
rx1 <- rank(grid$x1)
rx2 <- rank(grid$x2)
ry  <- rank(y2)
mod2 = lm(ry ~ rx1 + rx2)
summary(mod2)$r.squared  # [1] 0.7485
</code>
Though Spearman seems to also be worse, if I increase the variance from 100 to 1000 (0.328 in the regular $R^2$, 0.2547 in the $R^2$ of the ranks).
If I use a non monotonic function, e.g. $\sin(\sqrt{x^2+y^2})$ even without noise

both measures seem to be around zero.
I'm reading now a paper by Chatterjee, "A New Coefficient of Correlation", where he introduces an improved rank correlation he denotes as $\xi$. He mentions that "Multivariate measures of dependence and conditional dependence inspired by ξn are now available in the preprint (Azadkia and Chatterjee 2019)". So you might want to check these out.
Comment: OK, will look. Rs and monotonicity are not strict. For example, even if one starts with a monotonic function, in simulation noisy results may not be monotonic. True enough, the more monotonic the better.
Comment: Looks like adjacent differences are used as a noise estimate. Interesting.


Can a negative power series have zeros in the unit dics?

Question: As title say, suppose we have the expression $\sum_{n=0}^{\infty} a_{n}z^{-n}$ as an antianalytic function in $\mathbb{D}$.
Can it have zeros there? My first tought is now since these would be poles of the analytic function $\sum_{n=0}^{\infty} a_{n}z^{n}$
Comment: I do not understand clearly your question. Try $2-1/z$
Comment: You seem to think of $$\left(\sum_{n=0}^∞a_nz^{-n}\right)^{-1}$$ to exchange roots for poles.
Comment: This series, in its domain of convergence (which will be the exterior of a disk, possibly along with part of the boundary), is simply an ordinary analytic function; there is no notion of "antianalytic" in this regard. There is a notion of "antianalytic" but it has nothing to do with this post; an [antianalytic function](https://en.wikipedia.org/wiki/Antiholomorphic_function) is  a function $f$ such that $f(\bar{z})$ is analytic in $z$.
Comment: More generally, $\sum_{n=-\infty}^{\infty} a_n z^n$, if convergent, will converge on the interior of an annulus centered at the origin (possibly along with parts of its boundary), and be analytic there.
Comment: An analytic function in $\mathbb D$ does not have such an expansion, unless $a_n = 0$ for $n>0.$
Answer: This is the same as asking if
$$
\sum_n a_nw^n
$$
can have roots outside the unit disk. There are numerous standard power series, for instance the sine series, which show that indeed that is possible.


User with uid=0 in database

Question: I had to build a form with a select field populated with all the users registered in database. There are 10 users that I can see in admin>people.
To get all the users, I used entity_load('user').
But in my select, I have one empty option in addition to my 10 users.
I checked in my database, and I found this empty UID=0 record:

I searched the Internet but I didn't find a satisfying answer. I read something about Anonymous user but I didn't get it.

Is this record important?
Does it have to be there?
If yes, I'll do some trick to ignore it in my select.
If not, can I just delete it?

Thank you in advance for this little trivial question.
Answer:
Is this record important?

Yes, it prevents some queries from failing if it's anonymous user who caused them.

Does it have to be there?

There is a possibility site would stay browsable you remove it... but it would mess your login functionality and may prevent sessions from persisting.

If yes, I'll do some trick to ignore it in my select.

Consider using EntityFieldQuery. Omit UIDs lower than 1, or select only users with name, etc.
Comment: "Have to" isn't a bit strong...without the anon user record authentication/session doesn't work. It's pretty much fundamental to a working Drupal install.
Comment: @Clive OK, fixed
Comment: Thanks. I was pretty sure that it was there for something :D

No problem for my query, I'll just test the UID in my foreach where I populate my select's options.

PS: I can accept your answer in 4 minutes ;)
Comment: @Clive better now?
Comment: I think it's fairer to say "you can still browse the site, but you can't login". Or more accurately, you can login, but that session won't persist with subsequent requests. If it's ever happened to you it's very frustrating till you work out what the problem is - then you never, ever forget it!
Comment: I'm not sure if there is something different in my site (that I tested). Users can login even if the uid 0 record is missing. However, anonymous comments completely fail when uid 0 is not present. Anonymous forms worked fine as well. I'm not saying uid 0 is not necessary - in fact is is necessary. But there were no login issues when uid 0 is missing.
Comment: @AyeshK it depends - if session was initiated before user attempted to visit login form, it may get weird. Or may not. If session is created at login form opening (ie it already died earlier and is re-created), then login may work all right.

User with uid=0 in database


Count real website load speed via proxy?

Question: i make code for measure load speed of website but don't know if is possible measure real load speed of website via some proxy i try but always give me some abnormal number because slowness of proxy, there is some solution for measure real website load speed via proxy  ?
Comment: Give us some more info first. What are you using to measure the load speed of a website? What have you tried to fix this?
Comment: i need way how to measure real website load speed via some proxy e.g. 184.108.40.206 this is argentina proxy when i try measure load speed i get 19sec this is not real website load speed, now how i can know how much is this proxy slower and get real website load from some country depend of proxy location ?
Comment: Open proxies are used and misused by all kind of people to all kind of purposes, they are considered a security issue to whoever is running them and you cannot expect to have consistent results when tunneling your traffic through a compromised server. It can aswell be running in some home computer with a 1Mbps link and 20 people trying to download garbage through it, it won't perform consistently.
Answer: Use curl_getinfo method after execute
<code>        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
        curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $head = curl_exec($ch);
        $proxy_time = curl_getinfo($ch, CURLINFO_REDIRECT_TIME);
        curl_close($ch);
</code>

CURLINFO_CONNECT_TIME
CURLINFO_PRETRANSFER_TIME
CURLINFO_STARTTRANSFER_TIME
CURLINFO_REDIRECT_COUNT
CURLINFO_REDIRECT_TIME

More information you can see here:
http://php.net/manual/en/function.curl-getinfo.php
Good luck!


What is the different tactics between sending the ball to near post and back post in football corner kick?

Question: In football, some teams always send the ball to near post when they got a corner kick and they fail to score. I wonder why don't they try back post, or short corner kick.
Comment: you should narrow your question a lot more to come with a good answer. Any team could do anything they want with a corner kick, and the reasons to do that could be a lot. it can happen that they don't have a kicker that can kick that far away (?)
Answer: Short Corner kick
This is most of the time the option chosen if they have no real player who can head the ball in.
Corner kick to back post
This one is the most trickiest of the options I would say. Giving a good ball to the furtest goal post can be difficult. It all has to be (fairly)good: speed, height, direction are very important. 5cm too high and it's a bad kick, too low, too close to the goalkeeper, too slow, bad kick. Good height and speed but wrong direction, bad kick. No matter how good a player's shooting, it's still tricky and offcourse highly dependable on how players run and are allowed to run by their defender.
Corner kick to nearest post
This gives you a bit more options, you can pass the ball back, head it trough, take a shot/header at goal. Here a good kick is also important but if things go wrong there are some things to fall back on which are less possible with a kick to the furthest post. You also don't need the biggest players to manage a header there. A defender will most likely remain behind the player which gives him a better chance than heading for a kick going further in. A bad


Save page source in Javascript variable

Question: I am studying javascript and I've got some problems. I would like to save the source of a page (html, json, xml) in a javascript variable. I didn't find much surfing on the net so could you help me? Actually the page is on an external domain so how can I get around the same origin policy limitation?
Comment: I suspect what ever it is you're trying to achieve, you're going about it in the wrong way. What is the goal of "saving the source"?
Comment: You cannot "get around" the Same Origin Policy.  If you could, the Internet would be a disaster.
Comment: I'm trying to save the content of a json file (I'd like to copy to save all the lines of the json file in a javascript array)
Comment: I think you can use YQL. But I'm not sure how will you mitigate the same origin policy or put in other words, how YQL takes care of the same. Personally, I've never used YQL but I know that it can fetch the HTML...   `select * from HTML where url="http://cnn.com"` fetches the source of HTML.. http://developer.yahoo.com/yql/
Comment: @Bulk: How apt is it to use YQL for this purpose?
Answer: I do not believe you can pull the entire source code from an external domain without a server-side script such as PHP.  The only cross-domain compatible format is JSONP, which with JQuery would require a JSON response from the other server.  Both may pose a security risk to your webpage.
UPDATE:
See here for more information.

Save page source in Javascript variable


Is there an equation for every graph?

Question: Is it possible to write a formula for any line imaginable, for example a drawing?
I once saw this long, and complicated, formula made by a mathematician with loads of ceilings etc.
The explanation was something to do with something he was programming for computers using pixels - I'm really not sure - but basically, the entire graph had every single pixel drawing there was, and then limits were set to section off the image you wanted.
Is this possible with actual lines, not pixels.
-- I did a search and it's this: Tupper's self-referential formula
Comment: Are you actually talking about something like [the batman equation](http://math.stackexchange.com/questions/54506/is-this-batman-equation-for-real)?
Comment: yes $yes$ *yes* **yes**
Comment: @Tobi You forgot \*\*\*, as in ***yes***!
Comment: *** I'll add that to my pallet, yes! *** Nooooo!
Comment: Like John Hughes said, the answer is no. A more philiosophical question would be, is there an equation for every _concievable_ graph? In that case, we'd have to be defining what an equation is.
Comment: "*... something that's mathematically sensible, [and] is written with [a] set of symbols (xs, ys, addition, powers, multiplication...whatever you can express using LaTeX's equation editing, for instance)*"
Answer: @Ethan Bolker is right, and if you want to make his statement more precise, you could say something about the number of possible "curves" vs the number of possible "formulas", where a formula is something that's mathematically sensible, is written with some finite set of symbols (xs, ys, addition, powers, multiplication...whatever you can express using LaTeX's equation editing, for instance) in a finite string. The number of such formulas is countable, while the number of curves is uncountable (just think of the horizontal line at height $u$ for each possible real number $u$; as $u$ ranges over the reals, you have an uncountable number of 'curves').
But this question is also addressed, in a somewhat roundabout way, in Tom Stoppard's superb play Arcadia; in it there is the following interchange between Thomasina, a prodigy, and her tutor, Septimus:

Thomasina: ... Each week I plot your equations dot for dot, xs against
  ys in all manner of algebraical relation, and every week they draw
  themselves as commonplace geometry, as if the world of forms were
  nothing but arcs and angles. God's truth, Septimus, if there is an
  equation for a curve like a bell, there must be an equation for one
  like a bluebell, and if a bluebell, why not a rose? Do we believe
  nature is written in numbers?
Septimus: We do.
Thomasina: Then why do your equations only describe the shapes of
  manufacture?
Septimus: I do not know.
Thomasina: Armed thus, God could only make a cabinet.
Septimus: He has mastery of equations which lead into infinities where
  we cannot follow.
Thomasina: What a faint-heart! We must work outward from the middle of
  the maze. We will start with something simple. (She picks up the apple
  leaf.) I will plot this leaf and deduce its equation. You will be
  famous for being my tutor when Lord Byron is dead and forgotten.

While your question is mathematical, I strongly recommend reading the play, despite there being very little precise mathematics in it.
Comment: How can the number of possible formulas be countable if there is indeed a formula for every horizontal line at height $u$ for every real number $u$?
Comment: +1, more than once if I could. I did think about the cardinality argument but completely forgot that passage from Arcadia!
Comment: The argument reminds of the argument for uncomputable functions, due to the fact that there are only countable infinite many programs, but uncountable infinite many desireable machine functions.
Comment: So can you communicate an arbitrary line at height $h\in\mathbb{R}$ to me?
Comment: No, I absolutely can't (although I can't prove that). But if you believe thatm then that alone is enough to explain why there are more curves than formulas.
Comment: I figured I was just really explaining your answer  in a bit more detail, Ethan, but I'm pleased to have reminded you of *Arcadia*.
Answer: The short answer is "no". A long answer would require   careful definitions of "formula" and of "any line imaginable". Those definitions are hard to write.
If you have to draw a curve of pixels on a computer screen you will often be able to find a formula that gives you a good approximation of what you want.
Answer: There are fantastic formulas, like the Batman equation, but in general I believe it is not possible.
If we restrict us to the graphs of continuous functions of one variable, for our formulas we usually stick to a set of elementary functions which is exhausted rapidly for more exotic cases and must be extended by special functions or integral functions, solutions of differential equations etc.
Comment: Hahaha, that one.  +1 for the memories.
Answer: Well, you can approximate with Taylor's theorem.  You could also consider a fourier series (I am less familiar with that).
Indeed, many basic functions are calculated via their Taylor series.  Mainly analytic functions:
$$\sin(x)=x-\frac16x^3+\frac1{120}x^5+\mathcal O(x^7)$$
as you keep taking the expansion out, you will get a polynomial that is really close to $\sin(x)$.
Some "lines" are representable using implicit formulas, like $x^y=y^x,y\ne x$.  But it can also be represented by a parametric equation: $$(x,y)=(a^{1/(a-1)},a^{a/(a-1)})$$ or a polar form:
$$r=\left(\frac{(\sin\theta)^{\cos\theta}}{(\cos\theta)^{\sin\theta}}\right)^{1/(\sin\theta-\cos\theta)}$$
So there are many interesting ways to produce any numbers of lines.
I'm not really sure, however, if it could be possible to deduce any line's formula, but the above give some good ways to thinking about this.
Comment: I've just realised how many questions of mine you've answered/contributed to - thanks!
Comment: @Tobi I just happen to be an [extremely active user](http://math.stackexchange.com/users).  High up there in ranking.
Comment: *"... thanks[ on behalf of everyone]!"*
Comment: Parametric equations are pretty restrictive. A parametric equation defined using continuous functions on $[0,1]$ will always give you a connected curve. Many drawings are not connected curves, of course.
Comment: @bubba Then we'd have piece-wise parametric equations.  But I don't think the OP wanted discontinuous lines.
Answer: There's a big difference between drawing (either on a computer screen or with a pencil) and mathematics.
From the mathematical point of view, the answer from John Hughes explains that there are more curves than formulae, so there must be some curves that don't have a formula.
But drawing is an approximate process -- the pixels on a computer screen and the marks made by your pencil are not precise representations of mathematical formulae. The graphs of mathematical equations are infinitely thin curves, which are impossible to produce on a computer screen or on paper.
So, suppose you give me a drawing of a curve. I could scan it to get a black-and-white bitmap image (a two-dimensional array of pixels). Let $v_{ij}$ be the value of the $ij$-th pixel, where $v_{ij}=1$ means black and $v_{ij}=0$ means white for $1 \le i \le m$ and $1 \le j \le n$. For each $i,j$, define a function $\phi_{ij}: [1,m] \times [1,n] \to [0,1]$ by
\begin{align}
\phi_{ij}(x,y) &= v_{ij} \quad \text{   if } x = i \text{ and } y = j  \\
\phi_{ij}(x,y) &= 0 \quad \text{   otherwise }
\end{align}
and define
$$
\phi(x,y)  = \sum_{i=1}^m \sum_{j=1}^n \phi_{ij}(x,y)
$$
Then the curve is the set
$$
S = \{ (x,y) \in \mathbb{R}^2: \phi(x,y) = 1 \}
$$
or, less formally, the curve has equation $\phi(x,y) = 1$. If you were to plot this equation (in system like Mathematica, for example), then the result would be visually very close to the original drawing, perhaps even indistinguishable.
But this representation is essentially pixel-based, which you said you wanted to avoid. It could be turned into a vector/line based approach, though. The functions $\phi_{ij}$ are not continuous, but you can replace them with sharp spike-shaped continuous ones. Then the function $\phi$ is continuous. You can visualize it as a landscape that has sharp ridges (with height $z=1$) that follow the original curve. We want the contour plot at height $z=1$ on this landscape. There are well-known techniques for computing these sorts of contours, either as polylines or as spline curves. One of them is marching squares. Polylines and splines are somewhat cheating, arguably, since they are functions that are defined piecewise. But, I felt free to bend the rules, since you didn't state them precisely.

Is there an equation for every graph?


Qual a diferença de bindValue para um array executado diretamente no $pdo->execute()

Question: Atualmente eu uso uma programação como essa
<?php

$array = array('nome'=>'Alisson', 'idade'=>20);

$query = $conn->prepare("INSERT INTO table (nome,idade) VALUES (:nome, :idade)");
$query->execute($array);

?>

Qual a diferença se eu usar o bindValue ao invez do array() ? Deixar meu código mais ou menos assim:
<?php

$query = $conn->prepare("INSERT INTO table (nome,idade) VALUES (:nome, :idade)");

$query->bindValue(':nome', 'Alisson', PDO::PARAM_STR);
$query->bindValue(':idade', '20', PDO::PARAM_STR);

$query->execute();

?>

Answer: A diferença entre passar os valores com  bindValue() e execute() do primeiro com o segundo código é nenhuma.
Ambos os parâmentros estão sendo enviados como string, todos os argumentos enviados em execute() são do tipo string enquanto bindValue() permite outros tipos como o PDO::PARAM_INT que é usado praticamente em um clásula LIMIT/OFFSET
Relacionado:
Qual a diferença entre bindParam e bindValue?
SQL LIMIT parametrizado no PHP com PDO
Answer: Como acréscimo à resposta do @rray, gostaria de destacar aqui a vantagem de utilização do execute com array em relação ao método PDOStatment::bindValue.
Muitas vezes os dados que queremos passar para o bindValue pode estar em um array. A utilização poderia ser trabalhosa se você fosse definir um por um.
Exemplo:
$array = array('nome'=>'Alisson', 'idade'=>20);

$query = $conn->prepare("INSERT INTO table (nome,idade) VALUES (:nome, :idade)");

$query->bindValue(':nome', $array['nome'], PDO::PARAM_STR);

$query->bindValue(':idade', $array['idade'], PDO::PARAM_STR);

Quando eu precisei fazer uma operação de passar os valores de um array dinamicamente para o bindValue, a primeira coisa que eu pensei para diminuir o meu trabalho foi em fazer um foreach.
$array = array('nome'=>'Alisson', 'idade'=>20);

$query = $conn->prepare("INSERT INTO table (nome,idade) VALUES (:nome, :idade)");

foreach ($array as $key => $value) {
    $query->bindValue(":$key", $value, PDO::PARAM_STR);
}

No final das contas foi mais vantajoso usar execute passando o array.
Pequena diferença
Por mais que não pareça, eu acabei notando uma pequena diferença entre os dois. Isso só é percepível quando usamos o caractere ? para efetuar a 'vinculação de parâmetros'.
Veja:
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();

Observe que é necessário definir a posição das interrogações (?) para poder definir qual valor será vinculado a tal parâmetro.
Porém no caso do execute é um pouco diferente. O vínculo dos parâmetros ocorrerá de acordo com a posição do elemento no array
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));

A contagem nesse caso ocorre a partir do 0. Se você tentar nomear erroneamente um array (numericamente), ocorrerá um erro ao tentar rodar o método execute:
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array(1 => $calories, 2 => $colour));

PHP warning:  PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined


SSL with Amazon EC2 is invalid

Question: I purchased an SSL certificate from Comodo and have followed their (terrible) setup instructions.
I'm confident I have all the files in the right places, but browsers are still giving an error.
When I try to go on https://www.roryholland.co.uk it says the certificate is only valid for ip-10-112-47-5.ec2.internal (a dynamic Amazon IP), although I do have a static "elastic" IP set up.
Do I have to reissue the certificate?
Answer: Well, in addition to having the wrong domain, the cert presented has not been signed by a trusted CA.
You're still likely using the self-signed cert that shipped with the distro. You need to verify that your purchased cert has been installed correctly.
Comment: Well then you need to ensure that the correct virtual host is catching these requests.
Comment: Also, make sure when you are generating the cert, you use the proper domain name and not xxxx.ec2.internal.
Comment: In the virtualhost section in httpd.conf I'm specifying the correct certificate file
Comment: `grep -r -i ssl /etc/httpd/*` or whatever to see all the SSL configurations
Answer: Sounds like when you created the CSR.. you setup the CN wrong.. You set it to the hostname on the server and not www.roryholland.co.uk

SSL with Amazon EC2 is invalid


Any reason why this should not work? SQL will not add record to database

Question: so I have another problem that blows my mind why it will not work, but you all are smarter than me so..
the code is supposed to add new records to my database, it is a budgeting program and it asks the user the date of the income they have received, the user's ID, the name and category of the income and the amount that was received, and I am using SQL to add it into a ms access database. Take a look and please help!
Here is the code:
<code>procedure TForm1.BitBtn8Click(Sender: TObject);
var
 iNameOfIncome, iCategory, iDate :integer;
 sDate, sAmount :string;
 dDate :TDate;
begin
 with dmRecords do
  begin
   sAmount := Edit7.Text;
   iNameOfIncome := ComboBox10.ItemIndex + 1;
   iCategory := ComboBox2.ItemIndex + 1;
   dDate := DateTimePicker1.Date;
   sDate := DateToStr(dDate);

   qryRecords.SQL.Clear;
   qryRecords.Active := False;
   qryRecords.SQL.Add('INSERT INTO [Income (Ledger)](DateofIncome, [User ID], [Income ID], [Category ID], [Income Amount]');
   qryRecords.SQL.Add('VALUES (' + sDate + ',' + IntToStr(SpinEdit2.Value) + ',' + IntToStr(iNameOfIncome) + ',' + IntToStr(iCategory) + ',' + sAmount + ')');
   qryRecords.ExecSQL;
   qryRecords.SQL.Clear;
   qryRecords.SQL.Add('SELECT * FROM [Income (Ledger)] ORDER BY IncomeNo');
   qryRecords.Active := True;
  end;
</code>
Thank you in advance!
Comment: It seems which you are missing the final  parenthesis on this line  `INSERT INTO [Income (Ledger)](DateofIncome, [User ID], [Income ID], [Category ID], [Income Amount])`, Also consider use parameters to pass the values to insert.
Comment: Again stop using concatenated statements!!! The answer shows you how to do it correctly...
Comment: I cant believe I missed that! Thank you! It works but my datepicker keeps adding the date as 1900/01/27. Any reason why it would be like that?
Answer: I think you should rewrite it like this
<code>  qryRecords.Close;
  qryRecords.SQL.Text :=
  'INSERT INTO [Income (Ledger)](DateofIncome, [User ID], [Income ID], [Category ID], [Income Amount]) ' +
  'VALUES (:DateofIncome,:User_ID,:Category_ID,:Income_ID,:Income_Amount)';
  qryRecords.ParamByName('DateofIncome').AsDateTIme := dDate;
  qryRecords.ParamByName('User_ID').AsInteger := SpinEdit2.Value;
  qryRecords.ParamByname('Category_ID').AsInteger := iCategory;
  qryRecords.ParamByname('Income_ID').AsInteger := iNameOfIncome;
  qryRecords.ParamByname('Income_Amount').AsFloat:= sAmount;
  qryRecords.ExecSQL;

  qryRecords.SQL.Text := 'SELECT * FROM [Income (Ledger)] ORDER BY IncomeNo';
  qryRecords.Open;
</code>
This way you will pass right types to DB. Otherwise you do not know how db will interpret what you are sending to it.
Comment: If you are using ado-query I highly suggest to change it to something like ZeosLib. Because I had cases when ParamByName('XXX').Value := 1; Resulted in odd behavior because Value is variant an 1 was converted to varSmallint but db was waiting for varInteger.
Comment: I have tried it, and it keeps telling me "Undeclared Identifier: AsDateTime", undeclared identifier: as integer etc. Im using delphi 7
Comment: Sounds like you're perhaps using ADO (TADOQuery)? In which case the parameter syntax is ParamByName('User_ID').Value := ...


Ionic - Botões personalizados no google maps

Question: Estou usando ionic para criar um app onde uso a api do google maps eu preciso colocar alguns botões flutuando sobre esse mapa, como na imagem.
Eu achei um pedaço de código que parece ter funcionado pra pessoa, mas aqui comigo não funciona, parece que o botão fica atrás do mapa. Tentei aumentar o z-index, mas não consegui. Tentei também criar os botões dentro da div do #map, mas não aparecem.
Vou deixar o código para verem como estou tentando fazer.
<code>initMap(lat, lng) {
this.map = new google.maps.Map(this.mapElement.nativeElement, {
  zoom: 16,
  center: { lat: lat, lng: lng },
  mapTypeControl: true,
  streetViewControl: true,
  fullscreenControl: false,
  zoomControlOptions: {
    position: google.maps.ControlPosition.LEFT_BOTTOM
  }
})

//### Add a button on Google Maps ...
var controlMarkerUI = document.createElement('DIV');
controlMarkerUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundImage = "url(http://localhost/car.png)";
controlMarkerUI.style.height = '28px';
controlMarkerUI.style.width = '25px';
controlMarkerUI.style.top = '11px';
controlMarkerUI.style.left = '120px';
controlMarkerUI.title = 'Click to set the map to Home';
//myLocationControlDiv.appendChild(controlUI);

this.map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(controlMarkerUI);}
</code>
Agradeço qualquer ajuda.
Answer: Como o Ionic utiliza html para renderização dos elementos na tela, você pode criar os botões e posicioná-los com 'position: fixed' sobre o elemento do mapa.


New column based on the sum of another column

Question: Hi Guys i want to create a column based on the sum of another column
Let's say i have this table

Employee
id      iddepartment    idhostel     valuedepartment
1       1               1                   15
2       2               1                   15
3       3               1                   15
4       4               2                   10
5       5               2                   10
6       6               2                   10

I want to create another table with a calculated column (sum valuedepartment group by idhostel) that looks something like this one

Employee
id      iddepartment    idhostel     valuedepartment            valuehostel
1       1               1                   15                      45
2       2               1                   15                      45
3       3               1                   15                      45
4       4               2                   10                      30
5       5               2                   10                      30
6       6               2                   10                      30

There is a way i can do this please ?
Comment: Possible duplicate of [Column calculated from another column?](https://stackoverflow.com/questions/5222044/column-calculated-from-another-column)
Comment: Hi thank you for your reply yes i checked  your link but the problem is that we can perform some mathematics operations to store a column however if we want some agregate function like average or sum there is a problem
Comment: I'm guessing that value hostel is the sum of valudepartment by id hostel but I could be wrong, you didn't define.
Comment: Or value department = valuhostel / 3 or id hostel is a sequential number based on where value department and value hostel are the same
Comment: Salomon i updated my question hope that now it's clear !!
Answer: You want to create a new column in your table, then update its content from other columns :
ALTER TABLE my_table ADD COLUMN my_sum INT;

UPDATE my_table SET my_sum = value1 + value2;

In your use case, the relevant query seems to be :
UPDATE my_table as t1
INNER JOIN (
    SELECT idhostel, SUM(valuedepartment) AS sum_dpt
    FROM my_table
    GROUP BY idhostel
) t2 on t2.idhostel = t1.idhostel
SET t1.valuehostel = t2.sum_dpt

Comment: Yess that's what i want but instead of having value1 and value2 as a columns i want them to be as rows                                                                                update my_table set my_sum = sum(value1); something like that .
Comment: @HoussamZakariaAddad : Mmm, not sure that it would make sense... Please update your question to show the expected results...
Comment: I really appreciate your help man !! )ld take i have a mysql table that already have these columns (id-iddepartment-idhostel -valuedepartment) and i want to create another column which is valuehoste that contains the sum of valuedepartment grouped by idhostel l ! sorry if i didn't make things clear from the begining
Comment: Yess it looks something like that but the problem is that your solution updates also valuedepartment
Answer: The example suggests, that you want the sum of valuedepartment per idhostel. You can get that using a subquery.
SELECT e1.id,
       e1.iddepartment,
       e1.idhostel,
       e1.valuedepartment,
       (SELECT sum(e2.valuedepartment)
               FROM employee e2
               WHERE e2.idhostel = e1.idhostel) valuehostel
       FROM employee e1;

I don't recommend to persist this. You can always query it, like shown above, so you can get the information. Persisting values calculate from others bears the risk of inconsistencies however and should be avoided if possible. Otherwise great care has to be taken to avoid inconsistencies.
But you can use a view you can query like a table.
CREATE VIEW employees_with_valuehostel
AS
SELECT e1.id,
       e1.iddepartment,
       e1.idhostel,
       e1.valuedepartment,
       (SELECT sum(e2.valuedepartment)
               FROM employee e2
               WHERE e2.idhostel = e1.idhostel) valuehostel
       FROM employee e1;

You can then query the view.
SELECT *
       FROM employees_with_valuehostel;

would give you the same result as the query above.
Comment: This is the result i want thank you so much !! however it is possible to store the result in a seperate column ??
Comment: @HoussamZakariaAddad: As I wrote, I do not recommend to persist the vales. But you could use a view. See my edit.
Comment: I really appreciate your help man !! Your solution is what i wanted but the problem is that i am using this table in another program ( A spring boot program ) so the view is not the right path i should take                                                                                i have a mysql table that already have these columns (id-iddepartment-idhostel -valuedepartment) and i want to create another column  the other column which is valuehostel ! sorry if i didn't make things clear from the begining


Erro 404 em um arquivo php

Question: Estou tentando fazer um formulário, criado no arquivo index.php, que envia por método POST para a página cadastro.php e com um header() mando uma variável de verificação de volta para o index.
Porém, quando ele volta para a página index.php, diz que o arquivo não foi encontrado e dá Error 404.
index.php:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Exercicio 1</title>

<?php
    echo '<form action="cadastro.php" method="post">
            Nome: <input type="text" name="nome" value="" />

            Email: <input type="text" name="email" value="" />

            Senha: <input type="password" name="senha" value="" />

            <input type="submit" value="Enviar" />
        </form>';

    if(@$_GET['login'] == 1){
        echo 'Informe nome novamente!';
    }

?>

cadastro.php:
<?php
require 'connection.php';
require 'database.php';

$usuario = array(
    'nome' => $_POST['nome'],
    'email' => $_POST['email'],
    'senha' => $_POST['senha'],
    );

if(empty($_POST['nome']) || strlen($_POST['nome']) < 5){
    header("Location:index.php login=1");
}
else if(!strstr($_POST['email'], '@') || strlen($_POST['email']) < 5){
    header("Location:index.php login=2");
}
else if(empty($_POST['senha']) || strlen($_POST['senha']) < 5){
    header("Location:index.php login=3");
}
else{
    DBCreate('usuarios', $usuario);
    header("Location:index.php login=4");
}  ?>

Estou usando o XAMPP no Windows.
Comment: O seu `header` não deveria ser `Location: index.php?login=X`, onde `X` é o respectivo valor? Aliás, ele diz que qual arquivo não existe?
Answer: Os enderenços estão incorretos:
header("Location:index.php login=1");
...
header("Location:index.php login=2");
...
header("Location:index.php login=3");
...
header("Location:index.php login=4");

Troque por:
header("Location:index.php?login=1");
...
header("Location:index.php?login=2");
...
header("Location:index.php?login=3");
...
header("Location:index.php?login=4");

Vale lembrar que o Location é um header da resposta do HTTP, ou seja não é o PHP que redireciona e sim o navegador ao receber os headers, então o location: deve conter um caminho relativo ou absoluto ao endereço atual da página.
Sobre o uso do arroba:
Notei que esta usando @ para suprimir os "warnings", no caso seria legal dar uma lida nisto:

Por que dizem que utilizar @ arroba pra suprimir erros é uma má prática?
Comment: Aaah, muito obrigado, fiquei horas lendo e nao havia visto que faltava o "?".
Comment: Estava dando um warning na index, pois dizia que a variavel login ainda nao havia sido instanciada, mas como nao precisava da variavel a primeira vez que abro o index, resolvi suprimir aquele warning.

Erro 404 em um arquivo php


Adicionar coluna a um dataframe com base na classificação feita em outro dataframe

Question: Saudações! Possuo dois dataframes. Ambos possuem colunas que determinam intervalos, com números de máximo e mínimo. Em cada dataframe a classificação de cada intervalo é feita de uma maneira. Eu queria fazer uma nova coluna no segundo dataframe com a classificaçao de acordo com a classificação feita no primeiro.
por exemplo:
import pandas as pd
import numpy as np
var1 = 'df1.csv'
var2 = 'df2.csv'
df1 = pd.read_csv(var1, sep=';')
df2 = pd.read_csv(var2, sep=';')

print(df1)

Topo    Base    CLASSIFICADOR_1
0       10      A
11      22      B
23      37      C

print(df2)

Topo    Base    ClASSIFICADOR_2
0       2       T
3       5       N
6       10      T
11      14      P
15      22      U
23      33      N
34      37      P

O resultado que eu gostaria é basicamente isso:
Topo    Base    CLASSIFICADOR_2  CLASSIFICADOR_1
0       2       T                A
3       5       N                A
6       10      T                A
11      14      P                B
15      22      U                B
23      33      N                C
34      37      P                C

Answer: A resposta que eu desenvolvi é pouco "pythonica" e "pandonica", mas foi a que consegui. Espero que te ajude!
import pandas as pd

df1 = pd.read_csv('df1.csv')
df2 = pd.read_csv('df2.csv')

df1_values = df1.values
df2_values = df2.values

# lista com o valor a ser apendado futuramente ao df2
classificador_1 = []

for line2 in df2_values:
    topo2 = line2[0]
    base2 = line2[1]

    for line1 in df1_values:
        topo1 = line1[0]
        base1 = line1[1]

        # condicao de uniao de tabelas
        if (topo2 >= topo1 and base2 <= base1):
            classificador_1.append(line1[2])

    df2['CLASSIFICADOR_1'] = classificador_1

Comment: valeu! Consegui aqui, muito obrigado! abs


Proof by contradiction (another)

Question: I will suppose that I have to prove a theorem of this type
If a proposition $S$ is verified then;
for all $a>0,$ there exists $b>0$ such that the following my properties are satisfying ($p$), ($q$) and ($z$).
to prove this by contradiction I must suppose that there exists $a>0$ , for all $b>0$ we have the negation of $p$ or the negation of $q$ or the negation of $z$
is it equivalent to say
negation of $p$ and property $q$ and property $z$
or
property $p$  with negation of $q$ and $z$
or
property $p$ and property $q$ and negation of $z$
Thank you very much.
Comment: The first part, where you state what you have to prove, is right.  The second part where you state the equivalences is not.  What can't all of $p,q,z$ be false?
Answer:
If a proposition S is verified then; for all $a>0$, there exists $b>0$ such that the following my properties are satiying (p), (q) and (z).
to prove this by contradiction I must suppose that there exists
$a>0$, for all $b>0$ we have the negation of p or the negation of q or the negation of z

Yes.
To prove: $~~~S ~\vdash~ \forall a{>}0~\exists b{>}0~\big(P(a,b)\wedge Q(a,b)\wedge Z(a,b)\big)$
Show that: $~S,~\exists a{>}0~\forall b{>}0~\big(\neg P(a,b)\vee\neg Q(a,b)\vee\neg Z(a,b)\big)~\vdash~\bot$

is it equivalent to say:

negation of p and property q and property z, or
property p with negation of q and z, or
property p and property q and negation of z

No; that would be that exactly one property were false.   You need only show that when at least one property is false, you obtain a contradiction (under the assumption of S).

negation of p, and
p but negation of q, and
p and q but negation of z

Also recall that $(A\vee B)\to C \iff (A\to C)\wedge(B\to C)$ so to show that a disjunction entails a conclusion you need prove each of the disjuncts alone entails the conclusion.
Comment: So if i prove that i have a contradiction with p ,q and negation of z my proof is correct @Kemp
Comment: Your proof would be incomplete.  You need to show a contradiction arrises when any one from the three properties is negated. @Vrouvrou
Comment: then why you say that there is no equivalence ?
Comment: Because you were not covering cases where two or three of the properties were negated.  The difference is that you need to show that *all* that is needed to produce a contradiction is that any one from the three is negated.

Proof by contradiction (another)


Spark HiveContext does not retrieve newly inserted records from Hive Table

Question: I am using Spark 1.4. HiveContext is used to connect Hive. I did the following
val hx = new HiveContext(sc)
import hx.implicits._
hx.sql("select * from tab").show

// it is fine, result was shown as expected
then,  I inserted a few records into tab from beeline console
hx.refreshTable("tab")
hx.sql("select * from tab").show

// still old records, no newly inserted records
My question is:  why the HiveContext didn't retrieve the newly inserted records?
Comment: Have you found a solution, in the end? I'm having the same problem.
Answer: hiveContext.refreshTable(tableName: String)  - this will refresh only metadata of the table (not the actual data)
Notes from official documentaition : (credits: https://spark.apache.org)
refreshTable(tableName: String): Unit
Invalidate and refresh all the cached the metadata of the given table. For performance reasons, Spark SQL or the external data source library it uses might cache certain metadata about a table, such as the location of blocks. When those change outside of Spark SQL, users should call this function to invalidate the cache
To retrive newly inserted records:- uncache first and cache again using , uncacheTable(String tableName) and cacheTable(String tableName)
Comment: the table in the question was not even cached in the first place. Moreover, I tried to cache  -> uncache -> cache , it still didn't retrieve the newly inserted records.  Did your proposed solution work in your installation ?
Answer: If the target table is partitioned, You need to insert with 'partition' option. If you miss out the partition, data will not be visible.
INSERT OVERWRITE TABLE tablename1 PARTITION (partcol1=val1, partcol2=val2...) SELECT col1,col2,.... FROM tablename2

Answer: On a differently slight case, I have an RDD coming from a Spark SQL statement via HiveContext. The solution which worked for me after some experiments was to actually regenerate the RDD itself.
It does not matter whether you are using the DDL by Spark SQL or sending SQL statements directly via hiveContext.sql.
I have seen around people using a "count trick" in order to force the recomputation of a dataset but at least in my attempts I couldn't get to see the new data this way.
Anyway trying caching, refreshing and friends did not work for me, if somebody has some proper pattern here please share.


$\lambda$ is eigenvalue of $T$ implies $\lambda^{-1}$ is eigenvalue of $T^{-1}$

Question: Problem:
Let $T$ be an invertible linear operator. Prove that a scalar $\lambda$ is an eigenvalue of $T$ if and only if $\lambda^{-1}$ is an eigenvalue of $T^{-1}$.
I took a look at the solution. It reads:
"$\lambda$ is an eigenvalue if and only if $T(v)=\lambda v$ for some nonzero vector $v$. As $T$ is invertible, from the above, we see $\lambda\not=0$. So this means
$$\lambda v \color{red}= \lambda^{-1}T^{-1}(T(v))=T^{-1}v$$
which means that $\lambda^{-1}$ is an eigenvalue of $T^{-1}$."
Could anyone explain why the equality in red is valid?
Answer: It's a typo, it should be $\lambda^{-1} v = \lambda^{-1} T^{-1} (T (v))$.
Comment: Oh, thank you. You saved me!


How to remove a specific field by given conidtion in mongodb?

Question: I am not being able to remove the specific eventid from the UserSchema. I searched for this and got a method using unset but that is removing the whole user while the push function is not doing anything. Is there any other way to do this?
Current UserSchema
[
  {
    "_id": "56593f3657e27af8245735d7",
    "username": "abc",
    "name": "xyz",
    "__v": 0,
    "favouriteid": [
    {
      "eventid": "5659242639e43bfc2a0836b9",
      "_id": "56593f6b57e27af8245735d8"
    },
    {
      "eventid": "5659244039e43bfc2a0836ba",
      "_id": "56593f8857e27af8245735d9"
    }
    ]
  }
]

What I need-
[
 {
   "_id": "56593f3657e27af8245735d7",
   "username": "abc",
   "name": "xyz",
   "__v": 0,
   "favouriteid": [
   {
    "eventid": "5659242639e43bfc2a0836b9",
    "_id": "56593f6b57e27af8245735d8"
   }
   ]
 }
]

I will be passing eventid and userid
But when I am using this code, the user gets deleted itself rather than the required field.
api.post('/removefavourites', function (req, res) {
    // _id: req.body.id;
    User.findById({_id: req.body.userid},
        {$unset:{favouriteid: {eventid: req.body.eventid}}},
        {upsert: true},
        function (err) {
            if(err)
            return err;
            else
            res.json({success: true});
        });
});

Answer: You can use update method with pull operation as shown below:
api.post('/removefavourites', function (req, res) {
  // _id: req.body.id;
  User.update({_id: req.body.userid},
    {$pull:{favouriteid: {eventid: req.body.eventid}}},
    function (err) {
        if(err)
        return err;
        else
        res.json({success: true});
    });
});

Hope this helps :)