struggling with $\{(x, y) \in \mathbb Q \times \mathbb Q^+ \mid y = \frac1x\}$ is function or not?

Question: I must say that the last time I have done math (badly) at school was 20 years ago, and I have been given this function but even with the answer I am struggling
The anwer is:
$\{(x, y) \in \mathbb Q \times \mathbb Q^+ \mid y = \frac1x\}$ is not a function, because nothing corresponds to a negative
x.
I even struggle with the notation...
I assume that $\mathbb Q$ is the rational numbers (that inlcudes the negative $\mathbb Q$) and $\mathbb Q^+$ inlcudes the rational numbers but only the positives.
But why ther is nothing to correspond to a negative $x$? I am sure that starts with an intutive example but I lack of, can someone help?
Comment: The relation - call it $R$ - is defined as the set of *pairs* $(x,y)$ such that $x$ is rational, $y$ is a positive rational **and** $y=\frac 1 x$.
Comment: Thus, e.g. $(2,1) \notin R$ because $1 \ne \frac 1 2$ and also $(1,2) \notin R$ because $2 \ne \frac 1 1$
Comment: At the same time, no pair with a non-positive first component will be in $R$ because if $x$ is negative we have that also $\frac 1 x$ will be and thus the condition that $y \in \mathbb Q^+$ is **not** satisfied.
Comment: Having said that, we have only one number $q$ that is equal to its reciprocal and it is $1$: $(1,1) \in R$ because $1= \frac 1 1$. In conclusion: $R$ is a function.
Comment: So: is there a pair $(x,y)\in \Bbb Q\times\Bbb Q^+$ such that $x<0$ and $y=1/x$?
Comment: it still makes little sense to me, because I dont fully understand the notation.
does this mean that x belongs to Q and y belongs to q+?
Comment: It would seem that you do understand the notation.
Comment: if I substitute 2 to x becuase it has to be a positive rational,  I get 2<0 and y =1/2. But 2 is not less than 0, so I deduct that it is not a function, but maybe I am just confusing myself
Comment: some of it makes sense, but it break down quickly, if Q are rational numbers why you are   using 1 and 2, is 1 also a rational number ? 1=1/1. Sorry it is silly but it does no make sense for untrained
Comment: Yes, $1$ is a rational number since it can be expressed as the quotient of two integers.
Answer: For case where $x=0$: Because $\lim_{x\rightarrow 0^+}{\frac{1}{x}} = \infty$, the pair $(x,1/x)$ does not have a value when $x=0$, so the list of pairs $\{(x,y) \in Q\times Q^+| y=1/x\}$ is not a function because each value of $x$ does not have corresponding $y$ value ($\in Q^+$). QED, it's not a function.
For case where $x<0$: the $y=1/x$ would fall outside of $Q^+$ because y is negative, thus it's not a function of $Q \rightarrow Q^+$
For case where $x>0$: the $y=1/x$ would go inside $Q^+$. This alone cannot make it a function when the other cases claim otherwise.
Comment: You have to evaluate whether or not there is a pair $(x,y)\in \Bbb Q\times \Bbb Q^+$ such that $x=0\land y=1/x$. The fact $\lim_{x\to 0^+}\frac1x=\infty$ is completely irrelevant and misleading.
Comment: The actual rule that says something is a function is based on "whether there is exactly one value for f(x) for each possible value of x". In this case it fails because 1/x is going outside of $Q^+$ range, and then it requires knowing that a list of pairs is another representation for a function when $(x,f(x))$.
Comment: No, no, a hundred times no. It fails because $x$ is not in the domain. We could agree right now that the expression $1/0$ means $37$, and suddenly we'd have the pair $(0,37)$ in that set. Still, $\lim_{x\to 0^+}\frac1x =\infty$ would be true. You have to argue by using the defining property for what it means.
Comment: what you mean by $x$ is not in the domain? I would think $0 \in Q$ which would mean that x=0 is in the domain.
Comment: I guess you call [active domain](https://en.wikipedia.org/wiki/Binary_relation#Definition) what I call domain.
Comment: But you're right that the lim is kinda strange with $Q$, given that $\frac{a}{b}$ makes the lim jump from one rational to another in unpredictable manner.
Comment: No, I've never said that the limit was "strange": the limit is fine in $\Bbb Q$. The point is that what $\lim_{x\to 0^+}\frac1x$ is has nothing to do, on a material level, with whether or not there is some $y\in\Bbb Q^+$ such that $(0,y)\in \{(x,y)\in\Bbb Q\times\Bbb Q^+\,:\, y=1/x\}$.


How can I change the development version of a module?

Question: Originally, the Link Allowed Hosts module, which I'm a maintainer of (with "administer releases" permission), started with a default branch of 1.0.x. This branch was released and appeared since then as development version 1.0.x-dev.
This was wrong, the default branch needs to be 1.x. So I created a 1.x branch, set it as default on the project's GitLab page and also released it. Still the development version stayed 1.0.x-dev.
I also can't enable this branch in the project's "Releases" page as the matching checkbox is disabled.
How can I fix this? Or where can I file this issue?
Comment: Whoops that was supposed to be generic link. But on a project page, it says "git checkout -b 1.0.x" but on this page, it says 1.x: https://www.drupal.org/docs/develop/git/git-for-drupal-project-maintainers/release-naming-conventions
Comment: Does that mean this docs page at the bottom is _wrong_? https://www.drupal.org/project/views_minimum/git-instructions
Answer: There is no way to select that branch as supported, as the Supported checkbox for the 1.* series is disabled by code. That is done by project_release_project_edit_releases() which contains the following code. (drupal.org is still running on Drupal 7.)
// Check if the maintainer is allowed to mark the branch as supported.
if (($supportable_branch_pattern = variable_get('project_release_supportable_branch_pattern_' . $node->type, variable_get('project_release_supportable_branch_pattern'))) && !preg_match($supportable_branch_pattern, $branch)) {
  $form['branches'][$branch]['supported']['#disabled'] = TRUE;
  $form['branches'][$branch]['supported']['#value'] = 0;
  $form['branches'][$branch]['recommended']['#disabled'] = TRUE;
  $form['branches'][$branch]['recommended']['#value'] = 0;
}

That is probably done because the settings for 1.* would also be valid for 1.0.*; using settings for the 1.* and the 1.0.* series would cause "conflicts" between two different settings.
As for in which queue you could file an issue, that is the Project issue queue, the queue for the project that handles projects and their releases on drupal.org. Probably this is seen as works as designed, but the Project maintainers are the only ones who can change that code and decide for any change.
Answer: The easiest way to have this resolved is to as in the #drupal-infrastructure channel in Slack.


Como eu faço para pesquisar algo em html css js?

Question: Então Pessoal, eu queria poder pesquisar items em html, sem um banco, pois os itens não serão acrescentados de forma dinâmica, já serão pré-estabelecidos, como sou iniciante não faço ideia de como fazer isso, se alguém puder me ajudar eu agradeço desde já.

ul{
list-style: none;
}
<input type="text" placeholder="Pesquise aqui">

Abacate

Banana

Cenoura

Tomate

Answer: Aí está.
A lógica é simples: a cada vez que uma tecla é pressionada dentro do input, o código Javascript gera uma expressão regular com o valor do input, expressão essa que é comparada ao texto de cada item da lista. Os items cujo texto não corresponde à ela recebem display: none; em seu css, para que fiquem ocultos. Já os que correspondem, ficam com display: block;
Obs: o script só funciona para encontrar items que COMEÇAM com o que foi digitado. "Maçã verde", por exemplo, não seria encontrada apenas digitando a palavra "verde".

const campoPesquisa = document.querySelector('#pesquisa');
const items = document.querySelectorAll('#lista li');
let regexCheck;

campoPesquisa.addEventListener('keyup', function(e) {
  regexCheck = new RegExp(`^${e.target.value}`, 'i');
  items.forEach(item => {
    if (!item.innerText.match(regexCheck)) {
      item.style.display = 'none';
    } else {
      item.style.display = 'block';
    }
  });
});
#lista {
  list-style: none;
  }
<input type="text" id="pesquisa" placeholder="Pesquise aqui">

Abacate

Banana

Cenoura

Tomate


EFD-Reinf Assinatura XML - "Elemento Reference mal formado."

Question: Sou novo na comunidade e estou desenvolvendo uma aplicação em C# para o EFD-REINF. Tive um problema com a assinatura e recebi uma grande ajuda do Pedro neste link.
Ainda não estou conseguindo enviar o XML do evento R-1000 para o servidor de produção remota, pois estou tendo problemas na minha assinatura: "Elemento Reference mal formado." na linha "signedXml.ComputeSignature()". Alguém mais já passou por esse problema?
Basicamente, criei minha classe de EnvioREINF chamando métodos individuais para cada uma das informações a serem enviadas: R-1000 , R-2010, R-2020...(creio que pode existir uma maneira mais simples de fazer isso, porem como não possuo muita experiencia com Web Service eu implementei ele desta maneira) da seguinte forma:
 //R-1000
    public bool EnvioEventoevtInfoContribuinte(Empresa objEmpresa, DateTime periodoApuracao)
    {
        try
        {

            EventosREINF auxiliar = new EventosREINF();
            _reinf.evtInfoContri = auxiliar.EnviarEvtInfoContri(objEmpresa, periodoApuracao);
            ReinfEvtInfoContri evtInfoContri = _reinf.evtInfoContri;

            //serializa o evento informações do Contribuinte
            string xmlEventoInclusao = XMLConverte.SerializaObjeto<ReinfEvtInfoContri>(evtInfoContri);

            //Exibe a lista de certificados para o usuário selecionar
            X509Certificate2 oX509Cert = BuscarCertificadoEmpresa();

            //Adiciona a assinatura digital ao evento
            XmlDocument xmlDoc = new XmlDocument();
            Assinar(xmlDoc, oX509Cert, xmlEventoInclusao);

            //XmlDocument xmlReinf = Assinar(xmlEventoInclusao, oX509Cert);

            //Inicializa o vetor de eventos do lote a ser enviado
            REINF.Model.v1_04.TArquivoeReinf[] xmlsEvento = new REINF.Model.v1_04.TArquivoeReinf[1];

            //Adicionar Arquivo XML ao array de Eventos do Lote
            REINF.Model.v1_04.TArquivoeReinf arquivoR_1000 = new REINF.Model.v1_04.TArquivoeReinf
            {
                id = objEmpresa.ToString(),
                Any = xmlDoc.DocumentElement
            };
            xmlsEvento[0] = arquivoR_1000;

            //Adiciona o xml do evento de informações do Contribuinte ao xml do evento de envio
            XmlDocument xmlDocEventoEnvio = AdicionarLoteAoEventoEnvio(xmlsEvento, objEmpresa);

            //Envia arquivo xml para o web service e obtém o xml de retorno
            XmlElement xmlRetorno = EnviarXML(xmlDocEventoEnvio, oX509Cert);
        }
        catch
        {
            throw;
        }
        return true;
    }

    //R-2010
    public bool EnvioEventoevtServTom(List<NotaFiscal> objNotasFiscais, Empresa objEmpresa, DateTime periodoApuracao)
    {
        try
        {
            ReinfEvtServTom reinfEvtServTom = new ReinfEvtServTom();

            EventosREINF auxiliar = new EventosREINF();

            _reinf.evtServTom = auxiliar.EnviarevtServTom(objNotasFiscais, objEmpresa, periodoApuracao);

            //Exibe a lista de certificados para o usuário selecionar
            X509Certificate2 oX509Cert = BuscarCertificadoEmpresa();

            //Inicializa o vetor de eventos do lote a ser enviado
            REINF.Model.v1_04.TArquivoeReinf[] xmlsEvento = ComunicacaoREINF(objNotasFiscais, oX509Cert).ToArray();

            //Adicionar Arquivo XML ao array de Eventos do Lote
            REINF.Model.v1_04.TArquivoeReinf arquivoR_2010 = new REINF.Model.v1_04.TArquivoeReinf
            {
                id = objEmpresa.ToString(),
            };
            xmlsEvento[0] = arquivoR_2010;

            //Adiciona o xml do evento de informações do Contribuinte ao xml do evento de envio
            XmlDocument xmlR2010 = AdicionarLoteAoEventoEnvio(xmlsEvento, objEmpresa);

            //Envia arquivo xml para o web service e obtém o xml de retorno
            XmlElement xmlRetorno = EnviarXML(xmlR2010, oX509Cert);

            //Converte o xml de retorno para a classe retorno de envio
            ReinfRetornoLoteEventos reinfRetornoLoteEventos = XMLConverte.DeserializaObjeto<ReinfRetornoLoteEventos>(xmlRetorno.OuterXml);

        }
        catch
        {

            throw;
        }
        return true;
    }

    //R-2020
    public bool EnvioEventoevtServPrest(List<NotaFiscal> objNotasFiscais, Empresa objEmpresa, DateTime periodoApuracao)
    {
        try
        {

            ReinfEvtServPrest reinfEvtServPrest = new ReinfEvtServPrest();

            EventosREINF auxiliar = new EventosREINF();

            _reinf.evtServPrest = auxiliar.EnviarevtServPrest(objNotasFiscais, objEmpresa, periodoApuracao);

            //Exibe a lista de certificados para o usuário selecionar
            X509Certificate2 oX509Cert = BuscarCertificadoEmpresa();

            //Inicializa o vetor de eventos do lote a ser enviado
            REINF.Model.v1_04.TArquivoeReinf[] xmlsEvento = ComunicacaoREINF(objNotasFiscais, oX509Cert).ToArray();

            //Adicionar Arquivo XML ao array de Eventos do Lote
            REINF.Model.v1_04.TArquivoeReinf arquivoR_2020 = new REINF.Model.v1_04.TArquivoeReinf
            {
                id = objEmpresa.ToString(),
            };
            xmlsEvento[0] = arquivoR_2020;

            //Adiciona o xml do evento de informações do Contribuinte ao xml do evento de envio
            XmlDocument xmlR2100 = AdicionarLoteAoEventoEnvio(xmlsEvento, objEmpresa);

            //Envia arquivo xml para o web service e obtém o xml de retorno
            XmlElement xmlRetorno = EnviarXML(xmlR2100, oX509Cert);

            //Converte o xml de retorno para a classe retorno de envio
            ReinfRetornoLoteEventos reinfRetornoLoteEventos = XMLConverte.DeserializaObjeto<ReinfRetornoLoteEventos>(xmlRetorno.OuterXml);

        }
        catch
        {

            throw;
        }
        return true;
    }

    private List<TArquivoeReinf> ComunicacaoREINF(List<NotaFiscal> objNotasFiscais, X509Certificate2 oX509Cert)
    {
        List<TArquivoeReinf> loteEnvio = new List<TArquivoeReinf>();

        foreach (NotaFiscal notaFiscal in objNotasFiscais)
        {
            ReinfLoteEventos reinfLoteEventos = new ReinfLoteEventos();

            string xmlEventoInfoContribuinte = XMLConverte.SerializaObjeto<ReinfLoteEventos>(reinfLoteEventos);

            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlEventoInfoContribuinte);

            TArquivoeReinf ObjArqXmlFilho = new TArquivoeReinf
            {
                id = notaFiscal.TipoDocumento.Id.ToString(),
                Any = xmlDoc.DocumentElement
            };

            loteEnvio.Add(ObjArqXmlFilho);
        }
        return loteEnvio;
    }

    public ReinfRetornoLoteEventos RetornoLoteEventos(ReinfRetornoLoteEventos retornoLoteEventosInicial, string xmlRetorno)
    {

        try
        {
            ReinfRetornoLoteEventos reinfRetornoLoteEventos = new ReinfRetornoLoteEventos();
            reinfRetornoLoteEventos = XMLConverte.DeserializaObjeto<ReinfRetornoLoteEventos>(xmlRetorno);

            ReinfRetornoLoteEventosRetornoEventos reinfRetornoLoteEventosRetornoEventos = new ReinfRetornoLoteEventosRetornoEventos
            {
                evento = reinfRetornoLoteEventos.retornoEventos.evento
            };

            REINF.Model.ConsultaEvento_ProducaoRestrita.ConsultaInformacoesConsolidadasRequest consultaInformacoesConsolidadasRequest = new ConsultaEvento_ProducaoRestrita.ConsultaInformacoesConsolidadasRequest
            {
                Body = new ConsultaEvento_ProducaoRestrita.ConsultaInformacoesConsolidadasRequestBody()
            };
            //consultaInformacoesConsolidadasRequest.Body.numeroInscricaoContribuinte = "";
            //consultaInformacoesConsolidadasRequest.Body.numeroProtocoloFechamento = "";
            //consultaInformacoesConsolidadasRequest.Body.tipoInscricaoContribuinte = "";

            REINF.Model.ConsultaEvento_ProducaoRestrita.ConsultasReinfClient consultasReinfClient = new ConsultaEvento_ProducaoRestrita.ConsultasReinfClient();

        }
        catch
        {
            throw;
        }
        return retornoLoteEventosInicial;
    }

    private XmlDocument AdicionarLoteAoEventoEnvio(TArquivoeReinf[] xmlsEvento, Empresa objEmpresa)
    {
        //Leiaute Mensagem Entrada
        ReinfLoteEventos reinfLoteEventos = new ReinfLoteEventos
        {
            evento = new TArquivoeReinf[1]
        };
        reinfLoteEventos.evento = xmlsEvento;

        //Serializa objeto evento de envio
        string xmlEventoEnvio = XMLConverte.SerializaObjeto<ReinfLoteEventos>(reinfLoteEventos);

        //Converte xml do evento envio para XMLDocumente que será transmitido para o web service
        XmlDocument xmlDocEventoEnvio = XMLConverte.ConverterXMLParaXMLDocument(xmlEventoEnvio);

        return xmlDocEventoEnvio;
    }

    private static string UTF8ByteArrayToString(byte[] characters)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        string constructedString = encoding.GetString(characters);
        return (constructedString);
    }

    public void Assinar(XmlDocument xmlDoc, X509Certificate2 X509Cert, string xmlEventoInclusao)
    {

        // Cria o objeto SignedXml baseado no XmlDocument passado.
        SignedXml signedXml = new SignedXml(xmlDoc);
        signedXml.SigningKey = X509Cert.PrivateKey;
        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        // Checa se foi informado um URI para a referência, se foi acrescenta o "#" no começo.
        xmlEventoInclusao = String.IsNullOrEmpty(xmlEventoInclusao) ? "" : $"#{xmlEventoInclusao}";

        Reference reference = new Reference(xmlEventoInclusao);
        reference.Id = _reinf.evtInfoContri.id;
        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        reference.AddTransform(new XmlDsigC14NTransform());
        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        signedXml.AddReference(reference);

        // Carrega o certificado em um objeto KeyInfoX509Data e o adiciona ao objeto KeyInfo.
        KeyInfo KeyInfo = new KeyInfo();
        KeyInfo.AddClause(new KeyInfoX509Data(X509Cert));
        signedXml.KeyInfo = KeyInfo;

        // Calcula a assinatura.
        signedXml.ComputeSignature();

        // Obtém a representação XML da assinatura e a armazena em um objeto XmlElement.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Acrescenta o elemento ao documento XML.
        xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

        // Se o primeiro nó do documento for o nó de declaração XML
        // '<?xml version="1.0" encoding="utf-8"?>', remove ele.
        if (xmlDoc.FirstChild is XmlDeclaration)
            xmlDoc.RemoveChild(xmlDoc.FirstChild);
    }

    private X509Certificate2 BuscarCertificadoEmpresa()
    {
        X509Certificate2 cert = null;
        ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;

        X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
        X509Certificate2Collection certcollection = (X509Certificate2Collection)store.Certificates;
        // pick a certificate from the store
        cert = X509Certificate2UI.SelectFromCollection(certcollection,
                "Autenticação do Certificado",
                "Informe um certificao válido", X509SelectionFlag.SingleSelection)[0];

        store.Close();

        return cert;
    }

    private XmlElement EnviarXML(XmlDocument xmlDocEventoEnvio, X509Certificate2 oX509Cert)
    {
        XmlElement xmlResult = null;

        var urlServicoEnvio = @"https://preprodefdreinf.receita.fazenda.gov.br/wsreinf/RecepcaoLoteReinf.svc";
        var address = new EndpointAddress(urlServicoEnvio);
        var binding = new BasicHttpsBinding();

        // Informa que será usado um certificado digital para acessar o serviço.
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        // Cria o objeto cliente (do tipo System.ServiceModel.ClientBase) para acesso ao WebService.
        var recepcaoLoteReinfClient = new RecepcaoLoteReinfClient(binding, address);

        // Passa o certificado digital para o objeto do tipo System.ServiceModel.ClientBase.
        recepcaoLoteReinfClient.ClientCredentials.ClientCertificate.Certificate = oX509Cert;

        // Chama o WebService de fato, passando o XML do lote.
        recepcaoLoteReinfClient.Open();

        // O método espera um objeto do tipo XElement, e retorna outro objeto XElement.
        //xmlResult = recepcaoLoteReinfClient.ReceberLoteEventos(xmlDoc.DocumentElement);
        var retornoEnvioXElement = recepcaoLoteReinfClient.ReceberLoteEventos((XElement.Parse(xmlDocEventoEnvio.OuterXml)));
        recepcaoLoteReinfClient.Close();

        return xmlResult;

    }

    private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        // If the certificate is a valid, signed certificate, return true.
        if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
        {
            return true;
        }

        Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
            certificate.Subject,
            sslPolicyErrors.ToString());

        return false;
    }

EDIÇÃO
Segue o XML que está sendo gerado, ocultando as informações pessoais:
<?xml version="1.0" encoding="utf-8"?>
<Reinf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_04_00">
  <evtInfoContri id="ID1000000000000002018121815063800001" xmlns="http://www.w3.org/2000/09/xmldsig#">
    <ideEvento>
      <tpAmb>2</tpAmb>
      <procEmi>1</procEmi>
      <verProc>184.108.40.206</verProc>
    </ideEvento>
    <ideContri>
      <tpInsc>1</tpInsc>
      <nrInsc>00000000000000</nrInsc>
    </ideContri>
    <infoContri>
      <inclusao>
        <idePeriodo>
          <iniValid>2018-12</iniValid>
        </idePeriodo>
        <infoCadastro>
          <classTrib>1</classTrib>
          <indEscrituracao>0</indEscrituracao>
          <indDesoneracao>0</indDesoneracao>
          <indAcordoIsenMulta>0</indAcordoIsenMulta>
          <contato>
            <nmCtt>Nome Contato</nmCtt>
            <cpfCtt>00000000000</cpfCtt>
            <foneFixo>0000000000</foneFixo>
          </contato>
          <softHouse>
            <cnpjSoftHouse>00000000000000</cnpjSoftHouse>
            <nmRazao>Empresa</nmRazao>
            <nmCont>Contato</nmCont>
          </softHouse>
        </infoCadastro>
      </inclusao>
    </infoContri>
  </evtInfoContri>
</Reinf>

Answer: Creio que o problema esteja nessa linha da função Assinar:
    reference.Id = _reinf.evtInfoContri.id;

Aparentemente você não colocou o código onde você carrega o valor desse campo _reinf.evtInfoContri.id, mas, como eu disse na minha outra resposta, a propriedade reference.Id deve começar com "#", quando houver valor, e esse ID informado também deve existir no documento sendo assinado.
Então, provavelmente essa linha deveria ficar assim:
    reference.Id = "#" + _reinf.evtInfoContri.id;

Mas, eu sugiro que você passe esse ID como um parâmetro da função de assinatura, como sugeri na outra resposta, porque desse jeito que você fez, você não poderá usar a mesma função de assinatura para os outros eventos, e todos precisam ser assinados.
Outra sugestão: Seria interessante tentar criar uma função única para os 3 eventos que você está tratando (R-1000, R-2010 e R-2020), porque o procedimento para todos os eventos é praticamente idêntico. O código em geral também está meio confuso, inclusive com nomes de variáveis que não correspondem ao que estão armazenando, seria legal dar uma revisada.
E uma última sugestão: Não use blocos try/catch somente para executar um throw, isso não serve para nada, veja essa resposta: Preciso usar o try/catch em toda a cadeia de um processo? - Stack Overflow em Português.
Comment: Oi Pedro, muito obrigado pela sua ajuda. O campo "_reinf.evtInfoContri.id" é na verdade uma função que eu criei para pegar a resposta do campo "evtInfoContri.id" onde segui os conselhos da sua outra resposta. Adicionei o "#" e ainda sim continuo com esse problema.
Não sei se tem algo a ver, mais verificando os posts sobre Reinf, meu XML esta contendo os elementos xmlns:xsi e xmlns:xsd, que normalmente são adicionados automaticamente pelo serializador e eu não sei como remover isso do meu XML.
Comment: Sobre o `reference.Id`: Mas esse ID que você está informando existe no XML? Poste o seu XML na pergunta, e o valor que está sendo informado no campo `reference.Id`, quando o erro ocorre. Sobre os atributos `xmlns:xsi`e `xmlns:xsd`, veja o item 3 dessa resposta: [C# - EFD Reinf v1_04_00 - Como instanciar e preencher todas propriedades dos Eventos?](https://pt.stackoverflow.com/a/348662/86952).
Comment: Vi o XML que você está tentando enviar. O valor que você está informando no campo `reference.Id` é `"#ID100000000000002018121809024900001"`? Deveria ser esse (embora ele esteja errado, veja o item 2 [dessa resposta](https://pt.stackoverflow.com/a/348662/86952) para ver como esse ID deve ser composto)(ou você zerou o início do ID intencionalmente para não mostrar o CNPJ da empresa?). Também vi que você está colocando o atributo `xmlns` nos elementos ``, `` e ``, mas esse atributo só deveria aparecer no elemento raiz ``.
Comment: Creio que o valor no reference.Id esta correto, pois segui a regra do manual de orientação. Sobre o XML, consegui alguns avanços ontem e irei postar o novo XML agora. Porem ainda estou tendo problemas relativos ao meu reference.URI
Comment: Mas qual é o valor exato que você está informando no `reference.Id`? Ele precisa ser exatamente o valor que está no atributo `id` do elemento ``, adicionado do caractere `"#"` no início.
Comment: Na verdade eu segui sua orientação conforme me orientou naquele outro post; Eu estou pegando o resultado do campo reinf.evtInfoContri.id(ID+1+CNPJ+AAAAMMDDHHMMSS+00001) e adicionando o # no inicio. Verifiquei agora na documentação e ela diz que os ultimos campos seriam o nº sequencial da chave, porem eu estou incrementando com 00001. Esta correto?
Comment: Sim, na verdade essa última parte, o número sequencial, é só para garantir que o ID será único. Suponha que no dia 19/12/2018, às 10:50:31, você enviou 3 eventos. Cada um deve ter um ID único, então o primeiro teria final 00001, o segundo 00002 e o terceiro 00003. E mesmo informando no `reference.Id` exatamente o mesmo ID que está no XML, precedido por `#`, você está recebendo o mesmo erro, de _"Elemento Reference mal formado"_?
Comment: Sim, estou querendo enviar apenas o evento R-1000 para teste, porem na assinatura, na parte que calcula a assinatura eu recebo esse erro do Visual Studio. É necessario informar o reference.URI? Caso afirmativo, qual o valor desse campo?
Comment: No caso do eSocial o `reference.Id` não deve ser informado, e aí a assinatura é efetuada em todo o documento XML,mas no EFD-Reinf parece ser necessário informar o `reference.Id`, e nesse caso deve ser informado `"#" + {Atributo ID do elemento 'evtInfoContri'}`. Mas o seu elemento `` também não deveria ter um atributo `xmlns`, muito menos referenciando o *schema* do *XML Signature*: `"http://www.w3.org/2000/09/xmldsig#"`.
Comment: Entendi, percebi tambem que o meu XML não esta chamando o loteEventos, de Reinf ele ja vai direto para o . Creio que isso tambem esteja atrapalhando minha rotina.
Comment: Não, isso está certo. Esse XML é o do evento, o elemento `loteEventos` é do XML do lote. Depois você precisa pegar esse XML do evento e embutir no XML de lote.
Comment: @User1012, minha resposta respondeu sua pergunta? Se tiver respondido, por favor, marque-a como aceita, clicando no sinal de visto (✓). Mas faça isso apenas quando alguma resposta tiver respondido sua dúvida original. Quando atingir 15 pontos de reputação também poderá [votar a favor](https://pt.stackoverflow.com/help/privileges/vote-up) de uma resposta ou pergunta. Veja: [Alguém me respondeu](https://pt.stackoverflow.com/help/someone-answers) e [Por que votar?](https://pt.stackoverflow.com/help/why-vote). Faça também o [tour], para uma explicação inicial de como o site funciona.
Comment: Oi Pedro, respondeu sim meu caro. Cliquei no visto mais ainda preciso atingir 15 pts de reputacao :(


How can you do message interception in MassTransit?

Question: I want to inspect each message before it hits consumers or sagas.
I think I want an IInboundMessageInterceptor but I can't see an easy way to inject a custom one.
How can I achieve message interception in MT? And/Or how can I configure the bus with a custom IInboundMessageInterceptor?
Answer: You can do the following.
Your interceptor must implement IInboundMessageInterceptor
<code>  Bus.Initialize(sbc =>
            {
                // ... Initialise Settings ...

                var busConfiguratorr = new PostCreateBusBuilderConfigurator(bus =>
                    {

                        var interceptorConfigurator = new InboundMessageInterceptorConfigurator(bus.InboundPipeline);
                        interceptorConfigurator.Create(new MyIncomingInterceptor(bus));
                    });

                sbc.AddBusConfigurator(busConfiguratorr);
            });
</code>
You can then write an interceptor like so
<code>    internal class MyInboundInterceptor : IInboundMessageInterceptor
{
    public MyInboundInterceptor(ServiceBus bus)
    {

    }

    public void PreDispatch(IConsumeContext context)
    {
        IConsumeContext<AwesomeCommand> typedContext;
        if (context.TryGetContext(out typedContext))
        {
            // Do SOmething with typedContext.Message
        }
    }

    public void PostDispatch(IConsumeContext context)
    {
    }
}
</code>
Comment: Dear Adam,
I have more than one message to Intercept, so shall i have to define multiple IConsumeContext like given below:
IConsumeContext typedContext;
IConsumeContext typedContext;
IConsumeContext typedContext;

Please help me on this..


Functions from an $n$-dimensional hypercube to $\mathbb{R}^m$ when $n >m$.

Question: Let $n$ and $m$ be integers such that $n > m$. Suppose there exists a $n$-dimensional hypercube in $\mathbb{R}^n$. Let the hypercube be divided into $2^n$ regions ($n$-dimensional volumes) by perpendicularly bisecting each orthogonal dimension. For example, an analogous idea would be to divide a square into quadrants or a cube into octants.
Does there exist a differentiable function $f: \mathbb{R}^n \to \mathbb{R}^m$ such that the images of the regions of the hypercube are pairwise non-intersecting in $\mathbb{R}^m$?
Comment: Do you mean the images of the regions are pairwise non-intersecting or have empty intersection?
Comment: I mean pairwise not intersecting.
Answer: If $m=1$, no. By the Intermediate Value Theorem, the image of each region must be an interval. By continuity, the image of each region must contain $f(O)$ in its closure, where $O$ is the center. With four or more intervals that have zero either as an endpoint or in their interior, they must overlap.
If $m>1$, yes. Taking the cuts to be the coordinate hyperplanes in $\mathbb{R}^n$, here's a map from $\mathbb{R}^n$ to $\mathbb{R}^2$ that works:
Let $g(x_1,x_2,\dots,x_n)$ be a function from $\mathbb{R}^n$ to the unit circle in $\mathbb{R}^2$ that depends only on the sign of the $x_i$, and takes different values in each "quadrant"; if $x_i$ and $y_i$ have opposite signs for some $i$, $g(x_1,x_2,\dots,x_n)$ and $g(y_1,y_2,\dots,y_n)$ are different.
Then, define $f(x_1,x_2,\dots,x_n)=x_1^2x_2^2\cdots x_n^2g(x_1,x_2,\dots,x_n)$; this $f$ is the function we seek. Each "quadrant" is mapped to a different ray, while the hyperplanes separating them are all mapped to the single point $0$. Inside each "quadrant", $f$ is differentiable because it's a constant multiple of the differentiable function $x_1^2x_2^2\cdots x_n^2$, and $f$ is differentiable on the hyperplanes with derivative zero because we're multiplying something locally bounded by the square of the coordinate that's zero there.
For $m>2$? Pad the function with zeros in the extra coordinates.
This relies on the interpretation that only the interiors of the cut regions have to be separate, and the images of the boundary hyperplanes are allowed to intersect.
Comment: How do you know the function $g$ exists? I don't think this works because the hypercube graph is not planar for $n > 3$.
Comment: Just choose the $2^n$ values arbitrarily. For example, in $\mathbb{R^4}$, we could choose $g(1,1,1,1)=(1,0)$, $g(1,1,1,-1)=(0.8,0.6)$, $g(1,1,-1,1)=(0.6,0.8)$, and so on.
Comment: It has to be differentiable.
Comment: $g$ doesn't. Or, at least, it only has to be differentiable away from the separating hyperplanes, where it's locally constant.
Comment: If $g$ is not differentiable, $f$ will not be. $g$ does not count as a constant factor.
Comment: It's constant enough. Consider this one-dimensional example: $g(1)=1$, $g(-1)=-1$, $f(x)=x^2$ for $x>0$, $f(0)=0$, $f(x)=-x^2$ for $x<0$. That's differentiable - and that's the sort of thing I'm doing in this general case.
Comment: Ok, I understand.


C# convert an ArrayList of type ints into a Point[]

Question: First of all I am running this on a Mobile Device using CE6.5.  I have an ArrayList of data that are ints and for graphing purposes I want to convert in order the number it is into the list and the int value into the x and y values for a Point.  Put all those points into a Point Array then use bufferedGraphics.DrawLines to draw that onto the form.  I have a way of doing that that seems to work pretty fast but not sure if this is the best way. Any suggestions or improvements to this code?
Oh yeah dataList is usually about 450 or more depending on screen size and rotation.
public Point[] toPointArray(int w, int h) {
      Point[] p;
      int val;

      p = new Point[dataList.Count];
      for (int i = 0; i < dataList.Count; i++) {
          val = (int)dataList[i];
          if (i < p.Length)
               p[i] = new Point(i, h - (val * h) / range + (min * h) / range);
      }
      return p;
}

Some of my data coming is updating the dataList at 256 times per sec, so concerns of overwriting are there but so far this seems to work even at these speeds.
Here are some speed values on how fast this is currently, time is in secs:
Time to complete 0.000588
Time to complete 0.0005886154
Time to complete 0.0005846154
Time to complete 0.0005870769
Time to complete 0.0005830769
Time to complete 0.0005806154
Time to complete 0.0005981539
Time to complete 0.0007206154
Time to complete 0.0005836923
Time to complete 0.001039077

After taking suggestions from the answers below here is what my code looks like now and I am getting 0.00047 secs in execution time on the average.  dataList is a global that is now a List instead of ArrayList, the (int) cast was taking up a quarter of the original processing time.
   List<int> dataList = new List<int>();

   public Point[] toPointArray(int w, int h) {
        Point[] p = new Point[dataList.Count];
        for (int i = 0; i < dataList.Count; i++) {
            p[i] = new Point(i, h - (dataList[i] * h) / range + (min * h) / range);
        }

        return p;
    }

Comment: You can remove the `if` and it will improve performance slightly.
Answer: EDIT - after comment about the index and Dictionary:
Point[] p = (from i in Enumerable.Range(0, dataList.Count)
             select new Point(
                        i,
                        h - (((int)dataList[i]) * h) / range + (min * h) / range))
            .OrderBy ((pp) => pp.X)
            .ToArray();

this works with the ArrayList etc.
Comment: will this take the index of dataList[0] which say is equal to 25 and convert that to Point(0, h - (25* h) / range + (min * h) / range)?
Comment: no it won't... it could be done IF dataList were a Dictionary - is that a possibility ?
Comment: No not feasible at this time, too much code to rip this out and change everything to Dictionary.
Comment: see my last edit - this works with the ArrayList and does exactly what your method does including the index etc.
Comment: Using his method although it appeals to my elegant side is actually slower than my original code...for sake of beauty this code rocks but for speed it actually is almost 10x's slower... time to execute is averaged at 0.006785356 secs.  Whereas my original code is at 0.0009 secs.
Answer: 1) Declare the variables at the same place you use them.  No need to declare Point[] a separately (it's created right after that), and no reason to declare int val separately (it's not used outside the loop and there are no performance penalties for declaring it where you use it).
2) You know that i is < p.Length (assuming single-threaded application), remove the check.
3) Use LINQ
4) Use Microsoft's suggested naming standards (ProperCase for methods)
5) Use better variable names
6) Use better method names - this method isn't converting it to an array (or at least, that's not the main purpose of the method)
7) Use a typed datastore.  We can't see what dataList is, but you shouldn't have to convert it to an int (unless it's a long that you know is an int, or somesuch)
If you can use LINQ, I haven't looked over Yahia's solution but it should work.  If you can't/don't want to use LINQ, try:
public Point[] ToPointGrid(int width, int height)
{
  Point[] points = new Point[dataList.Count];
  for(int index = 0; index < dataList.Count; ++index)
  {
    points[index] = new Point(index, height - (dataList[index] * height) / range + (minimum * height) / range);
  }
  return points;
}

Comment: @JPM - I believe @Kyle was saying that `dataList` should be converted to a strongly typed `List` if possible.
Comment: the dataList is of type ArrayList and values added to it are of type int, hence the cast because ArrayList returns value of type Object.
Comment: I don't agree with #4, #5, #6 as that has nothing to do with speed and we use different naming conventions than MS.
Comment: You didn't specifically ask for only recommendations on speed.  Also, I doubt your naming conventions specify to use 1-letter names.  Those are never readable.
Comment: Touche yes you are correct, I hsould have said can I speed this up...Thanks for your help though I was able to use #1, #2, and #7 and saw an improvement in speed by almost double  Here is the time for my original code...0.000947304 sec  and here is the time for your suggestions 0.000493501 Secs


If the acceleration is constant, does it lie on a plane?

Question: The Calculus 3 book Apostle Volume 1 has a group of questions I don't quite know how to approach. It says that for the next two statements about a curve traced out by a particle moving in 3-space to give a proof or exhibit a counter example.

(a) If the acceleration is constant, the curve lies in a plane.

(b) If the velocity is perpendicular to the acceleration, the curve lies in a plane.
How do I approach these problems? What does it mean to lie in a plane? A solution to either would be appreciated as it would help me understand better.
Answer: If acceleration is constant, then the object takes a parabolic path through space (see constant gravitational acceleration), which thus lies on a plane.
If velocity is perpendicular to acceleration, then the object travels in a circle (see this video for a full explanation: https://www.youtube.com/watch?v=x3u53wVeWfA)
For this second case, you can imagine swinging a ball on a string in a circle over your head. Acceleration is always directed inwards, perpendicular to the velocity of the ball, which is tangent to the curve of the circle.
Comment: oh ok thanks the video helped!


How to add a certificate to cacerts in bluemix

Question: Usually, I'd just use keytool like this
http://www.ibm.com/support/knowledgecenter/SSYKE2_6.0.0/com.ibm.java.security.component.60.doc/security-component/keytoolDocs/cacertsfile.html
but how do I do for Bluemix Liberty runtime?
Comment: Possible duplicate of [Add certificate to truststore to enable SSL communication](https://stackoverflow.com/questions/32180717/add-certificate-to-truststore-to-enable-ssl-communication)
Answer: You can still use keytool, you just have to manually update server.xml to point to the cacerts file, then push a server package to Bluemix.[1]
[1] https://console.ng.bluemix.net/docs/runtimes/liberty/ts_index.html
Answer: I personally don't like modifying cacerts.
I usually create a separate truststore and I import certificates into it with the option to trust cacerts.


How to route object using asp-route-paramName

Question: I am using asp-route-paramName in my view:
<btn class="btn btn-danger" asp-action="ChangePrivacy" asp-controller="AdminManager"
     email@example.com(@other)
     firstname.lastname@example.com >@other.ToString()</btn>

I want to pass enum to the controller so I convert enum to int and then to string. Is there an option to pass object like enum or class (not string) to the controller by using asp-route?
Comment: Just pass the Enum as Enum. No need to convert it to int and string
Answer: Here is a working demo like below:
Model:
public class Test
{
    public int UserId { get; set; }
    public ErrorCode Code { get; set; }
}
public enum ErrorCode
{
    None = 0,
    Unknown = 1,
    ConnectionLost = 100,
    OutlierReading = 200
}

View:
The btn does not support for tag helper.You need to use a form to call the api:
@model Test

<form asp-action="TestEnum" asp-controller="Home" asp-route-to="@Model.Code">
    <input type="submit" class="btn btn-danger" value="PassEnum" />
</form>
<form asp-action="TestModel" asp-controller="Home" asp-all-route-data="@(new Dictionary<string, string> { { "to.Code", Model.Code.ToString() },{ "to.UserId",Model.UserId.ToString()} })">
    <input type="submit" class="btn btn-danger" value="PassModelWithEnum" />
</form>

Controller:
public IActionResult Index()
{
    //for easy testing,I set the value by default...
    var model = new Test()
    {
        UserId =1,
        Code = ErrorCode.OutlierReading
    };
    return View(model);
}
public IActionResult TestModel(Test to)
{
    return RedirectToAction("Index");
}
public IActionResult TestEnum(ErrorCode to)
{
    return RedirectToAction("Index");
}

Result:


Product with empty attribute values

Question: There are a couple of attributes in my product. If the product is added to the cart without choosing one or two attributes, the product goes to the cart, but unselected attributes are also showing up.
I want that attributes without values are not shown. How can I do this?
I tried using hook_product_description(), but it doesn't help.
I'm using Ubercart 6.x-2.7, and its Product attributes module.
Comment: You need to write more context, what modules are you using ect.
Comment: This doesn't seem to make much sense to me.  Maybe you could rewrite your question?
Answer: Create a module to customize the cart form. Here's how I usually do it.
function custom_cart_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'uc_cart_view_form') {

    for($i=0;$i<count($form['items']);$i++){
       //these are rows in your cart... that includes the "total" line etc, so make sure to check that the row has the data you need

       //I believe what you're looking for is in $form['items'][$i]['desc']['#value']
       //you're going to need to look for the empty tag, probably using a regex pattern and remove the whole
 element
    }

  }
}

Product with empty attribute values


Aurelia + Asp.net Web Api + Typescript + JSPM

Question: I have created an ASP.net MVC WebApi 2 project using Visual Studio Asp.Net SPA project template and installed Aurelia into the root folder by running the following jspm commands. I have selected TypeScript as a transpiler.

jspm init

jspm install aurelia-framework

jspm install aurelia-bootstrapper

Now I need to install/configure TypeScript for the project.
Could anyone post steps to follow?
UPDATE
How can I add Typescript support for the existing project? I renamed the app.js file to app.ts. I have added the tsconfig.json file as well.
Project folder structure:

tsconfig file:
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es6",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "module": "system"
  }
}

App.Ts File
import { inject } from 'aurelia-framework';
import { HttpClient } from 'aurelia-http-client';

@inject(HttpClient)

export class App {

    message: string;
    http: any;

    constructor(httpClient: HttpClient) {
        this.http = httpClient;
    }
}

When I build the project, the build fails due to the following error.
Comment: You should take a look at our TypeScript ASP.Net Core Skeleton.
Comment: which can be found here : https://github.com/aurelia/skeleton-navigation/tree/master/skeleton-typescript-aspnetcore
Comment: Hi Ashley & @Mvision, I need to achieve this for asp.net web api 2 application. Not for asp.net core project. I have updated the question with more details. Sorry for the confusion. Could you please help?
Comment: @Ashley, do you have any project template for asp.net Web Api + TypeScript?
Answer: The gulp task you are looking for is 'build' , which can be found here, it is part of the skeleton project.
Open build task on github
Answer: Using WebApi 2?  I think I got this.  It drove me insane for long enough.
Okay, from the top.  Create a new ASP.NET WebApi project.
Open the project folder (the one where the .csproj file is) in a command prompt.
Run jspm init.  Accept all the defaults except for picking Typescript as your transpiler.
Run
jspm install aurelia-framework aurelia-bootstrapper aurelia-pal-browser

Make the first section of your config.js file look like this:
System.config({
  baseURL: "/",
  defaultJSExtensions: true,
  transpiler: "typescript",
  paths: {
    "*": "client/*",
    "github:*": "jspm_packages/github/*",
    "npm:*": "jspm_packages/npm/*"
  }

You can use src instead of client but I like client because there's a lot of source code elsewhere, if you understand me.
Okay, now we're getting somewhere.  Pop open your Views folder, open up index.cshtml and make it look like this -
@{
    Layout = null;
}
<!DOCTYPE html>

    <title>Aurelia</title>

Next, add a file called typings.json at the root of your project and chuck the following into it.
{
  "name": "WhatEverYouCalledThisThing",
  "dependencies": {
    "aurelia-binding": "github:aurelia/binding",
    "aurelia-bootstrapper": "github:aurelia/bootstrapper",
    "aurelia-dependency-injection": "github:aurelia/dependency-injection",
    "aurelia-event-aggregator": "github:aurelia/event-aggregator",
    "aurelia-fetch-client": "github:aurelia/fetch-client",
    "aurelia-framework": "github:aurelia/framework",
    "aurelia-history": "github:aurelia/history",
    "aurelia-history-browser": "github:aurelia/history-browser",
    "aurelia-loader": "github:aurelia/loader",
    "aurelia-logging": "github:aurelia/logging",
    "aurelia-logging-console": "github:aurelia/logging-console",
    "aurelia-metadata": "github:aurelia/metadata",
    "aurelia-pal": "github:aurelia/pal",
    "aurelia-pal-browser": "github:aurelia/pal-browser",
    "aurelia-path": "github:aurelia/path",
    "aurelia-polyfills": "github:aurelia/polyfills",
    "aurelia-route-recognizer": "github:aurelia/route-recognizer",
    "aurelia-router": "github:aurelia/router",
    "aurelia-task-queue": "github:aurelia/task-queue",
    "aurelia-templating": "github:aurelia/templating",
    "aurelia-templating-binding": "github:aurelia/templating-binding",
    "aurelia-templating-resources": "github:aurelia/templating-resources",
    "aurelia-templating-router": "github:aurelia/templating-router"
  },
  "globalDevDependencies": {
    "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
    "aurelia-protractor": "github:aurelia/typings/dist/aurelia-protractor.d.ts",
    "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
    "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
  },
  "globalDependencies": {
    "url":
    "github:aurelia/fetch-client/doc/url.d.ts#bbe0777ef710d889a05759a65fa2c9c3865fc618",
    "whatwg-fetch": "registry:dt/whatwg-fetch#0.0.0+20160524142046"
  }
}

then quickly run
npm install typings –g

or, if you hate waiting,
yarn global add typings

and then
typings install

Almost there, just two more steps.
First, create a file called typings.d.ts in the root of your src or client folder and add this line to it -
/// <reference path="../typings/index.d.ts" />

And finally, open up the nuget package manager console and hit it with
Install-Package es6-promise.TypeScript.DefinitelyTyped
and then
Install-Package es6-collections.TypeScript.DefinitelyTyped
And you should be all set.
This doesn't bundle things nicely for you and you're going to find that CSS is probably best added in the HEAD of your HTML - sorry! - but it's enough to get things working.
And for production, you don't really want WebApi hosting your SPA anyway.
Answer: 2021 Update
TL; DR: If you don't want to read the full answer, just clone the Sandbox repo and follow the instructions in the Getting Started section.
Here are all the steps if you need to set up an Aurelia SPA with TypeScript on an ASP.NET (Core).
1. Install Dotnet
First, download the dotnet framework. You can check if it's installed properly by typing dotnet in your terminal window. It should give you the following output.
2. Create an ASP.NET Project
Next, create an MVC application using the generator provided by dotnet. Generators are tools that let you quickly set up a complete application using a single command. For an MVC application, run the following command.
➜  dotnet dotnet new mvc --name Sandbox

If you don't provide the --name flag, the dotnet command creates the MVC project in the same directory you are running the command from.
Now that dotnet has created an ASP.NET MVC project, switch to the directory and open the project in VS Code.
➜  cd Sandbox
➜  Sandbox code .

To run, type the dotnet run command from the Sandbox directory.
➜  Sandbox dotnet run

3. Create an Aurelia App
First, install node from the node.js website. Then, from the Sandbox directory, run the npx makes aurelia command which will guide you through setting up a new Aurelia application.
➜  Sandbox npx makes aurelia

...

✔ Please name this new project: › app
✔ Would you like to use the default setup or customize your choices? › Default TypeScript Aurelia 2 App
✔ Do you want to install npm dependencies now? › No

...

Update the output.path property in the app/webpack.config.js file with the following code.
output: {
    // put the generated output in the `wwwrooot\lib` directory
    path: path.resolve(__dirname, '..', 'wwwroot', 'lib'),
    // ...
},

Add the following script tag to the Views/Shared/_Layout.cshtml file.

Replace the entire content of the Views/Home/index.cshtml file with:
<my-app></my-app>

4. Run the App
First, install the required npm packages by switching to the app directory and running the npm install command.
➜  Sandbox cd app
➜  app npm install

Once npm installs the packages, you can launch your app using  npx webpack -w command from the app directory. This command tells Webpack to compile the Aurelia source code that includes the HTML, TypeScript (compiled to JavaScript), and CSS files and put it under the lib directory. The -w flag tells Webpack to watch for changes in the source.
➜  app npx webpack -w
...
...
webpack 5.31.0 compiled successfully in 5677 ms

Finally, start your ASP.NET server with the dotnet run command from the Sandbox directory. You should run this command in a different terminal window.
➜  Sandbox dotnet run
Building...

To verify if Webpack is watching for code changes, make a simple modification in the app/src/my-app.ts file and reload the browser.
For a detailed, step-by-step guide with screenshots and code snippets, check out my article on the same topic.
Of course, both the ASP.NET and Aurelia apps contain a lot of boilerplate code. If you are like me and like to start each new project from a clean slate, simply download/clone the Sandbox project from GitHub. Then follow the instructions in the README to set up a clean sandbox. It has a better project layout and a production-ready setup.


management menu invisible for the second administrator

Question: I am using Drupal 7.26, and I need a second administrator user. I created a user who can see the authenticated user's menu, but not the management menu which I (as user #1) can see.
How can I fix this? I want the user I created with administrator role to have access to everything from the management menu.
Answer: The page under admin require the access administration pages permission, or the administer themes one. (See system_menu(), the 'access arguments' lines.)
  $items['admin'] = array(
    'title' => 'Administration',
    'access arguments' => array('access administration pages'),
    'page callback' => 'system_admin_menu_block_page',
    'weight' => 9,
    'menu_name' => 'management',
    'file' => 'system.admin.inc',
  );
  $items['admin/compact'] = array(
    'title' => 'Compact mode',
    'page callback' => 'system_admin_compact_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
    'file' => 'system.admin.inc',
  );
  $items['admin/tasks'] = array(
    'title' => 'Tasks',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );
  $items['admin/index'] = array(
    'title' => 'Index',
    'page callback' => 'system_admin_index',
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -18,
    'file' => 'system.admin.inc',
  );

  // Menu items that are basically just menu blocks.
  $items['admin/structure'] = array(
    'title' => 'Structure',
    'description' => 'Administer blocks, content types, menus, etc.',
    'position' => 'right',
    'weight' => -8,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file' => 'system.admin.inc',
  );
  // Appearance.
  $items['admin/appearance'] = array(
    'title' => 'Appearance',
    'description' => 'Select and configure your themes.',
    'page callback' => 'system_themes_page',
    'access arguments' => array('administer themes'),
    'position' => 'left',
    'weight' => -6,
    'file' => 'system.admin.inc',
  );

The user you create must have a role with the right permission. Go to admin/people/permissions and assign to the role of that use the necessary permissions, listed under System.

Keep in mind that the user #1 has every permission, independently from the roles it has. If you are wondering why there is a difference between the user you created and the user you normally use, even if they have the same role, that is the reason. Drupal check the currently logged-in user is the user #1, as visible in the code for user_access().
  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

User #1 could not have any extra role, and simply be an authenticated user, and still it would have all the permissions, contrary to the normal authenticated users, who have just the permissions you assign to the authenticated user role.
Comment: I completed the code to user_access() and it worked...thank you...
Answer: 1.I found from the database and from table "users" the uid that belongs to the user i want to be an administrator.
2.I found the file user.module here: mysite/modules/user/user.module
3. I changed the following code :
 // User #1 has all privileges:
  if ($account->uid == 1 || $account->uid == my_uid ) {
    return TRUE;
  }
and it's worked.
Comment: Are you sure your solution will continue to work next time user.module gets updated?


Porcentagem de acerto Machine Learning utilizando sklearn

Question: Estava estudando algumas coisas em Machine Learning, e encontrei o seguinte codigo:
https://github.com/dadosaocubo/nlp/blob/master/NLP_com_scikit_learn.ipynb
Na minha máquina rodou certinho, porém tenho uma dúvida. Nessa parte do código:
itens = ['FEIJÃO','AÇÚCAR','QUEIJO']
for item in itens:
    print('Produto:', item, 'Departamento:', novo_item(item))

Produto: FEIJÃO Departamento: MERCEARIA SALGADA
Produto: AÇUCAR Departamento: MERCEARIA DOCE
Produto: QUEIJO Departamento: FRIOS

Como eu faço pra recuperar a porcentagem de certeza que a maquina tem que o produto pertence ao departamento? Por exemplo, gostaria que o retorno fosse:
Produto: FEIJÃO Departamento: MERCEARIA SALGADA COM 95% DE CERTEZA
Produto: AÇUCAR Departamento: MERCEARIA DOCE COM 84% DE CERTEZA
Produto: QUEIJO Departamento: FRIOS COM 45% DE CERTEZA

Pois quero criar uma métrica, se for acima de 90% de certeza, trazer o departamento. Se for menos que isso, trazer a informação DEPARTAMENTO NÃO LOCALIZADO COM CERTEZA.
Como fazer algo nesse tipo?
Comment: No "notebook" do link de seu post, vc já possui uma tabela com _precision_, _recall_ e _f1-score_. O que você está querendo exatamente?
Comment: Isso, mas eu quero saber a precisão de acerto de um item novo, que não esteja na tabela já cadastrada. Se eu adicionar o item "PRODUTO NOVO TESTE", quero saber a porcentagem de certeza que eu tenho que a categoria correta foi encontrada.
Answer: Por natureza, regressão linear não possui probabilidade de acerto. Isso se dá porque este modelo tenta representar seus dados em uma linha reta. Existem algumas métricas como "Root Mean Square Error (RMSE)", mas não acho que seja o que você procura.
Acredito que outro método como o DecisionTree ou RandomForest funcionaria melhor para seu caso.
Veja o exemplo abaixo:
Importando bibliotecas
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics

Criando dados falsos
x = np.array([i for i in range(100)]).reshape(-1, 1)
y = np.array([random.choice(["Area 1", "Area 2", "Area 3"]) for _ in range(100)])

Gerando modelo
clf = RandomForestClassifier()

clf.fit(x, y)

Fazendo predição
clf.predict(np.array(200).reshape(-1, 1))

# O output será algo como
# array(['Area 2'], dtype='<U6')

Checando probabilidades
clf.predict_proba(np.array(200).reshape(-1, 1))

# A resposta será como
# array([[0.25, 0.72, 0.03]])
# Ou seja 25% para Área 1, 72% para Área 2 e 3% para Área 3

Comment: Era isso mesmo que eu precisava. Só complementando, eu consigo alguma forma de identificar cada porcentagem no array? Ou seja, saber que o 0.25 representa a Area 1, e assim por diante?
Comment: Veja que ao definir o `y` a ordem é "Área 1", depois "Área 2"... Você pode fazer um [`zip`](https://www.w3schools.com/python/ref_func_zip.asp) desta lista com a de resultados.
Comment: Para quem votou negativo, pode informar o motivo para que eu melhore a resposta?
Comment: @zanonale, caso ache pertinente, favor marcar a resposta como aceita.


Extract words between doubles quotes in a variable in R

Question: I want to extract the name from the following input which is of the form as shown in brackets
# Example of the input in brackets('name":"Tale")
name<- c('name":"Tale"','name":"List"')

I want to extract the names between the quotes as shown below. Any suggestions?
name
Tale
List

Answer: We could use stri_extract_last_words
library(stringi)
library(data.table)
setDT(list(name=stri_extract_last_words(name)))[]
#   name
#1: Tale
#2: List

Comment: I have been going through stringi manual again since yesterday. You are too fast, as usual. :)
Comment: @jazzurro Thanks for the comment and vote.  There are handy functions in that package.
Comment: Yeah, I have been using some of them to handle string extraction for a data set. Fast speed.
Answer: Convert the vector to a single column data.frame, and then just use gsub to remove the name": and " from the string.
Example:
transform(data.frame(name), name = gsub("name\":|\"", "", name))
##   name
## 1 Tale
## 2 List


Rotation of points in Android

Question:
I have point A, B and width of CD (A' = A). If user will move point B to B'how I can know coordinates of points C' D'. I would be very grateful if someone write method in java with 3 input parameters (A, B, and width of CD) which output coordinates of C' and D'. As reward I can pay 50$ via Paypal.
Comment: Try Fiverr or Upwork. This is a Q&A site for professional programmers!
Comment: Hi. Im a programmer myself. I need a help in this task.
Comment: Are they in 2D or 3D coordinates?
Answer: The background:
First, if I understand correctly, the task actually is "given the coordinates of A and B, find coordinates of C and D if we know that AB and CD are perpendicular, and we know the length of CD"
To calculate the coordinates, we use 3 basic math equations:

Line from 2 points A, B: y = (x - B.x)* (A.y - B.y)/(A.x - B.x) + B.y
If we set m = (A.y - B.y)/(A.x - B.x)

The equation from 2 points A, B will be: y = m * (x - B.x) + B.y

Line which is perpendicular with the line above (CD): y =  (-1/m) * x + y0

Since CD goes through A, the equation can be written as: y = (-1/m) * (x - A.x) + A.y

The length (d) between 2 points A, C: d * d = (C.x - A.x) * (C.x - A.x) + (C.y - A.y) * (C.y - A.y)

From the equation of CD, we know C.y = (-1/m)*(C.x - A.x) + A.y
Therefore:
d*d = (C.x - A.x)*(C.x - A.x) + (1/(m*m))*(C.x - A.x)* (C.x - A.x)
Easily find out that C.x - A.x = (+|-) (m*d)/Math.sqrt(m*m + 1)
In java, I guess you can write the function as
public Point[] findCD(Point A, Point B, int widthCD) {
   if (A.x == B.x) {
      return [new Point(A.x - widthCD/2, A.y), new Point(A.x + widthCD/2, A.y)]
   }
   if (A.y == B.y) {
      return [new Point(A.x, A.y - widthCD/2), new Point(A.x, A.y + widthCD/2)]
   }

   var m = (A.y - B.y)/(A.x - B.x);

   var xC = A.x - m*widthCD/(2 * Math.sqrt(m*m + 1));
   var xD = A.x + m*widthCD/(2 * Math.sqrt(m*m + 1));

   var yC = (A.x - xC) / m + A.y;
   var yD = (A.x - xD) / m + A.y;

   return [new Point(xC, yC), new Point(xD, yD)];
}

Note: I don't have java, please correct if I write the pointer or array wrong

Rotation of points in Android


Fundamental group of the following disc

Question: What is the fundamental group of the following space in $\mathbf C^n$?
This is the topological space given by $$\{(x_1,\ldots,x_n)\in \mathbf C^n-\{0\} : \vert x_1\vert < 1, \ldots, \vert x_n\vert <1\} - \{x_1\cdot \ldots \cdot x_n =0\}.$$
For $n=1$, I know it's $\mathbf Z$. I'm guessing it should be $\mathbf Z^n$ in general. Is this true? And why?
Comment: Are you sure it's $\mathbb{Z}$ for $n=1$? The way you defined the space it's contractible, so the fundamental group should vanish.
Comment: Whoops. I was thinking about the punctured polydisc! My apologies.
Comment: Can you describe the unit disc (not punctured!) up to homeomorphism? This is a reasonable first step.
Comment: Ow I think I see what you're getting at. When $n=1$, this is going to be like $\mathbf C$ minus the origin topologically, right? When $n>1$, this is probably a simply connected space, no? It might even be contractable because of all the extra space you get to move around.
Comment: @PiotrPstragowski I changed the question again. This should be a less trivial question.
Answer: Your space deformation retracts to the $n$-torus $\prod_i\{\vert x_i\vert=\frac {1}{2} \}$, so has the same fundamental group : $$\mathbb Z^n $$

Fundamental group of the following disc


Unanswered questions about Second Inversion and Perfect fourth

Question:

image above is show how used the triad second Inversion.
and source is page 76 of paik byung dong theory of  harmonics by Byung
Dong Paik (Korean composer).

1. I've always wondered,
there's an explanation that all the voice parts have to move in a certain direction.
but I don't know why the rest of the notes other than the bass and the Perfect fourth have to move in the certain direction.
For example, in the 1st left part of the image,
it can't the alto in IV6 come down and become A-F-C-C?
I mean, why do I always have to move only with steps? (Except for case 2 in the image)
I don't know the exact reason for that.
2. Why use only I, IV, V?
Why not use same intervals chords like a VI - iii64 - VI6 or iii - vii64 - iii6... etc ?
These are the can same proceed as the examples in the image. so why not use them?
And if case 2 of the image is possible, can't the rest of the chords (ii, iii.. etc) proceed as in that case?
3. Not like the example in the image, the Perfect fourth  note is can't coming as a normal non-chord tone?
not only sus4, Like a Passing Tone, Anticipation, Appoggiatura..
Can't it ever be used like this?
4. Does it matter if a non-chord tone comes to the bass and becomes a Perfect fourth with the upper voice part?
I've seen this progression in Bach Choral A major as shown below.
A-C-A-E(I) -> B-D-A-E(I) -> C-E-A-E(I)
B-D-A-E is half beat and B-D is passing tone and B and E is Perfect fourth
but Contrary to the example in the image, it proceeded without anything special.
Why can this be done like this?
Answer:
why do I always have to move only with steps? (Except for case 2 in the image) I don't know the exact reason for that.

It's more idiomatic, more singable.  It's not a strict rule; you can find counterexamples in real music without having to look too hard.

And if case 2 of the image is possible, can't the rest of the chords (ii, iii.. etc) proceed as in that case?

They can.  Sometimes theorists will consider that such progressions are temporary tonicization of a different scale degree.  These examples focus on I, IV, and V because these are the chords for several prototypical cadential formulas (as is ii-V-I).  Progressions involving other chords may or may not conform to these formulas.
I don't quite understand the third question.  Perhaps you should ask it separately with an example.
As to the fourth question, it can be done like this because, well, it's Bach.  Bach's music is a bit older than the period that is best described by the usual rules of four-part harmony.  Consequently, there are more instances where his music does not comply with the rules.  That point aside, you can hardly expect to cover all allowable progressions in six examples from a beginning harmony textbook.
If by "half beat" you mean that the bass and tenor are moving in eighth notes while the harmonic rhythm is quarter notes, then this is a perfectly normal progression in which the second chord isn't structural (the first two chords if I-I6-IV, for example, or I-I6-V, with passing tones). As a passing sonority, it doesn't need to be consonant, and the fourth between the bass and soprano is of no consequence.
Comment: 2. Is the answer to question 2 the correct answer to the whole? Or did you only answer the part you quoted?                                                                                3. I haven't been able to find an example yet. If I could make an example,
D-F-A(ii) -> D-G-A(ii) -> F-A-C(IV) <-- passing tone
D-F-A(ii) -> D-G-A(ii) -> D-F-A(ii) <-- neighboring tone
like this. Shouldn't it come out like this? If the 4th question is possible, isn't this also possible?
Answer:

there's an explanation that all the voice parts have to move in a certain direction. but I don't know why the rest of the notes other than the bass and the Perfect fourth have to move in the certain direction. ... I mean, why do I always have to move only with steps?

One of the rules** of counterpoint is to favour smooth movement over angular or jumpy movement.  Generally, that means any notes shared between two chords should remain in the same voice, and the rest of the voices move the shortest distance possible while avoiding breaking any other rules.  Part of the rationale is that this will make your lines easier to sing.  They're also easier for the listener's ear to follow.  So, why do these examples unfold as they do?  Because they are using the smoothest voice leading possible for these chords in these inversions.  Do they need to do this?  No, not necessarily.

For example, in the 1st left part of the image, it can't the alto in IV6 come down and become A-F-C-C?

You could do this.  You'd be crossing your voices though (the alto would be below the tenor) and there is a rule** against this.

Why use only I, IV, V? Why not use same intervals chords like a VI - iii64 - VI6 or iii - vii64 - iii6... etc?

Only because these are common progressions.  You are correct that the same principles apply to other chord progressions.  The progressions you suggest would be unusual but there is nothing illegal about them.

Not like the example in the image, the Perfect fourth note is can't coming as a normal non-chord tone? not only sus4, Like a Passing Tone, Anticipation, Appoggiatura.. Can't it ever be used like this?

Yes, a perfect 4th can be created by the presence of any normal non-chord tone and the normal rules** governing non-chord tone resolutions apply.  In such a case, they are not dissonant because they are perfect 4ths; they are dissonant because there is a non-chord tone involved.  4ths are ubiquitous and in most cases they are not considered dissonant and do not require any special handling.  Consider that any voicing of a triad where the root is in the soprano (eg: C-E-G-C) will contain a perfect 4th, and in the vast majority of cases the 4th is not a dissonance.
The examples in the image demonstrate common ways to handle a 2nd inversion triad.  They are not showing ways to handle 4ths in general.  A 4th between the bass and any other voice is considered a dissonance which is why there are rules** about how to handle them.  They are a special case.
Regarding terminology, you used the phrase "Perfect fourth note".  4ths are intervals, not notes, and you need two notes to make an interval.  Therefore, you cannot say a particular note is a "perfect 4th note" because that doesn't make sense.  If you have a 4th and it happens to be dissonant, then one of the notes can probably be singled out as "the dissonance", but you still wouldn't call it a "perfect 4th note".  That term doesn't really mean anything.

Does it matter if a non-chord tone comes to the bass and becomes a Perfect fourth with the upper voice part?

A-C-A-E(I) -> B-D-A-E(I) -> C-E-A-E(I)
B-D-A-E is half beat and B-D is passing tone and B and E is Perfect fourth but Contrary to the example in the image, it proceeded without anything special. Why can this be done like this?

Like you said, they are passing notes which are non-chord tones.  This is not a problem.  Why do they not require special handling like in the examples?  Because these examples are for handling 2nd inversion triads, not non-chord tones.  There's a difference.  But you could easily imagine the 2nd chord being B-E-G(#)-E, in which case it would be a passing 2nd inversion chord which follows the examples.
** These rules are really just suggestions.  They're also descriptive, not prescriptive.  That means they describe what others have done in the past which worked well; they do not command you to do the same in the future.  Keep in mind that they were derived several hundred years ago to satisfy the aesthetic tastes of that particular time period.  They don't apply to all music everywhere at all times.  That said, they are not arbitrary and do have usefulness outside of their original context.  Use your judgement.  Don't follow them religiously.  Even within the music of that time period, you will see many examples of these rules being broken.  Often there is some rationale or exception to be noted; sometimes the music just made sense that way for artistic reasons and rules be damned; sometimes it's because you end up getting stuck between two rules and one of them needs to be broken.
Comment: Thank you very much!

What I said in question 3 is the perfect 4th relationship created by the bass and non-chord tones.

 D-F-A(ii) -> D-G-A(ii) -> F-A-C(IV) <-- passing tone D-F-A(ii) -> D-G-A(ii) -> D-F-A(ii) <-- neighboring tone

Are you saying this is possible?
Comment: As I said in question 1, I misunderstood the example, so I didn't know that the chord in question 4 followed the example.

but you say

'Why do they not require special handling like in the examples? Because these examples are for handling 2nd inversion triads, not non-chord tones. There's a difference.'

I'm still curious about this part. I think the reason the 2nd inversion triads are treated differently is like you said 'A 4th between the bass and any other voice is considered a dissonance which is why there are rules'.
Comment: But you said that the 4th with non-chord tone, where the same 4th between the bass occurs, is different from the 2nd inversion triads. I don't understand this.
Comment: i mean, Is there any other reason other than 4th between the bass that the 2nd inversion triads are treated differently?
Comment: And if B-D-A-E is B-E-G(#)-E in question 4, does that mean that non-chord tones can be inserted in the 2nd inversion triads?
Comment: Yes, a perfect 4th can be created between the bass and a non-chord tone of any type. Your examples are ok (except for the parallel 5ths in your passing tone progression). Yes, you can have non-chord tones in any chord and any inversion. Yes, even 2nd inversion.
Comment: I confused you with my response to #4. I didn't mean that "B-D-A-E _is_ B-E-G(#)-E". I was only trying to draw the distinction between a true 2nd inversion chord (B-E-G-E) that follows the rules** and a passing tone in the bass (B-D-A-E) that doesn't. 2nd inversion chords are 2nd inversion chords. Non-chord tones are non-chord tones. They are different and have different rules** of resolution.
Comment: What makes B-E-G-E a dissonance? It's the 4th between the bass and tenor/soprano. What makes B-D-A-E a dissonance? It's the fact that there are 2 passing notes. B rubs the A, and D rubs the E.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/137311/discussion-between-ibonyun-and-guss2222).


Como organizar arrays

Question: Na documentação do Pear, ele define um padrão para como montar a estrutura de um array:
<code>$some_array = array(
    'foo'  => 'bar',
    'spam' => 'ham',
);
</code>
Dessa forma, que já utilizo, separa de forma legível os elementos, mas e quanto a um array com digamos, 100 elementos. O código ficará muito extenso, mesmo assim está correto?
Esse é o único padrão a seguir? Há outras indicações de como essa estrutura deve ser organizada?
Comment: Com 100 elementos seria uma boa guardar isso no banco de dados.
Comment: Foi apenas uma suposição, @rray. Mas digamos que seja um array contendo configurações a serem salvas ou manipuladas.
Answer: Não, é a mesma coisa. Não tem como fazer mais organizado que isto a não se que exista alguma situação específica que ajude. Você pode pular uma linha para separar blocos que façam sentido, ou pode reavaliar se precisa todos elementos juntos no array, depende da situação.
Enfim, é gosto. Este é um padrão bom mas o importante é ser legível, pior seria espremer tudo porque tem informação demais.
Se faz sentido por no código, coloque no código. Só deixe fora do código se houver um motivo para isto. Se as informações devem vir de fonte externa porque o requisito pede isto, seja para facilitar a manutenção, configuração, etc. aí não importa porque os dados serão carregados no array sem precisar se preocupar com a sintaxe ficar grande e confusa.

Como organizar arrays


Sklearn - Choosing the right model for supervised learning/classification task

Question: I am beginning to learn how to use scikit-learn and I have a hard time choosing the right model.
Here is my dataset:
I have 100 persons. Each person was measured three times: baseline, first event and second event.
Each measurement had 100 different markers per person that range from 0.1 to 1000.
Additionally I have outcome measurements of each event: outcome can be 0, 1 or 2.
My task is to find just a few markers (let's say 10) that can predict outcome with a good accuracy.
If I am right it should be: Supervised learning/Classification problem.
What model would be the best?
Thanks for your help!
Answer: I'd try visualizing data in 3d, use generalized scatterplot matrix or  use PCA (if you know what it is) to project data to 2d and then try to see the structure.
In such low-dimensional dataset it should be easy to see visually which classifier will be the best, using scikit-learn's comparison of different classifiers.
Answer: Your data set has the following characteristics and consequences:

Not to many data points (100 * 3), so the method should work well on small datasets
Only a subset of the features may be used to predict the outcome, so you search for a sparse model
You want to interpret your model after learning it.
Finite, discrete outcome variable so model should be able to handle classification task
You do not mention it, but often it is best to start simple so the model should be simple and fast.

Starting simple is key to figure out if and how you want to improve. Based on these I would suggest regularized logistic regression. Examples are:

Logistic regression with L2-norm. This minimizes the sum of the squared weights (besides the prediction errors), i.e. close to zero is good enough.
Logistic regression with L1-norm. This minimizes the sum of the weights (besides the prediction error), i.e. most weights are exactly zero.

Both models can implemented with LogisticRegression. Note the penalty parameter that specifies the regularization (i.e. norm). Also check LogisticRegressionCV that can optimize the regularization strength for you.
Comment: Question asked for classification model. Linear regression is not used for classification.
Comment: That's true, I will check in sklearn for the logistic regressions variant
Comment: Check, now advising LogisticRegression
Answer: You could use decision trees, they have some desirable properties for your application:

they will automatically search among your many variables and select the ones that best predict the outcome
they are very easy to interpret. Basically they tell you that for each record you look first at a specific variable and compare the value to a cutoff. Based on the result of that comparison, you go on the corresponding branch of the tree to the next branching based on some other variable etc. When you arrive in a leaf, the majority class among the training records in that leaf will tell you how to classify your new record.
they can natively deal with classification into more than two classes. Some algorithms like support vector machines would need workarounds to be able to predict your three possible outcomes.

Random forests would usually have better classification performance than a single tree, but they are more difficult to interpret.


Close mini-cart dropdown automatically after 2 seconds in WooCommerce

Question: In my woocommerce shop, link, I have changed the add to cart button, when a user click on the add to cart button the cart dropdown is droping from to top, how can i close it after 2 seconds unless touched, (flatsome theme)
someone can help me figure out what js or other solution i can add to make the cart dropdown close itself after 2 secods?
If someone wants to add a quantity box with +/- next to the add to cart that will show the cart dropdown here is the codes: enjoy.

and in functions.php
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() && ! is_cart() ) {

        $html = 'id .'" onclick="addToCartLink(this,' . $product->id .')" class="add_to_cart_button product_type_simple button primary is-flat mb-0 is-small">הוסף לסל';
        //$html = 'id .')">הוסף לסל';

        $html .= '
';
        $html .= '<input type="button"  value="-"  class="minus button is-form">';
        $html .= '<input type="number" id="quantity_'. $product->id .'" class="input-text qty text" step="1" min="0" max="9999" name="quantity" value="1" title="כמות" size="4" pattern="[0-9]*" inputmode="numeric" >';
        $html .= '<input type="button" value="+" class="plus button is-form">';
        $html .= '
';

    }
    return $html;
}

Comment: You should need to give us a live website link (editing your question please)…
Comment: Here is the link [link](https://pharmers.co.il), add a product to the cart,
The Cart will drop from the top,
How can I add a js to close it after 2 seconds ?
Thanks Loic:)
Answer: You could try something like this (without guaranty as I can't test it):
add_action( 'wp_footer', 'custom_jquery_script' );
function custom_jquery_script(){
    ?>

    <?php
}

Explanations:
When an item is added to cart, class current-dropdown is added to:

and will apply a CSS to this Child html element to make it visible (the cart popin content):

So with my jQuery code, I catch "body" delegated event added_to_cart and I use setTimeout() javascript function to remove that current-dropdown class after 2 seconds (2000 milli seconds). When removing the class, it hides automatically the mini-cart content pop-in…
That should be the right way.

If it doesn't work, you can try (2 alternatives):
1) to replace in the code 'added_to_cart' by 'adding_to_cart' event instead
2) to replace $('body').on( 'added_to_cart', function(){ by:
$('.add_to_cart_button').click( function(){

I hope it will work…
Comment: @itayko **So know may be the problem is:** How do you embed this script? Even if it doesn't work at all for now (remember that I can't test it for real), Is this answer do not deserve to be upvoted as my explanations are the real process...
Comment: Thanks again for your help. unfortunately it didn't work, I tried all scenarios, any clue why ? thanks
Comment: i'm embeding this code inside the header, i tried also in the footer, is it working for you in inspect mode ?
the cart need to be closed automatically without touching with the mouse, is this possible ? :(
Comment: I upvoted u, you are great, unfortunately, it's still not working :(


Javascript sum values in 3 objects

Question: Hi I'm trying to sum the values I have in 3 json objects.
var things = {
    "noun": {
        "syn": ["belongings", "holding", "stuff", "property"]
    }
};
var stuff = {
    "noun": {
        "syn": ["belongings", "holding", "property"]
    }
};
var crap = {
    "noun": {
        "syn": ["things", "holding", "waste"]
    }
};

result = {};
word1 = things.noun.syn
for (key in word1) {
    nk = word1[key];
    if (result.nk == undefined) {
        result.nk = 1
    } else {
        result.nk = result.nk + 1;
    }
}
console.log(result);

The result I am getting is result.nk instead of result.belongings for example.
I've been screwing around in a jsfiddle: http://jsfiddle.net/qunUz/2/
How do I sum the amount of times each value appears?
Comment: btw, you should not use for-in loops to iterate over arrays. Use a regular for loop or the forEach method instead.
Comment: @missingno i thought you were supposed to use for-in for objects? (its not an array). Am i wrong?
Comment: Well, in the code you wrote `word1` is an array...
Answer: To access a property given a string value you should use bracket notation
result[nk] //access the property defined by nk's value

instead of the dot notation you are using
result.nk     //access the 'nk' property
result['nk']  //equivalent in bracket notation.

Answer: By setting result.nk you are not using the variable nk but really result.nk.
You should store it like this:
result[nk] = 1;

Like demonstrated on the updated fiddle: http://jsfiddle.net/qunUz/3/
Answer: I think this is what you are trying to do. The following will sum up the occurrences of each value in your three different arrays.
var a = things.noun.syn.concat(stuff.noun.syn).concat(crap.noun.syn);
var a = a.reduce(function (acc, curr) {
  if (typeof acc[curr] == 'undefined') {
    acc[curr] = 1;
  } else {
    acc[curr] += 1;
  }

  return acc;
}, {});

Results in
belongings: 2
holding: 3
property: 2
stuff: 1
things: 1
waste: 1

If your target browser doesn't have a reduce function, you can use underscore.js (or just copy their reduce function).

Javascript sum values in 3 objects


Copy list to Flowdocument messes up 1st listitem

Question: I'm writing an extension that allows a user to merge multiple notes into a single note and provides some features like adding periods onto the end of the original notes. I'm writing the code that copies the parts of one flowdocument to another and inserts the periods as it goes.
I am having problems copying lists to the new document. For some reason the first listitem always ends up in the paragraph PREceeding the list instead of in the list.
My code:
foreach (Block b in tempDoc.Blocks)
                {
                    thisBlock++;
                    if (b is List)
                    {
                        pkhCommon.WPF.Helpers.AddBlock(b, mergedDocument);
                    }
                    else
                    {
                        Paragraph p = b as Paragraph;
                        foreach (Inline inl in p.Inlines)
                        {
                            if (!(inl is LineBreak))
                                pkhCommon.WPF.Helpers.AddInline(inl, mergedDocument);
                        }
                        if (thisElement != lastElement || thisBlock != lastBlock)
                            if ((bool)cb_AddPeriods.IsChecked)
                                pkhCommon.WPF.Helpers.AddInline(new Run(". "), mergedDocument);
                            else
                                pkhCommon.WPF.Helpers.AddInline(new Run(" "), mergedDocument);
                    }
                }

Below is the function to merge the blocks. The AddIline function works the same way.
    public static void AddBlock(Block from, FlowDocument to)
    {
        if (from != null)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                TextRange range = new TextRange(from.ContentStart, from.ContentEnd);
                System.Windows.Markup.XamlWriter.Save(range, stream);
                range.Save(stream, DataFormats.XamlPackage);
                TextRange textRange2 = new TextRange(to.ContentEnd, to.ContentEnd);
                textRange2.Load(stream, DataFormats.XamlPackage);
            }
        }
    }

I can't understand why the flowdocument is deciding to put the listitem into the PREceeding paragraph.
Answer: Adding a block to the FlowDocument's block collection should put it at the end.
This works for  for me.
Document.Blocks.Add(blockToAdd);

You are doing the save/load to clone the block right?  Can you just try adding it this way at the end instead of inserting in the text range?
var blockToAdd = XamlReader.Load(stream) as Block;
Document.Blocks.Add(blockToAdd);

Part of your issue is that after saving, the stream position is at the end of the stream, so there is nothing to Load.  There is probably a better way to fix this but I am out of time to help.  Setting position to 0 feels wrong. This has no parse exception.
        var from = new System.Windows.Documents.List(new ListItem(new Paragraph(new Run("Blah"))));
        using (var stream = new MemoryStream())
        {
            System.Windows.Markup.XamlWriter.Save(from, stream);
            stream.Position = 0;
            Block b = System.Windows.Markup.XamlReader.Load(stream) as Block;
        }

Comment: I just get an xamlparse exception: Root element is missing. I used this code:     `using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    TextRange range = new TextRange(from.ContentStart, from.ContentEnd);
                    System.Windows.Markup.XamlWriter.Save(range, stream);
                    range.Save(stream, DataFormats.XamlPackage);
                    Block b = System.Windows.Markup.XamlReader.Load(stream) as Block;
                    to.Blocks.Add(b);
                }`
Comment: I am not sure of the best way to fix it, but your issue appears to be that you are at the end of the stream, so when it is loaded, there is nothing to load.  Resetting the stream position will fix it.  See my edited answer.
Comment: I also had to remove the line `System.Windows.Markup.XamlWriter.Save(range, stream);`. After that it worked.


getting all dependencies of an R package when calling library

Question: I have built my own R package, and I when I call library() on my package I want to also download all the dependencies while would appear in the DESCRIPTION file.
How does this work exactly? I can library on my package and I have to individually call library on some of the packages that are used in my package.
Comment: I'm confused: you mention both *"download all dependencies"* (which should be handled with `install.packages("yourpackage")`) and then *"call library"*. In general, a package should never fully load another package into the user's environment; by including the dependent packages in the `NAMESPACE` as `import(data.table)` (e.g.) ensures that all of the functions in your package have full access to that package's functions.
Comment: see the resolved part of this question https://stackoverflow.com/questions/37568884/r-package-does-not-load-dependencies?noredirect=1&lq=1
Comment: If you insist on side-effect when loading your package (rarely justified imo, so far the only popular exception is `library(tidyverse)`, which despite being popular/convenient is still a problem in some areas), then see the tidyverse package for how it does it.
Comment: And the word **download** seems confusing in the xontext of your question. May be you mean that you wanted to load the dependency packages in your R session ??
Comment: Other packages are loaded based on the Description file. Any packages in the **Depends** section of the description file will be automatically loaded when your package is loaded. Most package developers prefer to use **Imports** in the description file, which makes the other packages available internally, but does not presume to load them for the user.
Comment: If I put dplyr in the imports section. Will calling library on my package load dplyr?
Comment: https://stackoverflow.com/a/40391302/190277
Answer: You can do what R does for you by relying on some public information:
> db <- tools::CRAN_package_db()    # a big matrix with all packages
> deps <- tools::package_dependencies("ggplot2", recursive=TRUE, db=db)
> deps                   # a list as you could have called with more than arg
$ggplot2
 [1] "digest"       "glue"         "grDevices"    "grid"         "gtable"
 [6] "isoband"      "MASS"         "mgcv"         "rlang"        "scales"
[11] "stats"        "tibble"       "withr"        "utils"        "methods"
[16] "graphics"     "nlme"         "Matrix"       "splines"      "farver"
[21] "labeling"     "lifecycle"    "munsell"      "R6"           "RColorBrewer"
[26] "viridisLite"  "fansi"        "magrittr"     "pillar"       "pkgconfig"
[31] "vctrs"        "lattice"      "colorspace"   "cli"          "utf8"

>

So by calling the package_dependencies (base R) function you get the list of all dependencies, either level one or fully recursively.
You could then check this with installed.packages() to see what if anything is missing in the local installation.


Do ${\mathbb R}^\infty$, ${\mathbb Q}^\infty$, and ${\mathbb C}^\infty$ admit dot/inner products?

Question: I wonder if the vector spaces ${\mathbb R}^\infty$, ${\mathbb Q}^\infty$, and ${\mathbb C}^\infty$ admit dot/inner products. Maybe even extensions of the usual dot/inner products from ${\mathbb R}^n$, ${\mathbb Q}^n$, and ${\mathbb C}^n$?
Comment: Ever heard of $l^2$ space? it's not exactly what you ask for but it is close. I have the feeling that a nondegenerate inner product on the whole of $\mathbb{R}^\infty$ is impossible, but do not know how to prove it yet.
Answer: If by $\mathbb{R}^\infty$ you mean $c_{00}$, the space of all real sequences with at most finitely many nonzero terms, then you can construct an inner product similarly like in $\mathbb{R}^n$:
For $x = (x_n)_{n=1}^\infty, y = (x_n)_{n=1}^\infty \in\mathbb{R}^\infty$ define
$$\langle x, y\rangle = \sum_{n=1}^\infty x_ny_n$$
This sum is finite as at most finitely many $x_ny_n$ are nonzero so $\langle\cdot, \cdot\rangle$ is well defined. You can check that it is an inner product on $\mathbb{R}^\infty$.
If $\mathbb{R}^\infty = \mathbb{R}^\mathbb{N}$, i.e. the space of all real sequences, then you cannot define it like in $c_{00}$ because the sum need not converge, but the answer is still yes.
In fact, any vector space $V$ admits an inner product.
Let $\{b_i\}_{i\in I}$ be a Hamel basis for $V$. For every $x,y \in V$ we have $x = \sum_{i \in S} \alpha_ib_i$ and $y = \sum_{j \in T} \beta_jb_j$ for some finite subsets $S, T \subseteq I$, where $\alpha_i, \beta_j \ne 0$ (the representations of this form are unique). Also set $\alpha_i = 0, \forall i \in T\setminus S$ and $\beta_j = 0, \forall j \in S\setminus T$.
Now it makes sense to define:
$$\langle x, y\rangle = \sum_{k \in S \cup T} \alpha_k\overline{\beta_k}$$
You can check that $\langle\cdot, \cdot\rangle$ is an inner product on $V$.
Comment: How nice! Vector spaces are indeed a well-behaved bunch
Answer: The short answer is, yes.  But you may need to get a little bit creative in your definitions.
For example, the set of continuous  functions $f:[0,1]\to \mathbb R$ forms a vector space in $\mathbb R^\infty$
$\int_0^1 f(x)g(x) \ dx$ is an inner product for this space.
Answer: Yes, with some additional criteria on the inner product. If you try to extend the inner product on $\mathbb{R}^n$ for example to $\mathbb{R}^\infty$ as $\langle x,y\rangle=\sum_{i=0}^\infty x_iy_i$ you run into the problem that this series may not converge. If we consider the subset of $\mathbb{R}^{\infty}$ consisting of elements where the series $\sum_{i=0}^\infty x_i^2$ converges, then on these elements the inner product is well defined and we get an inner product space (in fact we get a Hilbert space). You can look into $\ell^2$ space for more reading.


Express serving static file: can't set headers after they are send

Question: I am using the express.static built-in middleware function to serve static files, but the console prints the error: Can't set headers after they are sent.
here is my code, i don't know what is wrong with this
'use strict';

let path = require('path');
let express = require('express');
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
let formidable = require('express-formidable');
let routes = require('./routes');
let app = express();
let port = process.env.PORT || 3000;

let db = mongoose.connect('mongodb://localhost:27017/old-driver');

// deal with img post
app.use(formidable({
  uploadDir: path.join(__dirname, 'upload'),
  keepExtensions: true
}));

app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());

// access-control
app.all('*', (req, res, next) => {
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
  res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.set("X-Powered-By",' 3.2.1')
  res.type("application/json");
  res.type("jpg");
  next();
});

// set assets path, GET /assets/demo.png
app.use('/assets', express.static('upload'));

routes(app);

app.listen(port);

the route middleware method:
getAllTeachers: (req, res) => {
    Teacher.find({}, (err, teacher) => {
        if (err) {
            res.send(err);
        } else {
            res.json(teacher);
        }
    });
},

Even if I remove the access-contol code as shown below, still get error
let db = mongoose.connect('mongodb://localhost:27017/old-driver');

// deal with img post
app.use(formidable({
  uploadDir: path.join(__dirname, 'upload'),
  keepExtensions: true
}));

app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());

// set assets path, GET /assets/demo.png
app.use('/assets', express.static('upload'));

routes(app);

app.listen(port);

when I request 2 existing jpg file, I also get 404 error in one jpg file
404 screenshot
Answer: To solve this you need to use app.use function instead of app.all for mounting your middleware function. app.use adds the middleware function to middleware stack ensuring that they are executed in same order at which they are added.
So you need to do this :
app.use((req, res, next) => { //change app.all to app.use here and remove '*', i.e. the first parameter part
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
  res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.set("X-Powered-By",' 3.2.1')
  res.type("application/json");
  res.type("jpg");
  next();
});

EDIT:
As you told in comments the above method doesn't work so what you can do is use the setHeaders method of express.static method to set headers before file is served like this :
app.use('/assets', express.static('upload', {
  setHeaders: function(res, path) {
    res.set("Access-Control-Allow-Origin", "*");
    res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
    res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.set("X-Powered-By",' 3.2.1')
    res.type("application/json");
    res.type("jpg");
  }
}));

Put this static file serving middleware method above the app.use so that app.use method for setting headers is not called hence the headers won't be set again.
Comment: @Rcrab I edited the post please try what I told and tell if this makes any difference