EFD-Reinf - Versão do lote inválida. Deve ser utilizada a versão 1.04.00

Question: Estou gerando o registro R-1000 para teste de envio no ambiente de produção restrita do EFD-Reinf, e já obtive ajuda aqui no SOpt mesmo:
Como consumir WebService do EFD-Reinf no C#? (Envio Eventos).
Consegui autenticar e fazer o consumo do serviço com sucesso, porém o retorno do XML enviado diz que a versão está inválida:

Versão do lote inválida. Deve ser utilizada a versão 1.04.00.

Sendo que aponto para a nova:
http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_04_00
Já pesquisei aqui no SOpt, inclusive no post:
C# EFD-REINF 1.03.02 - Assinatura do evento inválida. Assinatura Digital do documento XML é inválida, mas não encontrei a causa do problema.
Segue o XML que estou enviando, sem assinatura:
<?xml version="1.0" encoding="utf-8"?>
   <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sped="http://sped.fazenda.gov.br/">
  <soap:Header />
  <soap:Body>
    <REINF xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_04_00">
      <loteEventos>
        <evento id="ID1">
          <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_04_00">
            <evtInfoContri id="20181121110000000000000001">
              <ideEvento>
                <tpAmb>2</tpAmb>
                <procEmi>1</procEmi>
                <verProc>1.0</verProc>
              </ideEvento>
              <ideContri>
                <tpInsc>1</tpInsc>
                <nrInsc>01628604</nrInsc>
              </ideContri>
              <infoContri>
                <inclusao>
                  <idePeriodo>
                    <iniValid>2018-01</iniValid>
                  </idePeriodo>
                  <infoCadastro>
                    <classTrib>99</classTrib>
                    <indEscrituracao>1</indEscrituracao>
                    <indDesoneracao>0</indDesoneracao>
                    <indAcordoIsenMulta>0</indAcordoIsenMulta>
                    <indSitPJ>0</indSitPJ>
                    <contato>
                      <nmCtt>XXXX</nmCtt>
                      <cpfCtt>XXX</cpfCtt>
                      <foneFixo>(011)XXXX6427</foneFixo>
                      <email>XXXXX</email>
                    </contato>
                  </infoCadastro>
                </inclusao>
              </infoContri>
            </evtInfoContri>
          </Reinf>
        </evento>
      </loteEventos>
    </REINF>
  </soap:Body>
</soap:Envelope>

O XML com a assinatura:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sped="http://sped.fazenda.gov.br/">
  <soap:Header />
  <soap:Body>
    <REINF xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_04_00">
      <loteEventos>
        <evento id="ID1">
          <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_04_00">
            <evtInfoContri id="20181121110000000000000001">
              <ideEvento>
                <tpAmb>2</tpAmb>
                <procEmi>1</procEmi>
                <verProc>1.0</verProc>
              </ideEvento>
              <ideContri>
                <tpInsc>1</tpInsc>
                <nrInsc>01628604</nrInsc>
              </ideContri>
              <infoContri>
                <inclusao>
                  <idePeriodo>
                    <iniValid>2018-01</iniValid>
                  </idePeriodo>
                  <infoCadastro>
                    <classTrib>99</classTrib>
                    <indEscrituracao>1</indEscrituracao>
                    <indDesoneracao>0</indDesoneracao>
                    <indAcordoIsenMulta>0</indAcordoIsenMulta>
                    <indSitPJ>0</indSitPJ>
                    <contato>
                      <nmCtt>xxx</nmCtt>
                      <cpfCtt>xxx</cpfCtt>
                      <foneFixo>(011)xxx</foneFixo>
                      <email>xxxx</email>
                    </contato>
                  </infoCadastro>
                </inclusao>
              </infoContri>
            </evtInfoContri>
          </Reinf>
        </evento>
      </loteEventos>
    </REINF>
  </soap:Body>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
      <Reference URI="">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
          <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
        <DigestValue>Mv9GEVe2dZ4zstZhfcp0xok3OHolN5kjUNtMDvG1uF4=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>DUE7Q+LguONd8cDbPZHqC9ObqG51Um5Oh4v7I5fMw43zIQQeeMbhF2j1GrbKg0poFW134OUB1dFXZyXMEQ/ynrNXkRXT1zZAXgQ0jFtfUA6MIjDCUoE68Q/bNDG7N28A1loXqAILKMmVr8WGg73UA9rDU9wMTTWy9yOfN712yqFA5RJzp53wpVX6BmjC05lfRblslEcSZTvQg2QbgLh+FBRIubznVn+sFuZ5hAB6QggCumSyxVBrpeLPyvlpSPvQM2xHw4IO3bFSq2BqPHSePU3lLyl+8/irlOLUGYSSX77m8hmBOpKzmqBqjX+v8E6QLHLEUpXcN0HT3Y5bGMByrQ==</SignatureValue>
    <KeyInfo>
      <X509Data>
        <X509Certificate>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</X509Certificate>
      </X509Data>
    </KeyInfo>
  </Signature>
</soap:Envelope>

O XML completo de retorno:
<Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/retornoLoteEventos/v1_04_00">
  <retornoLoteEventos id="IDCE8ED92E6A9124FCD401AFF46756541E">
    <ideTransmissor>
      <IdTransmissor>01628604000140</IdTransmissor>
    </ideTransmissor>
    <status>
      <cdStatus>1</cdStatus>
      <descRetorno>ERRO</descRetorno>
      <dadosRegistroOcorrenciaLote>
        <ocorrencias>
          <tipo>1</tipo>
          <codigo>MS0092</codigo>
          <descricao>Versão do lote inválida. Deve ser utilizada a versão 1.04.00.</descricao>
        </ocorrencias>
      </dadosRegistroOcorrenciaLote>
    </status>
  </retornoLoteEventos>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
      <Reference URI="#IDCE8ED92E6A9124FCD401AFF46756541E">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
          <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
        <DigestValue>gRHi6NxvLDuhFO2Q2jB+Nl7B450LCzRynii+Mo10ZWE=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>CmbAd77rYGrwWkFSw+Hx4BqnbV7bgjGfnnw2Y1TkQt1HYJIjoe7JcjBO8v/BFmg0vzHMU4CLr4GuryhMFFP1m6ED/OhAbH1DAqwmPITypfSnLTZno5ILgxtV1mxic88oYY3VebPZnAeINg7OK1u+J3tQMmpEuTx0ew7kY5wIFOW+Fa2bUQXGRqrLP2r5C7Gmt+b/Z0mHxLAaeb/qwdhxqnyDVuCayFo93dI5rREP9WgQhTijwRv8k0uBQ94bOzv12kcF15w00rg3F/1bo6Vy8iSzFc9OtEl0C5tUMC765QnfFChdWdkT9BtQwVnKiOHTGISixa9EHpzjEv24cGvrPA==</SignatureValue>
    <KeyInfo>
      <X509Data>
        <X509Certificate>MIIHcTCCBVmgAwIBAgIDAvA9MA0GCSqGSIb3DQEBCwUAMIGOMQswCQYDVQQGEwJCUjETMBEGA1UECgwKSUNQLUJyYXNpbDE2MDQGA1UECwwtU2VjcmV0YXJpYSBkYSBSZWNlaXRhIEZlZGVyYWwgZG8gQnJhc2lsIC0gUkZCMTIwMAYDVQQDDClBdXRvcmlkYWRlIENlcnRpZmljYWRvcmEgZG8gU0VSUFJPUkZCIFNTTDAeFw0xODA5MDQxNzA5NDhaFw0xOTA5MDQxNzA5NDhaMIG6MQswCQYDVQQGEwJCUjETMBEGA1UECgwKSUNQLUJyYXNpbDE2MDQGA1UECwwtU2VjcmV0YXJpYSBkYSBSZWNlaXRhIEZlZGVyYWwgZG8gQnJhc2lsIC0gUkZCMREwDwYDVQQLDAhBUlNFUlBSTzEaMBgGA1UECwwRUkZCIGUtU2Vydmlkb3IgQTExLzAtBgNVBAMMJnByZXByb2RlZmRyZWluZi5yZWNlaXRhLmZhemVuZGEuZ292LmJyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+gp3NABZzSp4S1I7c6lgJXp1NgCOjHKn5OMxisk68fuHbhj1eyzfSMkc281ecF0uCmW+Fwyz7wnwRvS/VDE9/1p/21rg85AyzWvYfTvBcHKpi83d6PBmczt7xMNf8FRLU5Zj8dAS84YkoGBZw3GQTfWqW9LLnOf1zPmaPgdN8ALjecUkFmFIWNQLDgARR0YBIrTVtmk/BRZKk6z/j/gSHClhEy6ZCplVna5i9YJnDOoXlVuflEIuVMyRR2+SyuNk2QI5K/+vURKnZzY2xQKEfCBzu+Xj8ceuXHmtA75X03cKauCOq/Jqklfp9nY1ZvdXc4/lJXyFxf8iFfLAMHiDQIDAQABo4ICqDCCAqQwHwYDVR0jBBgwFoAUII0RXFXDAW+rVvGDzGipq8LatWMwXgYDVR0gBFcwVTBTBgZg
TAECAVswSTBHBggrBgEFBQcCARY7aHR0cDovL3JlcG9zaXRvcmlvLnNlcnByby5nb3YuYnIvZG9jcy9kcGNhY3NlcnByb3JmYnNzbC5wZGYwgYsGA1UdHwSBgzCBgDA9oDugOYY3aHR0cDovL3JlcG9zaXRvcmlvLnNlcnByby5nb3YuYnIvbGNyL2Fjc2VycHJvcmZic3NsLmNybDA/oD2gO4Y5aHR0cDovL2NlcnRpZmljYWRvczIuc2VycHJvLmdvdi5ici9sY3IvYWNzZXJwcm9yZmJzc2wuY3JsMFcGCCsGAQUFBwEBBEswSTBHBggrBgEFBQcwAoY7aHR0cDovL3JlcG9zaXRvcmlvLnNlcnByby5nb3YuYnIvY2FkZWlhcy9hY3NlcnByb3JmYnNzbC5wN2IwggEJBgNVHREEggEAMIH9oDsGBWBMAQMIoDIEMFNFUlZJQ08gRkVERVJBTCBERSBQUk9DRVNTQU1FTlRPIERFIERBRE9TIFNFUlBST4ImcHJlcHJvZGVmZHJlaW5mLnJlY2VpdGEuZmF6ZW5kYS5nb3YuYnKgOAYFYEwBAwSgLwQtMTgwMzE5ODAyODU2MDE2ODgwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwoCIGBWBMAQMCoBkEF0VEVUFSRE8gWU9TSElEQSBTQUxPTUFPoBkGBWBMAQMDoBAEDjMzNjgzMTExMDAwMTA3gR1lZHVhcmRvLnlvc2hpZGFAc2VycHJvLmdvdi5icjAOBgNVHQ8BAf8EBAMCBeAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4ICAQCL7xXh7bEYe42U/5oPfChSDLIEcsV4I4io/pAQBhtzf8UqCptT3aj2zWskg04BY10Xuq0UyE+pzInF6ulD4R4C1ee4bIkq84I4mq/cOx4HoIVZTq2j9F2NVSOJt87MxvUdSASPqiWj9qEvOpv/KopW8MJBRD35Pvukw
sHeiMlEKv5oMCa0mRUqrhWXVRYPeSjrBUbkRVNHGeUPH0if0N/uctlX8ecwGWD73fFbfrmSI+wkfmWxmEWdouu0pQXy/2A4KsODxc/CDUfM+61DJWC8mNKTVy1sae6W9wx8/uCY9lFsU5homfDxVhYgbHAjRpu9ItAomguKx82YJVUenHy7Oyi6u+QBOQZZuBnCrLgUDKqXKwGSh0qEI5m0uTZ9JE/MYMsJkr+iBUa9cM9r2UBwEslbzu4k6xrCCTawCoyMpd+LolKDLtl4gdveF7gzpBMyX90xT/TsqOhV94WRLLdcYEAAbpv+S+BaCPUXcEkD/1gWygQW5/P+jV88dAKLzL5lBX7k7pywZg27IXSB4IDUUJexCRpMehubTLG9gK9ua9JKmhHgNFCnche8+IrUyuFeyxUuLB0/4GJ152gsYlRdQs69GgzZa2YIEoo7dgw7vskTY9LVyvqybTY2MBzh+Wn0ktFwnkCSdyXegloQxWQqaakpzCwCo3tJPUDdU6EA2w==</X509Certificate>
      </X509Data>
    </KeyInfo>
  </Signature>
</Reinf>

EDIÇÃO
Tem razão, não havia percebido que a assinatura deve ser por evento e não por lote.
Sobre "A forma correta do seu soap:Envelope deveria ser essa":
fiz a edição conforme indicado, mas continua retornando a mesma mensagem de lote errado:
{<Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/retornoLoteEventos/v1_04_00">
  <retornoLoteEventos id="ID54ED726E636E2B6F9FD4FD7077870873">
    <ideTransmissor>
      <IdTransmissor>01628604000140</IdTransmissor>
    </ideTransmissor>
    <status>
      <cdStatus>1</cdStatus>
      <descRetorno>ERRO</descRetorno>
      <dadosRegistroOcorrenciaLote>
        <ocorrencias>
          <tipo>1</tipo>
          <codigo>MS0092</codigo>
          <descricao>Versão do lote inválida. Deve ser utilizada a versão 1.04.00.</descricao>
        </ocorrencias>
      </dadosRegistroOcorrenciaLote>
    </status>
  </retornoLoteEventos>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
      <Reference URI="#ID54ED726E636E2B6F9FD4FD7077870873">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
          <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
        <DigestValue>PkXxGAtPdkWYgZ21TLotsVYYE7mPLGnmpmLMXI65gnQ=</DigestValue>
      </Reference>
    </SignedInfo>
     [...]</SignatureValue>
    <KeyInfo>
      <X509Data>
        <X509Certificate> [...]</X509Certificate>
      </X509Data>
    </KeyInfo>
  </Signature>
</Reinf>}
    BaseUri: ""
    Document: null
    FirstAttribute: {xmlns="http://www.reinf.esocial.gov.br/schemas/retornoLoteEventos/v1_04_00"}
    FirstNode: {<retornoLoteEventos id="ID54ED726E636E2B6F9FD4FD7077870873" xmlns="http://www.reinf.esocial.gov.br/schemas/retornoLoteEventos/v1_04_00">
  <ideTransmissor>
    <IdTransmissor>01628604000140</IdTransmissor>
  </ideTransmissor>
  <status>
    <cdStatus>1</cdStatus>
    <descRetorno>ERRO</descRetorno>
    <dadosRegistroOcorrenciaLote>
      <ocorrencias>
        <tipo>1</tipo>
        <codigo>MS0092</codigo>
        <descricao>Versão do lote inválida. Deve ser utilizada a versão 1.04.00.</descricao>
      </ocorrencias>
    </dadosRegistroOcorrenciaLote>
  </status>
</retornoLoteEventos>}
    HasAttributes: true
    HasElements: true
    IsEmpty: false
    LastAttribute: {xmlns="http://www.reinf.esocial.gov.br/schemas/retornoLoteEventos/v1_04_00"}
    LastNode: {<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
    <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
    <Reference URI="#ID54ED726E636E2B6F9FD4FD7077870873">
      <Transforms>
        <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      </Transforms>
      <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
      <DigestValue>PkXxGAtPdkWYgZ21TLotsVYYE7mPLGnmpmLMXI65gnQ=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>NaDYeZv3gFDBH41BY5j8hcYXHhpdx+hjFWCIYvLaBxAVWNUUaAZixzV3Bld4Lul3m0yKL6Hq16xmKYiA55tCPbZWWy+YymnCtj3OC7rZPv2lQZZyTK6DiLugIIiUyk7TsTd1rZmT6D55OxwJfpmb1M+rQLK6siYAZmI2pguUX0NvKITIaaxUD6HGZOgO6cc9VGRR7PTxjhkl0j0jcwFPxCEvk8cTbT0PnkkLw1v5zPBC1nvgpz3Kn+fG11qkTwEIIdNonx/O1i7ZdvpLUe7/MXEYNbip/lcrGL/zapBHNTsLgN6NNI7QUUuPIPB4yMhpQcNA9FfzEgzdZVhbDzdLeQ==</SignatureValue>
  <KeyInfo>
    <X509Data>
      <X509Certificate> [...]</X509Certificate>
    </X509Data>
  </KeyInfo>
</Signature>}
    Name: {{http://www.reinf.esocial.gov.br/schemas/retornoLoteEventos/v1_04_00}Reinf}
    NextNode: null
    NodeType: Element
    Parent: null
    PreviousNode: null
    Value: "016286040001401ERRO1MS0092Versão do lote inválida. Deve ser utilizada a versão 1.04.00.PkXxGAtPdkWYgZ21TLotsVYYE7mPLGnmpmLMXI65gnQ=NaDYeZv3gFDBH41BY5j8hcYXHhpdx+hjFWCIYvLaBxAVWNUUaAZixzV3Bld4Lul3m0yKL6Hq16xmKYiA55tCPbZWWy+YymnCtj3OC7rZPv2lQZZyTK6DiLugIIiUyk7TsTd1rZmT6D55OxwJfpmb1M+rQLK6siYAZmI2pguUX0NvKITIaaxUD6HGZOgO [...]"

Não consigo postar meu XML aqui por limitação de caracteres.
Comment: O que eu faço é mais ou menos o que está aqui nessa resposta: [REINF - Assinatura Inválida](https://pt.stackoverflow.com/a/277475/86952), depois serializo o objeto do lote para um objeto `XElement` e então chamo o método `xElementLote.Save(nomeArquivo)`.
Comment: Você precisa serializar, mas não necessariamente gravar em disco. Serializar, nesse caso, é transformar o seu objeto em um XML, mesmo que esse XML esteja somente na memória. Aqui eu mando para o serviço sem nem salvar em disco, mando o XML em memória mesmo, porque na hora de enviar o XML para o serviço você tem que carrega-lo em memória de qualquer forma, em um objeto `XElement`.
Comment: Vagner, o retorno ficou truncado, poste o XML do retorno na mensagem, seguindo o padrão de formatação da edição que eu fiz.
Comment: Reeditei a pergunta para postar formatado.
Comment: Vagner, mas, quando você diz que "fez a edição", você não fez manualmente não, certo? Porque se você alterar qualquer coisa no arquivo depois de assinado, dará errado. Então, o seu programa tem que pegar apenas o XML do evento (aquele `` com `xmlns=".../evtInfoContribuinte/...`), assinar e embutir a assinatura dentro dele. Aí esse XML do evento, assinado, você embute dentro do lote (o `` com `xmlns=".../envioLoteEventos/...`), e não pode ter nenhuma alteração no XML do evento **depois** de assinado.
Comment: Desculpe a demora em responder. Para teste, eu concatenei manualmente o XML do Lote + o XML do Evento assinado, sem alterar o XML do evento assinado. Mas tudo bem, gostaria de saber o que e como vocês fizeram para unir os 2 XML. Inicialmente eu pensei no XmlTextWriter para ir criando elemento a elemento do XML Lote. No meio do mesmo, pensei em importar o XML do Evento assinado e passar para o XmlTextWriter. De que forma vocês fizeram isso?
Comment: Vagner, você conseguiu gerar evento assinado e embuti-lo no lote, via código? Se for o caso, abra mais outra pergunta sobre esse assunto. Minha resposta respondeu a sua pergunta original?
Comment: Pedro, infelizmente não tive tempo de aplicar sua sugestão devido outras urgências por aqui. Creio que na segunda feira consigo testar e respondo no post. Obrigado
Comment: Pedro, eu não tenho muita experiência na geração de XML desta forma, por isso talvez minha perguntas sejam bem "básicas". Minha dúvida neste ponto é a seguinte: Será que consigo gerar e validar com sucesso o XML sem serializar? Porque comecei a gera-lo desta forma: A partir do layout do evento, fui utilizando o XmlTexWriter para gerar elemento a elemento do XML com seus respectivos valores até finalizar o arquivo para posterior envio (Consumo do webservice).
Answer: O XML por padrão é sensível a maiúsculas e minúsculas (case-sensitive), e você chamou o elemento raiz do lote como <REINF>, mas o esquema XSD diz que o nome deveria ser <Reinf>. Altere isso e veja se resolve.

Referências:

Is XML case-sensitive? - Stack Overflow
Case sensitivity in XML Schema Definitions - Msdn forums
The XML FAQ: Which parts of an XML document are case-sensitive?

EDIÇÃO
Eu não havia notado no primeiro momento, mas o problema está na assinatura. Aqui há uma outra resposta que fala sobre isso: Erro de assinatura do XML para o EFD-Reinf.
Mas, basicamente, o seu evento R-1000 deveria estar assim, com a assinatura embutida dentro dele:
      <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_04_00">
        <evtInfoContri id="20181121110000000000000001">
            [...]
        </evtInfoContri>
        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            [...]
        </Signature>
      </Reinf>

Você está colocando a assinatura depois do soap:Body, o que está errado:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sped="http://sped.fazenda.gov.br/">
  <soap:Header />
  <soap:Body>
    <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_04_00">
      <loteEventos>
        <evento id="ID1">
          <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_04_00">
            <evtInfoContri id="20181121110000000000000001">
              [...]
            </evtInfoContri>
          </Reinf>
        </evento>
      </loteEventos>
    </REINF>
  </soap:Body>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    [...]
  </Signature>
</soap:Envelope>

A forma correta do seu soap:Envelope deveria ser essa:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sped="http://sped.fazenda.gov.br/">
  <soap:Header />
  <soap:Body>
    <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_04_00">
      <loteEventos>
        <evento id="ID1">
          <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_04_00">
            <evtInfoContri id="20181121110000000000000001">
              [...]
            </evtInfoContri>
            <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
              [...]
            </Signature>
          </Reinf>
        </evento>
      </loteEventos>
    </REINF>
  </soap:Body>
</soap:Envelope>

Comment: Sim.. alterei mas continua retornando a mesma mensagem de versão inválida.


Scales, modes, techniques for writing "Super Mario" style music

Question: I'm looking for a push in the right direction as to how to go about writing Super Mario type video game themes. What scales/modes work best, time signatures, etc...
Examples of where I'm trying to go:
Comment: The two examples aren't really stylistically related at all, outside of the fact that they're both composed for 8-bit NES audio hardware. I'm leaving this open since although I disagree somewhat with the content, you've stated it pretty well and I think a good answer can be found. Bear in mind, however, that you're operating under the assumption that musical style is based upon scales and time signatures. This is not the case!
Comment: These types of questions are not really answerable, and are really all just versions of "how do I compose music", for which there are entire sections in your local library dedicated to that subject. This question is like asking "what color should I use to paint a picture of an apple". Use whatever color you want, if you want a purple apple, use purple, if you want a red apple, use red. There is no answer to these types of questions, you may compose a perfectly reasonable song that doesn't use a similar scale at all, and just because you use this same scale, it doesn't mean that it is going to
Answer: The Super Mario theme song is characterized by mode mixture and syncopated sixteenth note rhythms alternating with eighth note triplets.
Each note duration is very short, and each voice has a different rhythm. When the voices overlap, you hear the combination of all of the rhythms into a more constant stream of impulses. Each impulse has a different combination of voices and pitch content, and that's what gives the music its bouncy feel.
The melody is in a pretty simple C major scale, but the harmonies borrow from the parallel minor in some cases. This is called mode mixture.
If you would like to compose music in this style, you should transcribe it exactly so you can deconstruct and see/hear for yourself what makes it tick.
Comment: You are a hero among men. This is exactly the kind of answer I was looking for. Thank you!
Answer: This notion may be apocryphal, but it does fit with what I remember of the Super Mario Brothers themes from NES.
I have at least heard that notes sounded on the early NES games had no capacity for duration (nor, presumably, timbral variations).  So, you end up with each note being the same length.  That limitation would tend to lead to a more rhythmic, perhaps contrapuntal style.  I don't know how pitches would have been specified, so it is quite possible that pitches had to stay within the Western system of twelve tones, and presumably composers would remain within major and minor keys by choice.  Other than that, though, I don't know that there are any "restrictions" on what you can write that would be similar in style to a particular video game.
Answer: I'm going on a hunch on this answer but it sounds like a Spanish flaminco style scale. Don't know the technical term for the scale.
Hope that helps
Comment: Maybe minor scale
Answer: I'm going to outsource my answer from this video, since it's pretty much exactly what you're asking for.

The Mario Franchise, when examined closely, draws a lot of influence from various jazz styles, more than people expect. Lots of chromaticism, and quickly-paced melodies. The Mario franchise's music in general, no matter who composes each piece, tends to have a lot of strong melodic material, an interesting/often-funky  bassline, and never seems to take itself too seriously.


Using Put request for ScienceDirect API

Question: I am having trouble using the ScienceDirect API and looking for help.
Before I used the API with a requests.get and everything worked just fine.
Due to some alternations on my search string I am forced to use the put-method (their API support told me so).
This is my code:
headers = {}
headers['Accept']='application/json'
headers['X-ELS-APIKey'] = 'my Api code here'
headers['X-ELS-Insttoken'] = 'my institutional token here'
headers['Content-Type'] = 'application/json'

data = {
        'qs':'("blockchain" OR "distributed ledger" OR "DLT") AND ("circular economy" OR "sustainable supply chain")',
       'offset': 0
       }

Url = "https://api.elsevier.com/content/search/sciencedirect"

r = requests.put(Url, data =json.dumps(data), headers=headers)

print(r.url)

I followed the documentation here: https://dev.elsevier.com/documentation/ScienceDirectSearchAPI.wadl
When I run this code I receive the error message:

{"service-error":{"status":
{"statusCode":"AUTHENTICATION_ERROR","statusText":"No APIKey provided for request"}}}

My apiKey and the institutional token are correct and as I see it submit them in the header.
Do you have any idea why this error occurs? Am I submitting the header somehow incorrect?
Comment: EDIT: Its because of the ' symbol. If I change it to double " it works fine!
Answer: actually this error happened bc of your website address. on the science direct you have to register your website address to get your Api_key then if you want to test your in your local system it doesn't work.
I suggest you:

start a django or flask project
set your project on port 8080
register your website in Sciencedirect like this: https://localhost:8080

Using Put request for ScienceDirect API


avoid line breaks in sublime text3 in short functions with js beautifier

Question: I'm using Sublime Text 3 with the JavaScript Beautify Package.
The code after beautifying looks like that:
var jobDimension = ndx.dimension(function(d) {
    return d.status;
});

But I want that it looks like that:
var jobDimension = ndx.dimension(function(d) { return d.status; });

That are the available settings:
{
    "indent_size": 4,
    "indent_char": " ",
    "indent_level": 0,
    "indent_with_tabs": false,
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "jslint_happy": false,
    "space_after_anon_function": false,
    "brace_style": "collapse",
    "keep_array_indentation": false,
    "keep_function_indentation": false,
    "space_before_conditional": true,
    "break_chained_methods": false,
    "eval_code": false,
    "unescape_strings": false,
    "wrap_line_length": 0
}

I tried different settings without success. Maybe you know how to achieve it with this package or an alternative.
Answer: You can change

"brace_style": "collapse",

to

"brace_style": "none",

Altough this completely disables cutting the line, so you have to do that yourself now.
Comment: That doesn't achieve what I want.
Answer: A recent version for the beautifier added preserve-inline as an option for brace-style.  This will keep inline (all on the same line) brace blocks unchanged.  It works as a modifier for the base setting:

"brace_style": "collapse,preserve-inline",


2x2 design - one way anova or two way anova

Question: So i did an experiment with 4 groups, each getting different advertisement communications tasty or healthy benefits:
group 1: control group, no health or taste benefits
group 2: only health benefits
group 3: only taste benefits
group 4: health & taste benefits
I have 4 different dependant variables: purchase intention, attitude, credibility and benefits all measured on 7 point likert scale
So I thought i had to do a 2 way anova because health and taste are the IV. But how do i test these? Because the interaction of them is already tested in group 4?
I work with SPSS
Answer: The two methods are statistically equivalent, but a two-way ANOVA will make it easier to test the specific effects of interest (i.e., an interaction between health benefits and taste and main effects of each). The model F-test in a two-way ANOVA will be equivalent to the F-test in the one-way ANOVA.
You can use a one-way ANOVA to test main and interaction effects. To test the main effect of health, you can test whether $\frac{\bar{x}_1+\bar{x}_3}{2}=\frac{\bar{x}_2+\bar{x}_4}{2}$. The t-test for this comparison will be equivalent to the F-test on the main effect of health benefits in a two-way ANOVA. For the interaction, you can test whether
$\bar{x}_2-\bar{x}_1=\bar{x}_4-\bar{x}_3$. The t-test on that will be equivalent to the interaction F-test in a two-way ANOVA. A one-way ANOVA makes it easier to compare individual groups and other contrasts (e.g., is there a difference between group 1 and all other groups combined?) while a two-way ANOVA makes it easier to test interactions, main effects, and simple main effects.
Answer: You have 1 independent variable with four levels (Group: Control vs. Health Only vs. Taste Only vs. Health + Taste). If your research question relates to finding any difference among these groups in response to a dependent variable, you have a 1-way ANOVA. If you want to do the same for all four dependent variables you describe above, you have four separate 1-way ANOVAs.


JPA HIBERNATE - mapping a column twice (embeddedID and POJO)

Question: I have to map a badly designed DB. And in the class "cote" there a composed PK with FK fields. So i made an embeddedable to avoid using derived entities with IdClass. So I tried this :
<code>@Entity
@Table(name="EVA_COTE")
public class Cote implements Serializable{

/**
 *
 */
private static final long serialVersionUID = -3902534586060936635L;

@EmbeddedId
private CotePK cotePK;

@ManyToOne
@JoinColumn(name="Evaluation", referencedColumnName = "NUDOSS")
private Evaluation evaluation;

@ManyToOne
@JoinColumn(name="CRITERE", referencedColumnName = "CODE")
private Critere critere;

@ManyToOne
@JoinColumn(name="SEUIL", referencedColumnName = "CODE")
private Seuil seuil;

@Column(name="VALEUR", columnDefinition="Decimal(5,0)")
private Integer valeur;

@Column(name="OBSERVATIONS", length=500)
private String observations;
</code>
With the following EmbeddedId :
<code>@Embeddable
public class CotePK implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 6835265195560184935L;
@Column(name="Evaluation", nullable=false)
private Integer evaluationId;

@Column(name="CRITERE", nullable =false)
private String critereId;

@Column(name="SEUIL", nullable=false)
private String seuilId;
</code>
As you can see i use the columns evaluation critere and seuil once in the embeddedId and once in the class Cote. And of course it doesn't work and i don't know what to try anymore. Is there a way to force JPA to link the two fields?
Answer: My final solution :
    @Entity
    @Table(name="EVA_COTE")
    public class Cote implements Serializable{
<code>/**
 *
 */
private static final long serialVersionUID = -3902534586060936635L;

@EmbeddedId
private CotePK cotePK;

@ManyToOne
@MapsId("evaluationId")
@JoinColumn(name="EVALUATION", referencedColumnName = "NUDOSS")
private Evaluation evaluation;

@ManyToOne
@MapsId("critereId")
@JoinColumn(name="CRITERE", referencedColumnName = "CODE")
private Critere critere;

@ManyToOne
@MapsId("seuilId")
@JoinColumn(name="SEUIL", referencedColumnName = "CODE")
private Seuil seuil;
</code>
Answer: Add this annotation to composite primary key
<code>       @EmbeddedId
       @AttributeOverrides( {
                @AttributeOverride(name="column_varible_name_1", column=@Column(name="column_name_1", nullable=false, length=<x>) ),
                @AttributeOverride(name="column_varible_name_2", column=@Column(name="column_name_2", nullable=false, length=<x>) ) } )
</code>


What module(s) should I use with Apache to provide SSL termination and Load-Balancing to non-clustered WebLogic instances?

Question: We have WebLogic installed on two separate RHEL 5.6 servers. An Apache web server instance will be installed on each of those servers which will be configured to listen on 80 and 443 and redirect any requests from 80 to 443. SSL will terminate at the Apache web server and traffic between the Apache web server and the WebLogic servers will not need to be encrypted. I want the Apache instance to round robin load-balance to the WebLogic servers with sticky sessions and want the web server to be aware if one of the servers is down (and if so, not to route requests to the down server).
What Apache module(s) should I install to set up this configuration?
Note that I am NOT using WebLogic clusters (otherwise I might use WebLogic's WebLogic-Cluster-Aware Apache plugin which can handle the load balancing requirements)
Answer: you can use Apache's mod_proxy and its ProxyPass function or better use proxy balancer module(mod_proxy_balancer which supports stickiness) for redirecting the request on non clustered weblogic
And need to set RequestHeader set WL-Proxy-SSL true along with weblogic plugin enabled setting on each manged server
Check below link:
http://theheat.dk/blog/?p=916


Windows IoT - Mongodb - Raspberry

Question: Is it possible to install mongodb on Windows 10 IoT?
I've mounted a Windows 10 IoT disk on my Raspberry PI3 and would like to install a nodejs app that connects to a mongodb database.
Do you have any advice? or what would be the database the more appropriated?
Comment: This might help you: https://blogs.windows.com/buildingapps/2015/05/12/bringing-node-js-to-windows-10-iot-core/
Answer: The answer is yes and no.
Either from the MongDB download page or build-from-source page, it only has x86 and x64 versions available, which are all targeting Intel/AMD processors.
Depending on the CPU architecture your windows IoT is running on,

If it's an ARM based like raspberry pi, you cannot run MongoDB directly unless you can build form the source code targeting AnyCPU.
If it's Intel based like MinnowBoard Turbot Dual Core Board, technically, you can run MongoDB. However, due to the fact Windows IoT is a minimum version of windows Core, you might run into trouble missing some dependency libraries.

So in both cases, I don't see you can do it with ease, until we have official or community efforts to port MongDB to windows IoT, to which I'm really looking forward.
If you're using windows IoT for cloud-based application, you can go for windows azure databases.
Comment: I've installed MongoDB on Raspbian and Ubuntu MATE version of Raspberry pi
Comment: @Abhishek Parikh, but it's Windows IoT we're talking about!

Windows IoT - Mongodb - Raspberry


Standard errors of the MLEs

Question: Can anybody tell me how to find numerical values for standard errors of the MLEs of Weibull distribution using the uncensored real data set on the breaking stress of carbon fibres (in Gba) reported by Cordeiro GM, Lemonte AJ. The β-Birnbaum–Saunders distribution: an improved distribution for fatigue life modeling. Comput. Stat. Data Anal. 2011; 55: 1445–1461.
The data are (n = 66):
<code>3.70, 2.74, 2.73, 2.50, 3.60, 3.11, 3.27, 2.87, 1.47, 3.11, 3.56, 4.42, 2.41, 3.19,
3.22, 1.69, 3.28, 3.09, 1.87, 3.15, 4.90, 1.57, 2.67, 2.93, 3.22, 3.39, 2.81, 4.20,
3.33, 2.55, 3.31, 3.31, 2.85, 1.25, 4.38, 1.84, 0.39, 3.68, 2.48, 0.85, 1.61, 2.79,
4.70, 2.03, 1.89, 2.88, 2.82, 2.05, 3.65, 3.75, 2.43, 2.95, 2.97, 3.39, 2.96, 2.35,
2.55, 2.59, 2.03, 1.61, 2.12, 3.15, 1.08, 2.56, 1.80, 2.53
</code>
I use Mathematica so kindly give answer for Mathematica users.
Comment: Table 4 of the cited article provides the MLE and standard errors for the data set quoted here.  Do you want to know how find the MLE and standard errors in general?
Comment: Thanks for reply, where is table 4? Yes, I want to know how to find standard errors of MLE in general?
Comment: In the the article you cited in your question, @Abdus
Answer: The normal way to compute the standard error of an MLE is using the Fisher information (which is just the second derivative of the log-likelihood function, evaluated at the location of the MLE). Because of the properties of maximum likelihood, the variance of the MLE is given by a normal distribution centered on the value of the MLE but with variance equal to the inverse Fisher information. For simple distributions, this can often be calculated analytically, and you then simply apply the formula (which will depend on your MLE and your data).
A simple and fairly reliable alternative is to use the bootstrap to estimate the distribution around the MLE and then compute your standard error that way. Let $x_i\in X$ be an element in your data set, and let $n$ be the number of observations in $X$. A bootstrap of your data would be some $Y$ such that each $y_j$ for $1\leq j \leq n$ is an element of $X$ drawn uniformly at random from $X$. In other words, $Y$ contains $n$ values drawn from $X$ with replacement. Note that while $X$ is fixed, $Y$ is a random variable.
Let $\hat{\theta}(X)$ be your MLE on your original data. Then, $\hat{\theta}(Y)$ is the MLE on a bootstrap of your data. And, $\Pr(\hat{\theta}(Y))$ is the distribution of the MLE under the bootstrap. From there, you can compute the variance, standard deviation, and thus standard error of your MLE, which will be asymptotically close to whatever you would calculate using the Fisher information. This approach is attractive because it works even when you cannot compute the Fisher information for a particular model analytically.
If you already have code that computes $\hat{\theta}(X)$, then it should be pretty straightforward to write the code for the bootstrap estimation you need.
Comment: Nice answer.  You might also note that if the MLE is found through a numerical optimization, then often a numerical estimate of the Hessian (matrix of second derivatives) is available (ie, for newton or quasi-newton algorithms).  In this case, a cheap and dirty estimate of the information, and hence standard errors, is this numerical Hessian.

Standard errors of the MLEs


Python: problema com lista

Question: Alguém saberia explicar e como corrigir o porque ocorre o problema na saida abaixo quando uso números repetidos? Obrigado!
O retorno deve ser apresentado na forma inversa e sem apresentar o "0"

    lista = []

n = int(input("Digite um número: "))
while n != 0:
    lista.append(n)
    n = int(input("Digite um número: "))
    if n == 0:
        lista.append(n)

i = 0
while i < len(lista):
    if len(lista) <= 1:
        break
    lista.remove(lista[-1])
    print(lista[-1])

Comment: O que é suposto acontecer? Aqui parece estar a funcionar bem... Retorna na ordem inversa
Comment: Atente para o numero "5" ele muda de ordem, se pores um print(lista) pode ficar melhor a visualização.
Comment: Dê uma olhada [neste link](https://pt.stackoverflow.com/questions/192304/invertendo-sequ%c3%aancia-python-3/463887#463887)
Answer: O problema está nesta linha:
...
lista.remove(lista[-1])
...

Deve-se ao facto do remove() remover a primeira ocorrência do elemento, ou seja, para os inputs, "2,2,5,2", obtive:

2 2 2 5

Na primeira volta aparentemente estás a eliminar o ultimo elemento: remove(lista[-1]), que neste caso fica remove(2), MAS, este 2 que vai ser removido vai ser o primeiro e não o ultimo:
remove(x)

Remove the first item from the list whose value is x.

Tradução

Remove o primeiro item da lista cujo valor é x.

DOCS
Ou seja o que vai acontecer à tua lista ao longo do teu segundo loop while é:

[2, 2, 5, 2, 0] [2, 2, 5, 2] [2, 5, 2] [5, 2] [5]

E os prints da  lista[-1] que neste caso vão ser:

2225

(não esquecer que o 0 foi eliminado antes do primeiro print)
Se me permites vou apresentar uma sugestão de melhoria (para fazer exatamente isto) sem modificar muito o teu código:
lista = []
n = int(input("Digite um número: "))
while n != 0:
    lista.append(n)
    n = int(input("Digite um número: "))

while lista: # enquanto houverem elementos na lista, equivalente a while len(lista) > 0
    ele = lista.pop() # retirar o ultimo elemento da lista
    print(ele)

DOCS DE pop()
Ou se preferires eliminas na mesma pelo index:
lista = []
n = int(input("Digite um número: "))
while n != 0:
    lista.append(n)
    n = int(input("Digite um número: "))

while lista: # enquanto houverem elementos na lista, equivalente a while len(lista) > 0
    ele = lista[-1]
    del lista[len(lista)-1]
    print(ele)

E até podemos ir mais longe, se o objetivo for só imprimir e retirar os inputs que estão na lista em ordem inversa podemos eliminar o segundo while e tiramos os casts para int:
lista = []
n = input("Digite um número: ")
while n != '0':
    lista.append(n)
    n = input("Digite um número: ")

print('\n'.join(reversed(lista)))
lista.clear()

Comment: Excelente Miguel! Desconhecia o "pop", ele resolve perfeitamente o meu problema. Obrigado!
Comment: Sim mas também podes ir removendo por indexes @MárioAntônioRodeghiero , vou fazer para veres, 5 mins. Mas o importante é perceberes o porquê do que estava a acontecer. De nada, boa noite
Comment: Tranquilo, quando tiver tempo é só postar! Valeu a força, devo aparecer com mais duvidas esta semana. vlw!

Python: problema com lista


squid proxies disabled ssh access, how to resolve

Question: After installing squid proxies I'm unable to assess my server via ssh over port 21.
Please help me to gain access via ssh.
I am able to access the server via VNC.
OS: Centos 6.
Thank you.
Comment: ssh use port 22. Please clarify
Comment: Sorry for! It is port 22
Answer: Why are you ssh'ing on port 21? That's the ftp port (unless you manually changed it).
What port did you configure Squid to run on?
It sounds like one of the following has happened:

you typoed port 22 for ssh
you've overloaded a port (ie, are trying  to run more than one service on the same port)
you turned ssh off

You say you can get to your server via virtual console. Check to see what services are configured to run on startup:
chkconfig --list | grep ':on'

Is ssh listed? Check /etc/sshd/sshd.conf for what port it's configured to listen on.
Check to see what is holding port 22 (default ssh port) open:
netstat -an | grep 22
lsof -i:22

Check to see if sshd is even running:
ps aux | grep -i ssh

Check what port Squid is using by looking at /etc/squid/squid.conf
Lastly, you could refer to the Squid config I use on my proxy servers: https://antipaucity.com/2018/07/18/a-fairly-comprehensive-squid-configuration-for-proxying-all-the-http-things


Hypothesis experiment

Question: [Im am told to carry out a suitable hypothesis test to
determine whether the removal of the red cedar trees has reduced the mean number of leaves with rust spots.
I have stated the null hypothesis which is the mean number of leaves with rusts sports had decreased and alternate hypothesis which is the mean number of leaves with rust spots did not decrease.
I have worked out the variance for both years which for year 1 is 538.5 and year 2 is 361.6429. I have also worked out the mean for both the years which for year 1 the mean is 46.75 and year 2 the mean is 36.25.
I think I have to use the formula T=((xbar)- µ0)/(σ/sqrtn). however I am not given the mean in the description given to me
Answer: You must use paired samples $t$-test.
The values of differences are found in the table:
$$\begin{array}{c|c|c}
\text{Tree}&Y1&Y2&d\\
\hline
1&38&32&6\\
2&10&16&-6\\
3&84&57&27\\
4&36&28&8\\
5&50&55&-5\\
6&35&12&23\\
7&73&61&12\\
8&48&29&19\\
\hline
&\bar{Y_1}=46.75&\bar{Y_2}=36.25&\bar{x}_d=10.5\\
&&&s_d=12.2
\end{array}$$
The hypothesis test:
$$H_0:\mu_d=0\\
H_a:\mu_d>0\\
t=\frac{\bar{x}_d-0}{s_d/\sqrt{n}}=\frac{10.5}{12.2/\sqrt{8}}=2.43\\
t_{\alpha,n-1}=t_{0.05,7}=1.89\\
t>t_{\alpha} \Rightarrow \text{Reject $H_0$}.$$
Conclusion: There is a significant evidence for the removal of the red cedar trees reduces the mean number of leaves with rust spots.

Hypothesis experiment


C# nhibernate global search

Question: I have a system which will have about 6 different entities in the domain.
This is a C# winforms app with using Nhibernate. MSSql server. +- 5-10 users.
One of the feature requests is to have a single search bar whereby the user can type and search all of these entities with "Google like" flexibility (i.e. unstructured).
The best method i can think of implementing is to include a clob field on every domain object that also holds text of every field the object represents. my global search just does a like search on the clob field.
This just seems like
1. a mission to maintain (i.e. every object fields needs to be stored inside the clob field and updated with every change)
2. may scale terribly. as the system grows I am sure a LIKE search will get slower and slower causing system strain.
The system isnt going to be massive. I would be surprised if a single table stores more than 10,000 records but I dont like banking on that.
I have read about projects like Lucene.NET which work by indexing a dataset, but then the search will never be "live" but rather a search on the last index.
How have others managed to tackle this one?
Thanks!!
Comment: [NHibernate Search](https://nhibernate.jira.com/browse/NHSR) seems to fit the bill (see [Ayende's post](http://ayende.com/blog/3992/nhibernate-search)), I'll be trying that myself soon as well. It's based on Lucene.NET and offers (supposedly) fast full-text searching.
Comment: Does the user need to be able to search absolutely everything?  Does every search need to be 100% up to date, could it be 5/10 mins out of date?
Comment: Yep, NHibernate Search is the bridge you need. It creates/updates index entries whenever you insert/update/delete your entities, so the results would be up to date.
Answer: You're looking for a full-text search solution. Like I mentioned in my comment, what seems to fit the bill for your situation is NHibernate Search, see also Ayende @ Rahien's post on the subject.

C# nhibernate global search


Show the following ring does not have nontrivial two sided nilpotent ideal

Question: Let $k$ be a field. $A/k $ is a finite dimensional algebra with no non-trivial nilpotent two sided ideals. If $G/ k$ is Galois, then is it true that the ring $A \otimes _k G$ does not have any non-trivial two sided nilpotent ideal?
Answer: A finite-dimensional algebra over a field is semisimple if and only if it has no nontrivial nilpotent two sided ideals, so the statement follows from your previous question Show the following ring is semisimple.
Concerning the above statement about the connection between semisimplicity and nilpotent two-sided ideals:
A finite-dimensional algebra $A$ is semisimple if and only if its radical ideal $\text{rad}(A)$, the intersection of all maximal left ideals, is trivial (the vanishing of $\text{rad}(A)$ is equivalent to the existence of an injection $A\rightarrowtail M_1\oplus\ldots\oplus M_n$ for $M_i$ simple left $A$-modules, whch in turn is equivalent to the semisimplicity of $A$). Since $\text{rad}(A)$ is a two-sided, nilpotent ideal (nilpotency follows from Nakayama's Lemma), this proves "$\Leftarrow$". Conversely, suppose $A$ is semisimple and let $I\lhd A$ be a nontrivial two-sided ideal. By semisimplicity of $A$, there exists a complementary left ideal $J\lhd A$, that is, $A = I\oplus J$. Writing $1 = e_1 + e_2$ for $e_1\in I, e_2\in J$ then gives $e_1 = e_1\cdot 1 = e_1^2 + e_1 e_2$, so we get $e_1 e_2\in I\cap J=\{0\}$ and we get $e_1 = e_1^2$. Further, $e_1\neq 0$ since for $x\in I\setminus\{0\}$ we have $x = x\cdot 1 = x e_1 + x e_2$, so $x e_2 = 0$ and $0\neq x = x e_1$ by the same reasoning. Hence, any nontrivial two-sided ideal of $A$ contains a nontrivial idempotent, hence cannot be nilpotent.
Comment: Thank you. But can you see if there's a direct way to do this problem? I understand this one is equivalent to the previous one.
Comment: @user112564 There doesn't seem to be any good reason to handicap oneself by not applying the previous result. Any direct proof would largely repeat the work in that problem.
Comment: @user112564: I'm sorry, I don't know a more direct approach.


Como converter valores em porcentagem de uma coluna "total" em pandas?

Question: Olá! Estou aprendendo sobre Python e Numpy, porém estou com dificuldades em trabalhar com porcentagens. Considerando que a coluna total corresponde a 100%, como faço para obter as respectivas porcentagens de cada coluna com suas linhas?
Comment: Bom dia, pf coloque o código que já tentou e/ou uma amostra dos dados (.csv talvez) para facilitar a vida a quem o tentar ajudar. Nunca coloque imagens pois isso dificulta o copy/paste obviamente.
Answer: Tenta isto:
<code>import pandas as pd

df = pd.DataFrame({
    'a': ['Data Analisis', 'Machine Learning', 'Data Visualisation', 'Big Data', 'Deep Learning', 'Data Journalism'],
    'b': [1688, 1629, 1340, 1332, 1263, 429],
    'c': [444, 477, 734, 729, 770, 1081],
    'd': [60, 74, 102, 127, 136, 610],
})

df['Total'] = df.sum(axis=1) # somar valores da linha, caso nao tenha isto logo a partida

# calcular percentagens
df['b %'] = df['b']/df['Total']*100
df['c %'] = df['c']/df['Total']*100
df['d %'] = df['d']/df['Total']*100
print(df)
</code>
OUTPUT:
<code>                    a     b     c    d  Total        b %        c %        d %
0       Data Analisis  1688   444   60   2192  77.007299  20.255474   2.737226
1    Machine Learning  1629   477   74   2180  74.724771  21.880734   3.394495
2  Data Visualisation  1340   734  102   2176  61.580882  33.731618   4.687500
3            Big Data  1332   729  127   2188  60.877514  33.318099   5.804388
4       Deep Learning  1263   770  136   2169  58.229599  35.500231   6.270171
5     Data Journalism   429  1081  610   2120  20.235849  50.990566  28.773585
</code>
DEMONSTRAÇÃO
Comment: Muito obrigado! É este tipo de operação que eu gostaria de fazer, e não estava conseguindo, Miguel!


How to return the value of CLLocationManager didUpdateLocations in function?

Question: The problem iam having is that when i call the getCityName() function in other classes it returns nil because didUpdateLocations needs more time to run, how to solve this Async problem? and How to return the value of CLLocationManager didUpdateLocations in function?
import Foundation
import CoreLocation

class userCurrentLocation: NSObject, CLLocationManagerDelegate {

    var locationManager:CLLocationManager!
    var cityName:String!

     init(cityName:String) {
        super.init()
        setUp()
    }

    func getCityName() -> String?{
        return cityName
    }

    func setUp() {
        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }
    }

     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locations.last!.geocode { placemark, error in
            if let error = error as? CLError {
                print("CLError:", error)
                return
            } else if let placemark = placemark?.first {
                    self.cityName = placemark.locality ?? ""
                    manager.stopUpdatingLocation()
            }
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
}

extension CLLocation {
    func geocode(completion: @escaping (_ placemark: [CLPlacemark]?, _ error: Error?) -> Void)  {
        CLGeocoder().reverseGeocodeLocation(self, completionHandler: completion)
    }
}

Answer: class userCurrentLocation: NSObject, CLLocationManagerDelegate {

    var locationManager:CLLocationManager!
    var cityName:String!

    //1. Add a closure callback
    var didGetCity: ((String) -> Void)?

    //2. Send City Name when received
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locations.last!.geocode { placemark, error in
            if let error = error as? CLError {
                print("CLError:", error)
                return
            } else if let placemark = placemark?.first {
                    self.cityName = placemark.locality ?? ""

                    // Check for null
                    // Send city name in the completion block
                    if (self.didGetCity != nil){
                    self.didGetCity?(self.cityName)
                    }
                    manager.stopUpdatingLocation()
            }
        }
    }

    //3. Add code to your class where you need the city Name

    var City : String?

    let locationManager = userCurrentLocation (cityName: "")
        locationManager.didGetCity = {
            [weak self] city in
            self!.City = city
        }

Comment: There isn't much point in using `[weak self]` if you are just going to force unwrap it. I suggest that you either retain a strong `self` or use a conditional unwrap.
Comment: @Paulw11 You are right. It was an error from my end
Comment: Also, the `City` property should be `city`
Answer: You can use Delegate to tell the main class that everything is ready and use that value
import Foundation
import CoreLocation

protocol userCurrentLocationDelegate: class {
  func userCurrentLocationDidGetLocation(_ userLocation: userCurrentLocation)
}

class userCurrentLocation: NSObject, CLLocationManagerDelegate {

    var locationManager:CLLocationManager!
    var cityName:String!
    weak var delegate: userCurrentLocationDelegate?

 init(cityName:String) {
    super.init()
    setUp()
}

func getCityName() -> String?{
    return cityName
}

func setUp() {
    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
}

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    locations.last!.geocode { placemark, error in
        if let error = error as? CLError {
            print("CLError:", error)
            return
        } else if let placemark = placemark?.first {
                self.cityName = placemark.locality ?? ""
                manager.stopUpdatingLocation()
                delegate?.userCurrentLocationDidGetLocation(self)
        }
    }
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

}
extension CLLocation {
    func geocode(completion: @escaping (_ placemark: [CLPlacemark]?, _ error: Error?) -> Void)  {
        CLGeocoder().reverseGeocodeLocation(self, completionHandler: completion)
    }
}

and in Main class that calls this one use delegate from this callback to start calling the city name


Erro dizendo que a Activity não foi declarada no Androidmanifest.xlm?

Question: Este é o código do meu Androidmanifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".Activitys.mainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Activitys.loginActivity" />
</application>

E este é o erro:

Error running 'app': The activity 'loginActivity' is not declared in AndroidManifest.xml

Img:
Comment: cara só uma dica, nome de pacotes são sempre minúsculos, e nomes de classes sempre começão com a primeira letra maiúscula
Answer: O que pode acontecer é que está com mais um arquivo loginActivity ou ele não existe nesse diretório.
Para ter certeza de que existe ou de qual você está apontando, especifique o caminho completo da Activity para descobrir se realmente está correto.
Você pode declarar desta forma:
<activity
   android:name="com.example.Activitys.loginActivity"
   android:label="@string/app_name" >
</activity>


How to use both reactive and non reactive MongoDB template on Webflux Application

Question: Currently, I'm developing a springboot webflux app for my project, where I use reactive-mongo-template and other reactive implementations. Now I have a legacy spring boot application that is implemented by WebMvc ( here i dont use the real springboot app. just using the core services implemented with mongoDB configurations) and it's using (normal) mongo-template for its implemented services. In my webflux app I'm trying to use the old services defined in the legacy application.
For that i tried importing the legacy app using component scan (com.a.b.cservice.core.configuration) and got some error. The problem is it wont detect the application correctly and the non-reactive mongo template.
Does the spring support only 1 mongo connection? These are the error logs i got;
[main] WARN  o.s.b.w.r.c.AnnotationConfigReactiveWebServerApplicationContext - [] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mapperDAOSpringConfigurations': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource
    [com/a/b/cservice/core/configuration/MongoConfigurations.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: com.mongodb.connection.ClusterSettings.getDescription()Ljava/lang/String;

***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    com.mongodb.connection.DefaultClusterFactory.createCluster(DefaultClusterFactory.java:182)

The following method did not exist:

    com.mongodb.connection.ClusterSettings.getDescription()Ljava/lang/String;

The method's class, com.mongodb.connection.ClusterSettings, is available from the following locations:

    jar:file:/C:/Users/abc/.m2/repository/org/mongodb/mongodb-driver-core/4.0.5/mongodb-driver-core-4.0.5.jar!/com/mongodb/connection/ClusterSettings.class
    jar:file:/C:/Users/abc/.m2/repository/org/mongodb/mongo-java-driver/3.12.7/mongo-java-driver-3.12.7.jar!/com/mongodb/connection/ClusterSettings.class

The class hierarchy was loaded from the following locations:

    com.mongodb.connection.ClusterSettings: file:/C:/Users/abc/.m2/repository/org/mongodb/mongodb-driver-core/4.0.5/mongodb-driver-core-4.0.5.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of com.mongodb.connection.ClusterSettings

Are there any workaround to work the legacy app with the webflux application with mongoDb? Or do i need to keep it as a seperate micro-service and call the relevent endpoints?
Answer: after a few works and searches, I found the issue is not related to Webflux. purely a mongo client collision between legacy application and webflux drivers. so I exclude the drivers from legacy and imported the spring-boot-starter-data-mongodb along with the reactive spring-boot-starter-data-mongodb-reactive version. (both are using the same version 2.3.5.RELEASE).
ps: found the same issue on here Spring boot 2.0.5.RELEASE and mongo 4.0 connection issues
Comment: Hi @namila007 , can you please tell me how did you manage to use both non-reactive and reactive repos? I have a similar need and I'm struggling to figure out the right config ([https://stackoverflow.com/questions/72731742/spring-mongodb-use-nonreactive-and-reactive-repository-at-once]here my SO question). Thank you!


megaraid: Logical Drives at different RAID levels

Question: I am currently using a SuperMicro machine that has an on-board LSI 2208 controller (MegaRAID class).
I want to create a single array from two drives and then carve that up into:

one RAID1 100GB logical drive
one RAID0 logical drive taking up the rest of the array

Can I do this with the LSI2208?
If not, is there a different LSI controller that supports this?
Comment: From a quick skim of [the manual](http://www.lsi.com/downloads/Public/MegaRAID%20Common%20Files/SASUG_51530-00_RevG.pdf) I did not see how to do this. So have an upvote and I wish you good luck.
Comment: Contact LSI would be my suggestion.
Answer: By partitions, do you mean that you want to create a single RAID array and then create more than one logical drive on that array?
<code># Clear the RAID config
megacli cfgclr -a0

# Create a RAID10 array from 4 drives with two logical drives,
# one 100GB and one comprised of the rest of the space
megacli cfgldadd -r1 "[?:0,?:1,?:2,?:3]" WB ADRA NoCachedBadBBU -sz100000 -sz0 -a0
</code>
Unfortunately, all logical drives created from a single array must be at the same RAID level.
I would suggest putting the disks into JBOD mode and doing the RAID in software:
<code>megacli pdmakejbod -physdrv "[?:0,?:1]" -a0
</code>
Comment: Kind of.  Let me try to translate into LSI-speak.  Let's say I have two physical drives: Drive0 and Drive1.  I want to take 100GB of Drive0 and 100GB of Drive1 and mirror it (RAID1).  I then want to take the remainder of Drive0 and create a second logical drive with the remainder of the space.  Finally I want to take the remainder of Drive1 and create a third logical drive with the rest of it's space.  In the end I would have a RAID1 for my OS, and two RAID0s.  Make sense?
Comment: I edited your question to better word what you are trying to accomplish. Please feel free to modify it if it doesn't actually reflect what you're doing.
Comment: Thanks for the input everyone.  I've sent an email to LSI just to see what they say.  We will most likely go with the software raid suggestion.
Answer: RAID arrays are made up of physical drives, not partitions. Once you have added the disks to a RAID array you can then create multiple logical or virtual disks on the array using megacli. Those virtual disks can then be partitioned using FDISK or various other file system utilities as if they were physical drives.
Comment: You can do this on HP SmartArray controllers to be fair, mad I know but you can, can't think of a great reason to do it but there you go - no idea about megaraid however.
Comment: @Chopper3 You have any documentation on that? A quick search for `HP SmartArray raid partitions` didn't show anything that talked about using Partitions to create a RAID array. I also looked through the HP Array Configuration Utility on one of our servers and didn't see it in there either.


Proving that the complex numbers: additive/multiplicative identity is unique

Question: From an example/solution from my study guide that I was given:
a) Write (x,y) + (u,v) = (x,y) and point out how it follows that the complex number 0 = (0,0) is
unique as an additive identity
b) Likewise, write (x,y) (u,v) = (x,y) and show that the number 1 = (1,0) is a unique multiplicative identity.
Proof
a) Let $(u,v)$ be any complex number such that $(x,y) + (u,v) = (x,y)$ for all $(x,y) ∈ C$.
Then surely:
$(0,0) = (0,0) + (u,v)$  (by assumption)
$= (u,v)$
b)Let $(u,v)$ be given such that $(x,y) (u,v) = (x,y)$ for all $(x,y) ∈ C$.
Then
$(1,0) = (1,0) (u,v)$ (by assumption)
$= (u,v) (1,0)$
$= (u,v)$
My Question
How does this prove that its "$0 = (0,0)$ is unique as an additive identity" we just took one example that happens to be correct. I don't see how this proves uniqueness
Here is my understanding(of what it should be):
a) let $x = (x,y)∈ C$, let $a = (v,u)$ that is the additive identity, thus
$x + a = x$ {1} and $x+b=x$ {2}
Subtract {2} from {1} thus
$x + a-(x+b) = x-x$
thus $a-b = 0$ thus $a=b$
now we know that the additive identity is unique. we can prove that $a=b=0$ by subbing 0 for x into {1} eg:  $0 + a = 0$ thus $a =0$ thus concludes the proof.
(OR)
simply could we just do $x + a = x$, subtract $x$ from each side
thus $a=0$ for all $x∈ C$
b)let $x = (x,y)∈ C$, let $a = (v,u)$ that is the multiplicative identity, thus
$xa = x$ {1} and $xb=x$ {2}.
Subtract {2} from {1} thus
$xa-xb = x-x$
$x(a-b) = 0$
as $x$ is arbitrary, thus $(a-b) = 0$, thus $a=b$
now by subbing 1 for a in $xa = 1$ we get $1a=1$ thus $a =1$ thus concluding the proof.
More Questions
(1) I would like to know whether any of my proofs are valid to proving the uniqueness and
(2) and my first question How does this prove that its "$0 = (0,0)$ is unique as an additive identity"
I would really appreciate any help/ insight you can offer
Comment: I would say that in general in complex arithmetic $(x,y)+(u,v)=(x+u,y+v)$ and $(x,y)(u,v)=(xu-yv,xv+yu)$.  You want these to be equal to $(x,y)$ in each case for all $x$ and $y$, and can solve two simultaneous equations to find unique $u$ and $v$ for that case
Comment: Here is another way it was proven https://stemjock.com/STEM%20Books/Churchill%20Complex%20Variables%208e/Chapter%201/Section%202/Exercise%208/ChurchillCV8es2e8.pdf
I understand this as well apart from the final stage of part b)
I just do get the way in the book so I must be misunderstanding something
Comment: @Henry wow that was a fast reply, I like your way as it keeps the arbitrary vairable  and it feels more complete. but the one in the book seems so simple but I don't feel like it solves it
Answer: tl; dr: When we write $(0, 0) = (0, 0) + (u, v) = (u, v)$, we're showing that an arbitrary identity element $(u, v)$ for addition is equal to a particular identity element $(0, 0)$; and similarly for multiplication.

In the hope of illustrating why both proofs are correct, let's reduce matters to the abstract details: Suppose $A$ is a non-empty set equipped with a binary operation $*$, and suppose $e$ and $e'$ are identity elements for $*$, i.e., that
\begin{align*}
&\left.
\begin{aligned}
  e * x = x \\
  x * e = x
\end{aligned}
\right\}\quad\text{for all $x$ in $A$;}
&&\left.
\begin{aligned}
  e' * x = x \\
  x * e' = x
\end{aligned}
\right\}\quad\text{for all $x$ in $A$.}
\end{align*}
Since $x * e' = x$ for all $x$, in particular (taking $x = e$) we have $e * e' = e$. Similarly, since $e * x = x$ for all $x$, in particular (taking $x = e'$) we have $e * e' = e'$. By transitivity of equality, $e = e * e' = e'$.
Comment: @Reuben - the interesting thing about the general proof Andrew D. Hwang gives here is that it requires practically nothing about either the set $A$ or the binary operation $*$. Unlike your proofs, it does not require the existence of inverses. It does not even require that the operation be commutative or associative, which your proofs also use in the background. In fact, it doesn't even require that $A$ have an identity under $*$. It just says that *if* $A$ has an identity, it can have at most one. It applies to many, many situations, not just complex numbers.


A function that checks the average of dict items

Question: I'm trying to send a dictionary into a function that caculated the average, I believe my function is good but I'm having trouble with sending the dictionary
my_dict = {"first": 100, "second": 0, "third": 200}

def avg(dict):

    sum=0
    count=0
    for k,v in dict:
        sum = sum+v
        count +=1
    return(sum/count)

result = avg(**my_dict)

print(result)

The output should be 100 that goes into "result"
Comment: sum(my_dict.values()) / len(d)
Comment: The output should be 100, right? Or do you wish to do something else?
Answer: my_dict = {"first": 100, "second": 0, "third": 200}
def dictavg(your_dict):
    return sum(your_dict.values())/len(your_dict)
print(dictavg(my_dict))

Answer: Pass your dictionary directly, not via the ** dictionary unpacking operator. Do the unpacking within your function instead: iterating dict.items gives key-value pairs, but here you can use dict.values.
Also, never shadow built-ins. So don't use dict, sum, etc as variable names.
This would work:
def avg(d):

    val_sum = 0
    count = 0
    for v in d.values():
        val_sum += v
        count += 1
    return(val_sum/count)

result = avg(my_dict)  # 100.0

You can also use the built-ins sum and len:
result = sum(my_dict.values()) / len(my_dict.values())

Or use statistics.mean:
from statistics import mean

result = mean(my_dict.values())  # 100

Comment: @YOLO see my comment above
Comment: I wonder how to rewrite this if we were to pass as unpacking operator.
Comment: @YOLO, Unpacking doesn't help you solve your problem. So I advise you don't do it.
Comment: @jpg actually it is solvable with unpacking, just very superfluous. `f = lambda **kwargs: sum(kwargs.values())/len(kwargs)` then `f(**my_dict)`
Comment: @DeepSpace, Yes, but that doesn't help. It's an extremely poor use of function arguments.
Answer: Drop the asterisks and use .items() on the dict
my_dict = {"first": 100, "second": 0, "third": 200}

def avg(dict):

    sum=0
    count=0
    for k,v in dict.items():
        sum = sum+v
        count +=1
    return(sum/count)

result = avg(my_dict)

print(result)

Comment: `k` is not being used. You can just sum the values with `sum(dict.values())`.
Comment: Oh yeah, true.. I only changed the bits it failed on, didn't re-write it (or I would have also changed the poorly chosen variable names)
Answer: Just try:
my_dict = {'first': 100, 'second': 0, 'third': 200}
avg = sum(my_dict.values()) / len(my_dict)

Answer: You cannot use the following statement with a dictionary:
for k, v in dict:

instead there is a way to receive a list of the keys or the values of the dictionary using the methods keys() or values() respectively. these methods return a list of the dictionary keys or the dictionary values and then you can iterate over them. Also there is a method which returns a list of tuples of key and value - items().
So any of these should work for you:
my_dict = {"first": 100, "second": 0, "third": 200}

def avg(dicti):

    total_sum=0
    count=0
    for key in dicti.keys():
        sum += dicti[key]
        count +=1
    return(sum/count)

result = avg(my_dict)

print(result)

or:
my_dict = {"first": 100, "second": 0, "third": 200}

def avg(dicti):

    total_sum=0
    count=0
    for value in dicti.values():
        sum += value
        count +=1
    return(sum/count)

result = avg(my_dict)

print(result)

Answer: Dont use keywords as variable names, such as dict or sum. You can send your whole dictionary, and iterate over the items:
my_dict = {"first": 100, "second": 0, "third": 200}

def avg(a_dict):
    total=0
    count=0
    for k,v in a_dict.items():
        total = total+v
        count +=1
    return(total/count)

result = avg(my_dict)

print(result)

Note that the avg is 100.


Is $page only an array important for theming purposes?

Question: I know Wordpress theming, but I am a beginner with Drupal theming. Drupal render array totally confuses me.

Do all modules put their content in the $page array?
Is $page only an array that is important for theming purpose? If the answer is no, then what kind of renderable arrays are available in Drupal for advanced theming?
Answer: There is just a type of render array, and it is the one described in drupal_render(); the form API extends the render array with properties necessary to validate/submit a form element. The purpose of a render array is just to theme elements present in a page; it is not used for other purposes, if not rendering/theming.
The output of a module is always part of a render array, except when a module implements code similar to the following one.
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view() {
    echo "<title>Error</title>Error page";
    drupal_exit();
  }

If you visit http://example.com/abc/def, there isn't any render array involved in rendering the page.
Comment: sir thanks for your reply and  editing. but sir i am still confuse. can you please explain answer in simple word and with theming example. i understand nothing regarding answer to my first quertion(Do all modules put their content in the $page array?)
Comment: Do all modules put their content in the `$page` array? Yes, except in one case. Is $page only an array that is important for theming purpose? The render array is used only for theming, so yes.


Script para voltar para a página anterior atualizada?

Question: Bom, eu queria algo que fizesse que quando um pessoa clicasse para ir para uma página ela fosse redirecionada para a página anterior.. Mas a página atualiza...
É que eu fiz um pequeno sistema de comentários, quando clico para comentar ele vai para uma página "InsertComment" mas preciso que ele volte para a página original...
Comment: Não deveria ser o caso de redirecionar automaticamente apos o form ser submetido?
Answer: Podes fazer isso das seguintes maneiras:
Go Back

ou usando:

Answer: Caso seja de forma automática, após o form ser submetido, metes na página que object form vai abrir object seguinte código:

Answer: Outras possibilidades para voltar para a página anterior:
history.go(-1);

window.open(document.referrer,'_self');

location.href = document.referrer;

Exemplos para teste:

<button onclick="history.go(-1);">Voltar 1</button>

<button onclick="location.href = document.referrer;">Voltar 2</button>

<button onclick="window.open(document.referrer,'_self');">Voltar 3</button>

Referência:
http://www.guj.com.br/t/como-voltar-para-a-pagina-anterior-jsp/153165/3


Can't MERGE with null values; 'Cannot merge node using null property value' in neo4j

Question: I have a column in a csv that looks like this:

I am using this code to test how the splitting of the dates is working:
LOAD CSV WITH HEADERS FROM
'file:///..some_csv.csv' AS line
WITH
SPLIT(line.date_of_birth, '/') AS date_of_birth
return date_of_birth;

This code block works fine and gives me what I'd expect, which is a collection of three values for each date, or perhaps a null if there was no date ( e.g,
[4, 5, 1971]
[0, 0, 2003]
[0, 0, 2005]
 . . .
null
null
 . . .

My question is, what is this problem with the nulls that are created, and why can't I do a MERGE when there are nulls?
LOAD CSV WITH HEADERS FROM
'file:///..some_csv.csv' AS line
WITH
SPLIT(line.date_of_birth, '/') AS date_of_birth, line
MERGE (p:Person {
 date_of_birth: date_of_birth
});

This block above gives me the error:
Cannot merge node using null property value for date_of_birth

I have searched around and have only found one other SO question about this error, which has no answer. Other searches didn't help.
I was under the impression that if there isn't a value, then Neo4j simply doesn't create the element.
I figured maybe the node can't be generated since, after all, how can a node be generated if there is no value to generate it from? So, since I know there are no ID's missing, maybe I could MERGE with ID and date, so Neo4j always sees a value.
But this code didn't fare any better (same error message):
LOAD CSV WITH HEADERS FROM
'file:///..some_csv.csv' AS line
WITH
SPLIT(line.date_of_birth, '/') AS date_of_birth, line
MERGE (p:Person {
 ID: line.ID
,date_of_birth: date_of_birth
});

My next idea is that maybe this error is because I'm trying to split a null value on slashes?  Maybe the whole issue is due to the SPLIT.
But alas, same error when simplified to this:
LOAD CSV WITH HEADERS FROM
'file:///..some_csv.csv' AS line
WITH line
MERGE (p:Person {
 subject_person_id: line.subject_person_id
,date_of_birth: line.date_of_birth
});

So I don't really understand the cause of the error.  Thanks for looking at this.
EDIT
Both @stdob-- and @cybersam have both answered with equally excellent responses, if you came here via Google please consider them as if both were accepted
Comment: I get this error even though I have no null or empty values whatsoever.
Comment: Figured it out: you will also get this error when importing from CSV and the column is inside backticks (for ex. due to spaces) AND YOU HAVE FOREIGN CHARACTERS.
Answer: As @cybersam said,MERGE doesn't work well with queries where the properties are set within the scope in null. So, you can use ON CREATE and ON MATCH:
LOAD CSV WITH HEADERS FROM
  'file:///..some_csv.csv' AS line
MERGE (p:Person {
  subject_person_id: line.subject_person_id
})
  ON CREATE SET p.date_of_birth = line.date_of_birth
  ON MATCH SET p.date_of_birth = line.date_of_birth

Comment: If`ON CREATE` and `ON MATCH` do exactly the same `SET`, then just replace the 2 clauses with a single `SET`.
Answer: Some Cypher queries, like MERGE, do not work well with NULL values.
The somewhat tricky workaround for handling this situation with MERGE is to use the FOREACH clause to conditionally perform the MERGE. This query might work for you:
LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line
FOREACH (x IN CASE WHEN line.date_of_birth IS NULL THEN [] ELSE [1] END |
  MERGE (:Person {date_of_birth: SPLIT(line.date_of_birth, '/')})
);

[UPDATE with answer for "simplified" query]
Keep potentially-null properties out of your MERGE clause. Also, MERGE clauses must be carefully crafted to avoid creating unwanted extra nodes by limiting the properties specified in the MERGE.
LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line
MERGE (p:Person {subject_person_id: line.subject_person_id})
SET p.date_of_birth = line.date_of_birth

Answer: Another solution that I've been rather fond of is to just tell cypher to skip rows in which the field of interest is NULL as follows:
USING PERIODIC COMMIT #
LOAD CSV WITH HEADERS FROM
'file:///.../csv.csv' AS line
WITH line, SPLIT(line.somedatefield, delimiter) AS date
WHERE NOT line.somedatefield IS NULL

[THE REST OF YOUR QUERY INVOLVING THE FIELD]

Comment: Very elegant solution IMO.
Comment: `WHERE NOT` was key for me
Answer: Or you can use COALESCE(n.property?, {defaultValue})
Comment: why the question mark after `property`? and are the {}s supposed to mean a required value as in the Backus-Naur notation?
Answer: Following with Vojtech Ruzicka's approach, you can use something like this your_value:COALESCE(line.your_value, 'default value')
Link to the documentation here, in case you need more information.


add empty cell in dynamic twig table

Question: Hi I've got the following array
Array
(
    [6] => Array
        (
            [id] => 6
            [immobile] => 3
            [interno] => 1A
            [condomino] => Giuseppe Rossi (P)
            [Tabella generale] => Array
                (
                    [spesa] => 187.50
                    [millesimi] => 250.0000
                )

            [Tabella scale] => Array
                (
                    [spesa] => 125.00
                    [millesimi] => 250.0000
                )

        )

    [7] => Array
        (
            [id] => 7
            [immobile] => 3
            [interno] => 1A
            [condomino] => Francesco Rossi (Co-P)
            [Tabella generale] => Array
                (
                    [spesa] => 187.50
                    [millesimi] => 250.0000
                )

            [Tabella scale] => Array
                (
                    [spesa] => 125.00
                    [millesimi] => 250.0000
                )

        )

    [9] => Array
        (
            [id] => 9
            [immobile] => 3
            [interno] => 1A
            [condomino] => Alessandro Rossi (I)
            [Tabella generale] => Array
                (
                    [spesa] => 0.00
                    [millesimi] => 250.0000
                )

            [Tabella scale] => Array
                (
                    [spesa] => 125.00
                    [millesimi] => 250.0000
                )

        )

    [8] => Array
        (
            [id] => 8
            [immobile] => 5
            [interno] => 1B
            [condomino] => Alessandro Rossi (P)
            [Tabella generale] => Array
                (
                    [spesa] => 375.00
                    [millesimi] => 250.0000
                )

        )

)

And I need to convert it into a table using twig, this is what i've achieved so far

But i need to achieve this instead:

This is my code so far:

          {% for titolo in ripartoPreventivo|first|keys|slice(1) %}
            {{titolo}}
          {% endfor %}

           Totale

      {% for sub_array in ripartoPreventivo %}

            {% for value in sub_array|slice(1,2) %}
              {{ value|raw }}
            {% endfor %}

            {% for value in sub_array|slice(3) %}

                € -{{ value.spesa|raw }} (mill. {{ value.millesimi|raw }})

            {% endfor %}

            {% set sum = 0 %}

            {% for value in sub_array|slice(3) %}
              {% set sum = sum + value.spesa %}
            {% endfor %}

             € -{{ sum|number_format(2, '.', ',') }}

      {% endfor %}

As you can see from the pictures I need to add an empty cell if the dynamic key in the array doesn't exist, instead with my code it put the total where the empty cell should be, any help? many thanks
Comment: What I don't understand is that you say the data is generic, but you are actually accessing some parts of the array with your `slice(1,2)` and `slice(3)`, `value.spesa`. For this reason, I thought that accessing the fields by name was more logical than by index (which moves if you have missing entries). If you access it by key then you can do `{{ sub_array.interno|default('') }}`
Comment: Isn't it possible to access your values by keys instead of indexes? Is it because you want to keep it "generic" with the loop over the `` items? If not, I would print the `` items manually as they are directly representing some different data. Or you could loop over the data before the Twig template and fill the missing values with ` ` so that the empty cells display correctly with a border.
Comment: Hi @PatrickJanser thanks for your answer I need to keep it generic because it is a dynamic array of keys,values so the number of  is not always the same
Comment: Yes, sorry I didn't explain it correctly the first four keys (id, immobile,interno, condominio) are always called (id, immobile,interno, condominio) what is dynamic is the other keys.
Answer: Well same as you printed the keys to use them as headers, you can use those keys to output the data
Do note: This will only work if the structure of the data remains the same, meaning you only use an array to store the info about spesa and millesimi
In the snippet below I use the test iterable to determine whether the value is an array, based on that the code assumes, if it's an array the keys spesa and millesimi are present.
If you have any other array based values you would need to perform some extra checks

        {% for key in ripartoPreventivo|first|keys|slice(1) %}
            {{ key }}
        {% endfor %}
        Total

    {% for row in ripartoPreventivo %}

        {% for key in ripartoPreventivo|first|keys|slice(1) %}

            {% set value = row[key]|default(' ') %}
            {% if value is iterable %}
                € -{{ value.spesa|raw }} (mill. {{ value.millesimi|raw }})
            {% else %}
                {{ value|raw }}
            {% endif %}

        {% endfor %}

            500

    {% endfor %}

demo

Just an extra FYI:
Keep in mind that it is possible not all keys will be present in the table as you are using ripartoPreventivo|first|keys|slice(1). This would mean if the first row in the set doesn't have the key Tabella Scale present, it will never be shown in the table!
Comment: Hi @DarkBee I've tested your solution and works fine, it is exactly what i was looking for. Ialso discovered the iterable function. I've accepted your answer
Comment: Hi is there a solution to fix the problem if first row in the set doesn't have the key?
Comment: See the answer below, you should need to restructure the data in advance
Answer: I guess you could do this before rendering your twig. It's adding empty data as the index  Tabella scale. If the index exists, so the row isn't affected by the code
$data is your initial array
$initial = [
    'spesa' => '',
    'millesimi' => '',
];
foreach($data as $item) {
    if(!isset($item['Tabella scale'])) {
        $item['Tabella scale'] = $initial;
    }
}

EDIT :
Based to the comments, I would suggest you to do this (not the cleanest)
$modele = [
    "id" => '',
    "immobile" => '',
    "interno" => '',
    "condomino" => '',
    'Tabella generale' => [
        'spesa' => '',
        'millesimi' => '',
    ],
    'Tabella scale' => [
        'spesa' => '',
        'millesimi' => '',
    ]
];
$data = [
    [
        "id" => 10,
        "condomino" => '20',
        'Tabella generale' => [
            'spesa' => '100',
            'millesimi' => '25',
        ],
    ],
    [
        "id" => 22,
        "interno" => '15',
        'Tabella scale' => [
            'spesa' => '100',
            'millesimi' => '25',
        ],
    ],
];
//add all fields from model to all data
foreach($data as $key => $item) {
    //to add fields, use a simple merge
    //be careful of array_merge order
    //if array_merge($item, $modele), your values will be erased
    $new_item = array_merge($modele, $item);
    $data[$key] = $new_item;
}

//reorder based on model keys
$reordered = [];
foreach($data as $row) {
    $item = [];
    #loop over your model keys to have model's order
    foreach($modele as $key_model => $modele_value) {
        #add to your new ordered item at the index of the model, your current value
        $item[$key_model] = $row[$key_model];
    }
    $reordered[] = $item;
}

Comment: Hi thanks for your replay, the key 'Tabella scale' is dynamic and is not always called 'Tabella scale' the same for the other keys
Comment: @pippo: I personnaly find @MorganTartreau's solution intelligent. In some way, if your data is generic it must reflect a certain model so should have some default values, such as an empty value. You could loop over all items first to create the model (list of existing fields for all the items). Then loop a second time over this data to set the missing values to `' '` or `''`.
Comment: Hi PatrickJanser yes it make sense the only problem with code posted by MorganTartreau is that it checks if 'tabella scalse' is isset but I don't always have a key called 'tabella scale' as these keys are dynamic also in other scenario it could be the key 'tabella generale' that doesn't have any values so how can I apply MorganTartreau code dynamically?
Comment: This is why I propose you first loop over all items in order to create the *model* which represents the list of all the existing field names. Then, with the second loop over the items you check that each field name is set. If it isn't then you set it to the empty value.

add empty cell in dynamic twig table


Inductive proof of symmetric identity of binomial coefficients

Question: I'm trying to proof the symmetric identity ${n \choose k} = {n \choose n-k}$ using induction.
I have the base case $${0 \choose 0} = 1 = {0 \choose 0-0}$$ for k=0 and $${0 \choose k} = 0 = {0 \choose n-k}$$ for every other k>0. My hypothesis is ${n \choose k} = {n \choose n-k}$ for any natural number, and I need to show that ${n+1 \choose k} = {n+1 \choose n-k+1}$. I used Pascal's Identity to show that $${n+1 \choose k} = {n \choose k} + {n \choose k-1}$$ which is equal to $${n! \over (n-k)!k!} = {n! \over (n-k+1)!(k-1)!} $$. At this point I don't know how to go on. I am generally not sure if I have done the induction steps correctly (I am a biology student), and would be very appreciating of any help.
Answer: ${n \choose k}= \frac{n!}{(n-k)! k!}=\frac{n!}{k! (n-k)!}={n\choose {n-k}}$
Did I misunderstand the purpose of this question?
Comment: I am trying to do an inductive proof for which I am asking for help.
Comment: @Quebec27 Well you can write the above sentence after you assume the induction hypothesis... I would say it is really a bad idea to write an inductive proof, since the induction hypothesis will not help you. Especially when you write the formula for ${n\choose k}$ out, the conclusion becomes obvious. In case you want some exercise, try to prove $1^2+2^2+\dots+n^2=\frac{n(n+1)}{2}$, by induction.
Comment: Yeah, I wanted to see for myself how induction can be used in not so "convenient" cases. Thanks anyway.
Answer: It is more complicated than necessary, but your induction argument can be completed.  Starting from
$$\binom{n+1}{k} = \binom{n}{k} + \binom{n}{k-1}$$
apply the induction hypothesis to both terms on the right side (remember the induction hypothesis applies when the top is $n$ with any value on the bottom), which gives
$$\binom{n+1}{k} = \binom{n}{n-k} + \binom{n}{n-k+1}$$
Now apply the Pascal identity once more on the right side, to get what you want:
$$\binom{n+1}{k} = \binom{n+1}{n-k+1}.$$
Comment: Okay thank you for your helpful response! One more thing, is the base case with ${0 \choose k} = {0 \choose 0-k}$ for any k>0 correct?
Comment: @Quebec27 Yes.  In fact, for nonnegative $n$, if we define $\binom{n}{k} = 0$ for all integers $k<0$ or $k>n$, then Pascal's identity will still hold.  Just imagine extending Pascal's triangle with 0's indefinitely to the left and right on each row, and check that Pascal's identity still works.
Answer: As k99731 has pointed out, this result follows immediately from the definition.
Instead consider the following recurrence relation $A_{n,k}$ where we define $$ A_{n,k} = A_{n-1,k} + A_{n-1,k-1}$$ for all integers $n$ and integers $k$ such that $1\leq k\leq n$ and set the boundary conditions $A_{n,n}=A_{n,0}=1$ for every integer $n$.
Can you use induction to prove that $A_{n,k}=A_{n,n-k}$ for all $n,k$?
Hint:
Let $S(n)$ be the statement that $A_{n,k}=A_{n,n-k}$ for all $1\leq k\leq n$. Can you prove that $S(n+1)$ will be true if $S(n)$ is true?


When is a topological space uniquely uniformizable?

Question: In general, multiple uniformities can induce a given topology.  But if a topological space is a compact Hausdorff space, then there is only one uniformity which induces its topology.  The formal way to say it is, compact Hausdorff spaces are uniquely uniformizable.
My question is, what other spaces are uniquely uniformizable?  Are there specific examples of such spaces, and is there a general chatacteization of such spaces?
Answer: Engelking (in General topology, (2nd ed.)) mentions these spaces in exercises 8.5.11 and 8.5.12 with a reference to

Doss, R. On uniform spaces with a unique structure, Amer. J. Math. 71 (1949), 19-23.

Looking for that reference online I quickly found related papers and looking in online databases of papers could get you many more perhaps.
Ex. 8.5.11 states that such spaces $X$ are Tychonov spaces that have a unique Hausdorff compactification (up to equivalence).
Ex. 8.5.12. asks to show that in such spaces $X$, if they are not compact,  can have no complete uniformity on $X$, with a reference to

Dieudonné, J. Sur les espaces uniformes complets, Ann. Sci. École Normale Sup. 56 (1939), 277-291.

Willard (General Topology) mentions them in exercise 41F where one has to prove that $|\beta X - X| \le 1$ is equivalent to having a unique uniformity (or proximity) on a Tychonoff space $X$. (Where $\beta X$ is the Čech-Stone compactification of $X$, as usual.)
This means that $\omega_1$, the first uncountable ordinal in its order topology, is an example of a compact and uniquely uniformisable space, as $\beta \omega_1 = \omega_1 +1$, and similarly for the long line, which has its one-point compactification as its Čech-Stone compactification. Or of course spaces like $\beta X \setminus \{p\}$ for some remainder point $p \in \beta X$.
Such spaces are also mentioned in the classic book by Gilman and Jerrison, Rings of continuous functions, how call such spaces almost compact in exercises 6J and 15R. The former states the equivalence in terms of the Čech-Stone compactification again, as Willard does while the latter has some more formulations for such $X$:
TFAE for a Tychonoff space $X$:

$X$ has a unique compatible uniform structure.
Every continuous mapping from $X$ into any uniform space $Y$ is uniformly continuous in every compatible uniformity on $X$.
Every function in $C(X)$ is uniformly continuous in every compatible uniformity on $X$.
Every function in $C^\ast(X)$ is uniformly continuous in every compatible uniformity on $X$.
Every function in $C^\ast(X)$ is uniformly continuous in every precompact (definition in the book) compatible uniformity on $X$.
$X$ admits only one precompact uniformity.
$X$ has a unique compactification.


Compiling ARM on Mac for iOS

Question: This is a bit similar to Compiling ARM .s file on Mac
Especially the response given by Simon Urbanek, thanks for that!
I'm basically wondering how to make this asm file work on a jailbroken iPhone.  Currently, I am cross compiling and attempting to place the object on the iPhone and run it without success because its not meant for the iPhoneOS obviously, its just ARM code with no Mach-O header.  Any idea how to get this working?  -isysroot may be the answer, but I've provided the SDK file as its input and I don't get a mach-o header.
Also, I would also love to know if there is a way to compile ASM code on the iphone itself without using inline gcc.
Anyways, here is the current workflow:
[On Mac]
<code>$ cat foo.s
mov r0, r1

$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/llvm-gcc-4.2/bin/llvm-gcc-4.2 -arch armv6 -c foo.s

$ file foo.o
foo.o: Mach-O object arm

$ otool -v -t foo.o
foo.o:
(__TEXT,__text) section
00000000    e1a00001    mov r0, r1
</code>
[On iPhone]
<code>$ file foo.o
foo.o: Mach-O object arm

$ otool -v -t foo.ofoo.o:
(__TEXT,__text) section
00000000    e1a00001    mov r0, r1
</code>
Answer: It's not enough to compile the code, you also have to link it to produce an executable from the object code:
<code>$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/llvm-gcc-4.2/bin/llvm-gcc-4.2 -arch armv6 foo.o -o foo
$./foo
</code>
If you omit the C/C++ part of this, and start right from the assembly step, you can use this document for understanding:
http://markuskimius.wikidot.com/programming:explain:compiling
Comment: Correct, yes I forgot that step, but at this point it would still be a malformed mach-o file since there is no header.  the code simply looks like this:  __text:00000000 ; Segment type: Pure code
__text:00000000                 AREA __text, CODE, READWRITE, ALIGN=0
__text:00000000                 CODE32
__text:00000000                 MOV     R0, R1
__text:00000000 ; __text        ends
__text:00000000
__text:00000000                 END
Comment: Well, if you link it, then it should be correct... Have you just TRIED running it without trying to figure out sceptically the exact binary representation of a file? Also have a look at here for what and when a header's needed: http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

Compiling ARM on Mac for iOS