问:
C# code to add soap header wsse:Security, wsse:BinarySecurityToken,ds:Signature, wsse:UsernameToken,wsu:Timestamp
we are able to invoke the web service from SOAP UI tool by adding key store, Outgoing WS-Security Configuration (TimeStamp, UserName & Signature) and namespaces for usertoken, timestamp body and then apply outgoing wss -> apply "TimeStamp_Signed".

But how to do these things in c# code (we are consuming java web service)
 Soap Header :

We are used custom binding option to create these soap headers but when we inspect in IClientMessageInspector -> BeforeSendRequest header was not been created.

Sample Code attached here
    public static bool AcceptAllCertificatePolicy(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

```<code>    private static Binding GetCustomBinding()
    {
        var asbe = new AsymmetricSecurityBindingElement
        {
            MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12,
            InitiatorTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
            RecipientTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
            MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt,
            SecurityHeaderLayout = SecurityHeaderLayout.Strict,
            EnableUnsecuredResponse = true,
            IncludeTimestamp = true
        };

        asbe.SetKeyDerivation(false);
        asbe.AllowSerializedSigningTokenOnReply = true;

        asbe.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128Rsa15;
        asbe.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
        asbe.EndpointSupportingTokenParameters.Signed.Add(new X509SecurityTokenParameters());

        var myBinding = new CustomBinding();

        myBinding.Elements.Add(asbe);

        myBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));

        var httpsBindingElement = new HttpsTransportBindingElement
        {
            RequireClientCertificate = true
        };

        myBinding.Elements.Add(httpsBindingElement);

        return myBinding;

    }

    private static Client GetCredentialingClient()
    {
        var customBinding = GetCustomBinding();

        var client = new Client
            (customBinding,
            new EndpointAddress(new Uri(_endpointAddress),
            new DnsEndpointIdentity(_dnsEndpointIdentity),
            new AddressHeaderCollection()));

        client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
            System.ServiceModel.Security.X509CertificateValidationMode.None;

        client.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
        client.Endpoint.Behaviors.Add(new InspectorBehavior());

        SetClientCredentialsSecurity(client.ClientCredentials);

        Binding binding = client.Endpoint.Binding;
        BindingElementCollection elements = binding.CreateBindingElements();
        SecurityBindingElement security = elements.Find<SecurityBindingElement>();

        if (security != null)
        {
            X509SecurityTokenParameters tokenParameters = new X509SecurityTokenParameters();
            tokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
            tokenParameters.RequireDerivedKeys = false;
            security.EndpointSupportingTokenParameters.SignedEncrypted.Add(tokenParameters);
            client.Endpoint.Binding = new CustomBinding(elements.ToArray());
        }

            return client;
    }

    private static void SetClientCredentialsSecurity(ClientCredentials clientCredentials)
    {
        clientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
               System.ServiceModel.Security.X509CertificateValidationMode.None;
        clientCredentials.UserName.UserName = _userName;
        clientCredentials.UserName.Password = _password;
        clientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(_certificatePath, _certificatePassword);
        clientCredentials.ClientCertificate.Certificate = new X509Certificate2(_certificatePath,_certificatePassword);
    }

    static void Main(string[] args)
    {
        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;

        using (var client = GetCredentialingClient())
        {
            client.Open();

            try
            {

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        Console.ReadLine();
    }
</code>```

Please do help us to create these soap header in  c# code

Thank You

答:
You could try to add header in your xml under headers node.

```<code><endpoint address="http://ws-wuxipc-5077:4000/calculator" binding="basicHttpBinding"
contract="ServiceInterface.ICalculatorService" name="cal">
<headers>
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:Username>
    </wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">monMonDePasse</wsse:Password>
    <wsse:Nonce>sdsdsdlojhfdsdM5Nw==</wsse:Nonce>
    <wsu:Created>2019-01-21T6:17:34Z</wsu:Created>
  </wsse:UsernameToken>
</Security>
</code>```

Or you could add header programmatically through  OperationContextScope and XmlDocument.

```<code> using (ChannelFactory<ICalculatorService> ChannelFactory = new ChannelFactory<ICalculatorService>("cal"))
    {

        ICalculatorService employeeService = ChannelFactory.CreateChannel();
        using (OperationContextScope scope = new OperationContextScope((IContextChannel)employeeService))
        {

            System.Xml.XmlDocument document = new XmlDocument();

            XmlElement element = document.CreateElement("wsse", "UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            XmlElement newChild = null;

            newChild = document.CreateElement("wsse", "Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            newChild.InnerText = "finance";
            element.AppendChild(newChild);

            newChild = document.CreateElement("wsse", "password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            newChild.SetAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
            newChild.InnerText = "387";
            element.AppendChild(newChild);

            MessageHeader messageHeader = MessageHeader.CreateHeader("security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", element, false);

            OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
            employeeService.Add(5, 6);
        }

        Console.Read();
    }
</code>```

Body:
we are able to invoke the web service from SOAP UI tool by adding key store, Outgoing WS-Security Configuration (TimeStamp, UserName & Signature) and namespaces for usertoken, timestamp body and then apply outgoing wss -> apply "TimeStamp_Signed".

But how to do these things in c# code (we are consuming java web service)
 Soap Header :

We are used custom binding option to create these soap headers but when we inspect in IClientMessageInspector -> BeforeSendRequest header was not been created.

Sample Code attached here
    public static bool AcceptAllCertificatePolicy(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

    private static Binding GetCustomBinding()
    {
        var asbe = new AsymmetricSecurityBindingElement
        {
            MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12,
            InitiatorTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
            RecipientTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
            MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt,
            SecurityHeaderLayout = SecurityHeaderLayout.Strict,
            EnableUnsecuredResponse = true,
            IncludeTimestamp = true
        };

        asbe.SetKeyDerivation(false);
        asbe.AllowSerializedSigningTokenOnReply = true;

        asbe.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128Rsa15;
        asbe.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
        asbe.EndpointSupportingTokenParameters.Signed.Add(new X509SecurityTokenParameters());

        var myBinding = new CustomBinding();

        myBinding.Elements.Add(asbe);

        myBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));

        var httpsBindingElement = new HttpsTransportBindingElement
        {
            RequireClientCertificate = true
        };

        myBinding.Elements.Add(httpsBindingElement);

        return myBinding;

    }

    private static Client GetCredentialingClient()
    {
        var customBinding = GetCustomBinding();

        var client = new Client
            (customBinding,
            new EndpointAddress(new Uri(_endpointAddress),
            new DnsEndpointIdentity(_dnsEndpointIdentity),
            new AddressHeaderCollection()));

        client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
            System.ServiceModel.Security.X509CertificateValidationMode.None;

        client.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
        client.Endpoint.Behaviors.Add(new InspectorBehavior());

        SetClientCredentialsSecurity(client.ClientCredentials);

        Binding binding = client.Endpoint.Binding;
        BindingElementCollection elements = binding.CreateBindingElements();
        SecurityBindingElement security = elements.Find<SecurityBindingElement>();

        if (security != null)
        {
            X509SecurityTokenParameters tokenParameters = new X509SecurityTokenParameters();
            tokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
            tokenParameters.RequireDerivedKeys = false;
            security.EndpointSupportingTokenParameters.SignedEncrypted.Add(tokenParameters);
            client.Endpoint.Binding = new CustomBinding(elements.ToArray());
        }

            return client;
    }

    private static void SetClientCredentialsSecurity(ClientCredentials clientCredentials)
    {
        clientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
               System.ServiceModel.Security.X509CertificateValidationMode.None;
        clientCredentials.UserName.UserName = _userName;
        clientCredentials.UserName.Password = _password;
        clientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(_certificatePath, _certificatePassword);
        clientCredentials.ClientCertificate.Certificate = new X509Certificate2(_certificatePath,_certificatePassword);
    }

    static void Main(string[] args)
    {
        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;

        using (var client = GetCredentialingClient())
        {
            client.Open();

            try
            {

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        Console.ReadLine();
    }

Please do help us to create these soap header in  c# code

Thank You

Body:
You could try to add header in your xml under headers node.

<endpoint address="http://ws-wuxipc-5077:4000/calculator" binding="basicHttpBinding"
contract="ServiceInterface.ICalculatorService" name="cal">
<headers>
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:Username>
    </wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">monMonDePasse</wsse:Password>
    <wsse:Nonce>sdsdsdlojhfdsdM5Nw==</wsse:Nonce>
    <wsu:Created>2019-01-21T6:17:34Z</wsu:Created>
  </wsse:UsernameToken>
</Security>

Or you could add header programmatically through  OperationContextScope and XmlDocument.

 using (ChannelFactory<ICalculatorService> ChannelFactory = new ChannelFactory<ICalculatorService>("cal"))
    {

        ICalculatorService employeeService = ChannelFactory.CreateChannel();
        using (OperationContextScope scope = new OperationContextScope((IContextChannel)employeeService))
        {

            System.Xml.XmlDocument document = new XmlDocument();

            XmlElement element = document.CreateElement("wsse", "UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            XmlElement newChild = null;

            newChild = document.CreateElement("wsse", "Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            newChild.InnerText = "finance";
            element.AppendChild(newChild);

            newChild = document.CreateElement("wsse", "password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            newChild.SetAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
            newChild.InnerText = "387";
            element.AppendChild(newChild);

            MessageHeader messageHeader = MessageHeader.CreateHeader("security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", element, false);

            OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
            employeeService.Add(5, 6);
        }

        Console.Read();
    }


来源: stackexchange

问:
How can I get the return value from an `setTimeout` callback?
consider this code

```<code>const obj = {
  generate(num) {
    return Math.random()*num;
  },
  add(a,b) {
    return this.generate(a) + this.generate(b)
  }
};

function delay(func, ms) {
  function wrapper() {
    setTimeout(() => func.apply(this, arguments), ms)  // How can I get the return value from the original function?
  }

  return wrapper;
}

// create wrappers
obj.f1000 = delay(obj.add, 1000);
obj.f1500 = delay(obj.add, 1500);

obj.f1000(1,3);
obj.f1500(2,5);
</code>```

I made a wrapper to delay the method call for add()
Is there a way to retrieve the value from the callback inside setTimeout, i.e. the this.generate(a) + this.generate(b) from add()?

答:
Just change this line within the wrapper:

```<code>setTimeout(() => func.apply(this, arguments), ms)
</code>```

to return a Promise (ES6)

```<code>return new Promise(resolve => setTimeout(() => resolve(func.apply(this, arguments)), ms));
</code>```

You can access the delayed result via .then.

Update Per OP's request, edited answer to use async/await insted of then. Since await needs to be called inside a function declared as async, we need to wrap our js code inside a new function (main() below):

const obj = {
  generate(num) {
    return Math.random() * num;
  },
  add(a, b) {
    return this.generate(a) + this.generate(b)
  },

};

function delay(func, ms) {
  function wrapper() {
    // CHANGE THIS LINE
    return new Promise(resolve => setTimeout(() => resolve(func.apply(this, arguments)), ms)); // How can I get the return value from the original function?
  }
  return wrapper;
}

//await can only work in an 'async' function
async function main() {
  obj.f1000 = delay(obj.add, 1000);
  console.time('completed');

  // add await here
  let x = await obj.f1000(1, 3);
  console.log(x);
  console.timeEnd('completed');
}

main();```

ContentLicense: CC BY-SA 4.0

Body:
consider this code

const obj = {
  generate(num) {
    return Math.random()*num;
  },
  add(a,b) {
    return this.generate(a) + this.generate(b)
  }
};

function delay(func, ms) {
  function wrapper() {
    setTimeout(() => func.apply(this, arguments), ms)  // How can I get the return value from the original function?
  }

  return wrapper;
}

// create wrappers
obj.f1000 = delay(obj.add, 1000);
obj.f1500 = delay(obj.add, 1500);

obj.f1000(1,3);
obj.f1500(2,5);

I made a wrapper to delay the method call for add()
Is there a way to retrieve the value from the callback inside setTimeout, i.e. the this.generate(a) + this.generate(b) from add()?

Body:
Just change this line within the wrapper:

setTimeout(() => func.apply(this, arguments), ms)

to return a Promise (ES6)

return new Promise(resolve => setTimeout(() => resolve(func.apply(this, arguments)), ms));

You can access the delayed result via .then.

Update Per OP's request, edited answer to use async/await insted of then. Since await needs to be called inside a function declared as async, we need to wrap our js code inside a new function (main() below):

const obj = {
  generate(num) {
    return Math.random() * num;
  },
  add(a, b) {
    return this.generate(a) + this.generate(b)
  },

};

function delay(func, ms) {
  function wrapper() {
    // CHANGE THIS LINE
    return new Promise(resolve => setTimeout(() => resolve(func.apply(this, arguments)), ms)); // How can I get the return value from the original function?
  }
  return wrapper;
}

//await can only work in an 'async' function
async function main() {
  obj.f1000 = delay(obj.add, 1000);
  console.time('completed');

  // add await here
  let x = await obj.f1000(1, 3);
  console.log(x);
  console.timeEnd('completed');
}

main();


问:
Encountering IllegalArgumentException in Jboss EAP
I'm miograting an app in our server, from Websphere to JBoss EAP7.
The app is working fine in the Webspehere server but when we migrate in in JBoss, we are encountering an exception upon logging in the app.

```<code>java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException
</code>```

Here is the stacktrace of the error.

```<code>2019-05-28 17:17:38,161 ERROR [stderr] (default task-7) java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.infinispan.session.coar  se.CoarseSessionAttributes.setAttribute(CoarseSessionAttributes.java:63)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.undertow.session.Distri  butableSession.setAttribute(DistributableSession.java:147)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at io.undertow.servlet.spec.HttpSessionImpl.setAttrib  ute(HttpSessionImpl.java:169)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:803)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .handleFirstRequest(ServletInitialHandler.java:285)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .dispatchRequest(ServletInitialHandler.java:264)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .access$000(ServletInitialHandler.java:81)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  $1.handleRequest(ServletInitialHandler.java:175)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.Connectors.executeRootHandler(C  onnectors.java:202)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.HttpServerExchange$1.run(HttpSe  rverExchange.java:792)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor.runWorker(  ThreadPoolExecutor.java:1149)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor$Worker.run  (ThreadPoolExecutor.java:624)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7)         at java.lang.Thread.run(Thread.java:748)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) Caused by: org.infinispan.commons.marshall.NotSerializableExc  eption: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) java.lang.Exception: org.infinispan.commons.marshall.NotSeria  lizableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:809)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)

</code>```

Any inputs would be appreciated thanks!

答: I already fixed it by adding implements Serialization in my class specifically in ListLovListVO.</p>

Body:
I'm miograting an app in our server, from Websphere to JBoss EAP7.
The app is working fine in the Webspehere server but when we migrate in in JBoss, we are encountering an exception upon logging in the app.

java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException

Here is the stacktrace of the error.

2019-05-28 17:17:38,161 ERROR [stderr] (default task-7) java.lang.IllegalArgumentException: org.infinispan.commons.ma  rshall.NotSerializableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.infinispan.session.coar  se.CoarseSessionAttributes.setAttribute(CoarseSessionAttributes.java:63)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at org.wildfly.clustering.web.undertow.session.Distri  butableSession.setAttribute(DistributableSession.java:147)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at io.undertow.servlet.spec.HttpSessionImpl.setAttrib  ute(HttpSessionImpl.java:169)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:803)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,162 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,163 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,164 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .handleFirstRequest(ServletInitialHandler.java:285)
2019-05-28 17:17:38,165 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .dispatchRequest(ServletInitialHandler.java:264)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  .access$000(ServletInitialHandler.java:81)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletInitialHandler  $1.handleRequest(ServletInitialHandler.java:175)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.Connectors.executeRootHandler(C  onnectors.java:202)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at io.undertow.server.HttpServerExchange$1.run(HttpSe  rverExchange.java:792)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor.runWorker(  ThreadPoolExecutor.java:1149)
2019-05-28 17:17:38,166 ERROR [stderr] (default task-7)         at java.util.concurrent.ThreadPoolExecutor$Worker.run  (ThreadPoolExecutor.java:624)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7)         at java.lang.Thread.run(Thread.java:748)
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) Caused by: org.infinispan.commons.marshall.NotSerializableExc  eption: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,167 ERROR [stderr] (default task-7) java.lang.Exception: org.infinispan.commons.marshall.NotSeria  lizableException: ph.com.crm.common.admin.ListLovListVO
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.t  oHomePage(LoginProcessor.java:809)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.p  erformTask(LoginProcessor.java:327)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.LoginProcessor.e  xecute(LoginProcessor.java:146)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.crm.modules.security.ActionListener.e  xecute(ActionListener.java:41)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.performT  ask(CommonServlet.java:289)
2019-05-28 17:17:38,168 ERROR [stderr] (default task-7)         at ph.com.common.servlet.CommonServlet.doPost(C  ommonServlet.java:82)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:707)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at javax.servlet.http.HttpServlet.service(HttpServlet  .java:790)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletHandler.handle  Request(ServletHandler.java:85)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletSecur  ityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.ServletDispatchingHan  dler.handleRequest(ServletDispatchingHandler.java:36)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.SecurityCo  ntextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
2019-05-28 17:17:38,169 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.SSLInformati  onAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletAuthe  nticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractConfidential  ityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.ServletConfi  dentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AuthenticationMechan  ismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
2019-05-28 17:17:38,170 ERROR [stderr] (default task-7)         at io.undertow.servlet.handlers.security.CachedAuthen  ticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.NotificationReceiver  Handler.handleRequest(NotificationReceiverHandler.java:50)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.security.handlers.AbstractSecurityCont  extAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at io.undertow.server.handlers.PredicateHandler.handl  eRequest(PredicateHandler.java:43)
2019-05-28 17:17:38,171 ERROR [stderr] (default task-7)         at org.wildfly.extension.undertow.security.jacc.JACCC  ontextIdHandler.handleRequest(JACCContextIdHandler.java:61)

Any inputs would be appreciated thanks!


问:
Cannot upload media files in Django production to external folder
I have an issue on my Django production server.
When I try to upload images, they always go to the app/media/ folder.
However I want them to be uploaded to /mnt/data.
In the admin panel, when I upload the image, it is always uploading in the app/media/ folder.
I tried adjusting the Nginx config file and the settings.py, but I guess I am lost.

Here is my Nginx configuration:

```<code>     location /static/ {
            root /home/somthing/something/;
        }
        location /media/ {
        root /mnt/data/;
        }
</code>```

and the Settings.py:

```<code>STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

    # Media files

    MEDIA_URL = '/media/'

    MEDIA_ROOT = (
        os.path.join(BASE_DIR, 'media')
    )
</code>```

and in my model this is how I create the image:

```<code>    pictures = models.ImageField(
            upload_to='postings/',
            verbose_name=_('Posting_picture'),
            blank=True, null=True,
            validators=[validate_image],
        )
</code>```

I guess following this configuration, the uploaded picture is supposed to be in mnt/data/media/postings.

The media folder on the mnt/data/ is chmod 777, I did it when I lost hope in writing/reading the folder.

答:
I finally figured it out, Debendera was right for the path, but the Nginx configuration was wrong. I changed it to :

```<code>location /media/ {
    alias /mnt/data/;
    }
</code>```

and then it worked. If I am not mistaken, it was better to use alias instead of root.
This is my reference: Nginx -- static file serving confusion with root & alias

Body:
I have an issue on my Django production server.
When I try to upload images, they always go to the app/media/ folder.
However I want them to be uploaded to /mnt/data.
In the admin panel, when I upload the image, it is always uploading in the app/media/ folder.
I tried adjusting the Nginx config file and the settings.py, but I guess I am lost.

Here is my Nginx configuration:

     location /static/ {
            root /home/somthing/something/;
        }
        location /media/ {
        root /mnt/data/;
        }

and the Settings.py:

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

    # Media files

    MEDIA_URL = '/media/'

    MEDIA_ROOT = (
        os.path.join(BASE_DIR, 'media')
    )

and in my model this is how I create the image:

    pictures = models.ImageField(
            upload_to='postings/',
            verbose_name=_('Posting_picture'),
            blank=True, null=True,
            validators=[validate_image],
        )

I guess following this configuration, the uploaded picture is supposed to be in mnt/data/media/postings.

The media folder on the mnt/data/ is chmod 777, I did it when I lost hope in writing/reading the folder.

Body:
I finally figured it out, Debendera was right for the path, but the Nginx configuration was wrong. I changed it to :

location /media/ {
    alias /mnt/data/;
    }

and then it worked. If I am not mistaken, it was better to use alias instead of root.
This is my reference: Nginx -- static file serving confusion with root & alias


问:
How to check whether tasks in io_service are completed?
I have a question about boost::io_service.

I have a set of tasks that I can run concurrently. After running all of them, I need to run another set of tasks concurrently. However first set has to be completed before starting to run the second set. This means I need to make sure that all the jobs submitted to io_service is completed before starting to schedule to second set.

I can implement it by keeping some kind of counter and add a busy loop but it does not look very efficient. So, I wanted to checked whether someone has a better idea or not. Following is a dummy code that I was using to experiment.

Thank you in advance!

 #include <cstdio>
 #include <iostream>
 #include <unistd.h>
 #include <boost/asio/io_service.hpp>
 #include <boost/bind.hpp>
 #include <boost/thread/thread.hpp>

 const size_t numTasks = 100000;

 void print_counter(const size_t id)
 {
   if (id + 1 == numTasks) {
     printf("sleeping for %ld\n", id);
     sleep(15);
   }
   printf("%ld\n", id);
 }

 int main(int argc, char** argv)
 {
   using namespace std;
   using namespace boost;

   asio::io_service io_service;
   asio::io_service::work work(io_service);

   const size_t numWorker = 4;
   boost::thread_group workers;
   for(size_t i = 0; i < numWorker; ++i) {
     workers.create_thread(boost::bind(&asio::io_service::run, &io_service));
   }

   for(size_t i = 0; i < numTasks; ++i) {
     io_service.post(boost::bind(print_counter, i));
   }

   // TODO: wait until all the tasks are done above

   for(size_t i = 0; i < numTasks; ++i) {
     io_service.post(boost::bind(print_counter, i));
   }

   // TODO: wait until all the tasks are done above

   // ...

   // Finally stop the service
   io_service.stop();
   workers.join_all();
   return 0;
 }
```

答:
From the io_service::run documentation:

The run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_context has been stopped.

Also, from the io_context::work constructor documentation:

The constructor is used to inform the io_context that some work has begun. This ensures that the io_context object's run() function will not exit while the work is underway.

[Emphasis mine]

In short, if the run function returns and stopped returns false, then all work has been finished.


问:
How to optimize code - it works, but I know I'm missing much learning
The exercise I'm working on asks "Write a method, coprime?(num_1, num_2), that accepts two numbers as args. The method should return true if the only common divisor between the two numbers is 1."

I've written a method to complete the task, first by finding all the factors then sorting them and looking for duplicates. But I'm looking for suggestions on areas I should consider to optimize it.

The code works, but it is just not clean.

def factors(num)
 return (1..num).select { |n| num % n == 0}
end

def coprime?(num_1, num_2)
  num_1_factors = factors(num_1)
  num_2_factors = factors(num_2)
  all_factors = num_1_factors + num_2_factors
  new = all_factors.sort
  dups = 0
  new.each_index do |i|
    dups += 1 if new[i] == new[i+1]
  end
  if dups > 1
    false
  else
    true
  end
end

p coprime?(25, 12)    # => true
p coprime?(7, 11)     # => true
p coprime?(30, 9)     # => false
p coprime?(6, 24)     # => false

```

答:
You don't need to compare all the factors, just the prime ones. Ruby does come with a Prime class</p>

```<code>require 'prime'

def prime_numbers(num_1, num_2)
  Prime.each([num_1, num_2].max / 2).map(&:itself)
end

def factors(num, prime_numbers)
  prime_numbers.select {|n| num % n == 0}
end

def coprime?(num_1, num_2)
 prime_numbers = prime_numbers(num_1, num_2)
 # & returns the intersection of 2 arrays (https://stackoverflow.com/a/5678143)
 (factors(num_1, prime_numbers) & factors(num_2, prime_numbers)).length == 0
end
</code>```

Body:
You don't need to compare all the factors, just the prime ones. Ruby does come with a Prime class

require 'prime'

def prime_numbers(num_1, num_2)
  Prime.each([num_1, num_2].max / 2).map(&:itself)
end

def factors(num, prime_numbers)
  prime_numbers.select {|n| num % n == 0}
end

def coprime?(num_1, num_2)
 prime_numbers = prime_numbers(num_1, num_2)
 # & returns the intersection of 2 arrays (https://stackoverflow.com/a/5678143)
 (factors(num_1, prime_numbers) & factors(num_2, prime_numbers)).length == 0
end


问:
How to change an objects properties by touching it on mobile (UNITY) (2D)
i'm really new to game dev and stack overflow so i'm sorry if I've missed something.

I've looked everywhere but can't find a solution to my question.

So, i'm making a 2D mobile game through unity. Objects (sprites) are falling down using a rigid body and i want the user to be able touch the objects that are falling down which will trigger an animation or color change and add a particle explosion.

The issue is i'm having trouble trying to figure out how to actually get the user to touch the sprite and trigger an event ( I have no idea how to code touch input on the object) i've watched youtube tutorials such as brackeys and a bunch of other videos and through the unity documentation but they don't explain exactly what i need and all make joysticks which is no help for me.

From the research i've done i've found quite a few people talk about raycasting, should i be looking more into that?

Thank you everyone for your help, you've no idea how much i appreciate this.

答: Add a script to those objects with the method OnMouseDown which works for both mouse and touch, then trigger whatever event you what. Before exporting to Android test it on your own PC. They also need a collider.</p>


问:
How can I convert a f64 to f32 and get the closest approximation and the next greater or smaller value?
Possible pseudocode for the operation could be:

fn f32_greater(x: f64) -> f32 {
    let mut y = x as f32; //I get closest
    while f64::from(y) < x {
        y = nextafter(y, f32::INFINITY);
    }
    y
}

fn f32_smaller(x: f64) -> f32 {
    let mut y = x as f32; //I get closest
    while f64::from(y) > x {
        y = nextafter(y, f32::NEG_INFINITY);
    }
    y
}
```

I can not find an equivalent to C11's nextafter function in the libc crate or in the methods on f64

For context, I have an R-tree index using f32. I want to search the region with coordinates provided as a f64, so I need the smallest possible region in f32 that includes the f64 value.

答:
This function was removed from the standard library. A solution could be to use the float_extras crate, but I don't really like the way of this crate so here my solution:

mod float {
    use libc::{c_double, c_float};
    use std::{f32, f64};

    #[link_name = "m"]
    extern "C" {
        pub fn nextafter(x: c_double, y: c_double) -> c_double;
        pub fn nextafterf(x: c_float, y: c_float) -> c_float;
    // long double nextafterl(long double x, long double y);

    // double nexttoward(double x, long double y);
    // float nexttowardf(float x, long double y);
    // long double nexttowardl(long double x, long double y);
    }

    pub trait NextAfter {
        fn next_after(self, y: Self) -> Self;
    }

    impl NextAfter for f32 {
        fn next_after(self, y: Self) -> Self {
            unsafe { nextafterf(self, y) }
        }
    }

    impl NextAfter for f64 {
        fn next_after(self, y: Self) -> Self {
            unsafe { nextafter(self, y) }
        }
    }

    pub trait Succ {
        fn succ(self) -> Self;
    }

    impl Succ for f32 {
        fn succ(self) -> Self {
            self.next_after(f32::INFINITY)
        }
    }

    impl Succ for f64 {
        fn succ(self) -> Self {
            self.next_after(f64::INFINITY)
        }
    }

    pub trait Pred {
        fn pred(self) -> Self;
    }
    impl Pred for f32 {
        fn pred(self) -> Self {
            self.next_after(f32::NEG_INFINITY)
        }
    }

    impl Pred for f64 {
        fn pred(self) -> Self {
            self.next_after(f64::NEG_INFINITY)
        }
    }

}

use crate::float::{Pred, Succ};
use num_traits::cast::{FromPrimitive, ToPrimitive};

fn f32_greater<T>(x: T) -> Option<f32>
where
    T: ToPrimitive + FromPrimitive + std::cmp::PartialOrd,
{
    let mut y = x.to_f32()?;
    while T::from_f32(y)? < x {
        y = y.succ();
    }
    Some(y)
}

fn f32_smaller<T>(x: T) -> Option<f32>
where
    T: ToPrimitive + FromPrimitive + std::cmp::PartialOrd,
{
    let mut y = x.to_f32()?;
    while T::from_f32(y)? > x {
        y = y.pred();
    }
    Some(y)
}

fn main() {
    let a = 42.4242424242424242;
    println!(
        "{:.16?} < {:.16} < {:.16?}",
        f32_smaller(a),
        a,
        f32_greater(a)
    );
}
```

I don't understand why they don't include it in the num crate.

Body:
Possible pseudocode for the operation could be:

fn f32_greater(x: f64) -> f32 {
    let mut y = x as f32; //I get closest
    while f64::from(y) < x {
        y = nextafter(y, f32::INFINITY);
    }
    y
}

fn f32_smaller(x: f64) -> f32 {
    let mut y = x as f32; //I get closest
    while f64::from(y) > x {
        y = nextafter(y, f32::NEG_INFINITY);
    }
    y
}

I can not find an equivalent to C11's nextafter function in the libc crate or in the methods on f64

For context, I have an R-tree index using f32. I want to search the region with coordinates provided as a f64, so I need the smallest possible region in f32 that includes the f64 value.

Body:
This function was removed from the standard library. A solution could be to use the float_extras crate, but I don't really like the way of this crate so here my solution:

mod float {
    use libc::{c_double, c_float};
    use std::{f32, f64};

    #[link_name = "m"]
    extern "C" {
        pub fn nextafter(x: c_double, y: c_double) -> c_double;
        pub fn nextafterf(x: c_float, y: c_float) -> c_float;
    // long double nextafterl(long double x, long double y);

    // double nexttoward(double x, long double y);
    // float nexttowardf(float x, long double y);
    // long double nexttowardl(long double x, long double y);
    }

    pub trait NextAfter {
        fn next_after(self, y: Self) -> Self;
    }

    impl NextAfter for f32 {
        fn next_after(self, y: Self) -> Self {
            unsafe { nextafterf(self, y) }
        }
    }

    impl NextAfter for f64 {
        fn next_after(self, y: Self) -> Self {
            unsafe { nextafter(self, y) }
        }
    }

    pub trait Succ {
        fn succ(self) -> Self;
    }

    impl Succ for f32 {
        fn succ(self) -> Self {
            self.next_after(f32::INFINITY)
        }
    }

    impl Succ for f64 {
        fn succ(self) -> Self {
            self.next_after(f64::INFINITY)
        }
    }

    pub trait Pred {
        fn pred(self) -> Self;
    }
    impl Pred for f32 {
        fn pred(self) -> Self {
            self.next_after(f32::NEG_INFINITY)
        }
    }

    impl Pred for f64 {
        fn pred(self) -> Self {
            self.next_after(f64::NEG_INFINITY)
        }
    }

}

use crate::float::{Pred, Succ};
use num_traits::cast::{FromPrimitive, ToPrimitive};

fn f32_greater<T>(x: T) -> Option<f32>
where
    T: ToPrimitive + FromPrimitive + std::cmp::PartialOrd,
{
    let mut y = x.to_f32()?;
    while T::from_f32(y)? < x {
        y = y.succ();
    }
    Some(y)
}

fn f32_smaller<T>(x: T) -> Option<f32>
where
    T: ToPrimitive + FromPrimitive + std::cmp::PartialOrd,
{
    let mut y = x.to_f32()?;
    while T::from_f32(y)? > x {
        y = y.pred();
    }
    Some(y)
}

fn main() {
    let a = 42.4242424242424242;
    println!(
        "{:.16?} < {:.16} < {:.16?}",
        f32_smaller(a),
        a,
        f32_greater(a)
    );
}

I don't understand why they don't include it in the num crate.


问:
group and combine items using LINQ
```<code>public class Product
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Amount { get; set; }
}

public List<Product> Products = new List<Product>()
{
    new Product() { Code="A1", Name="Vacuum", Amount = "10" },
    new Product() { Code="A2", Name="Iron", Amount = "20" },
    new Product() { Code="A3", Name="Kettle", Amount = "13" },
    new Product() { Code="A2", Name="Microwave", Amount = "11" },
    new Product() { Code="A3", Name="Dryer", Amount = "3" }
};
</code>```

I need to select all products without duplicate code. Products with the same code should be combined into one line, in this case name and amount should be separated by commas. How to modify the following code to make it more elegant

```<code>    var list1 = new List<Product>();
    var gl = Products.GroupBy(x => x.Code).Where(x => x.Count() > 1);
    gl.ToList().ForEach(x => list1.AddRange(x));

    var list2 = Products.Where(x => !list1.Contains(x)).ToList(); // uniq values

    var list3 = gl.Select(x =>
    {
        var p = new Product() { Code = x.Key };
        p.Name = string.Join(",", x.ToList().Select(r => r.Name).Distinct());
        p.Amount = string.Join(",", x.ToList().Select(r => r.Amount).Distinct());
        return p;
    }).ToList();

    list2.AddRange(list3);
    list2.ForEach(x =>
    {
        Console.WriteLine($"{x.Code.PadRight(20)},{x.Name.PadRight(20)},{x.Amount.PadRight(20)}");
    });
</code>```

the result should be:

```<code>Code  Name              Amount
A1    Vacuum            10
A2    Iron, Microwave   20, 11
A3    Kettle, Dryer     13, 3
</code>```

答:
Use GroupBy on Code, then iterate over it to get the individual elements to combine using string.Join().

```<code>var results = products
    .GroupBy
    (
        p => p.Code
    )
    .Select
    (
        g => new
        {
            Code = g.Key,
            Name = string.Join
            (
                ",",
                g.Select( p => p.Name )
            ),
            Amount = string.Join
            (
                ",",
                g.Select( p => p.Amount.ToString() )
            )
        }
    );
</code>```

Output:

```<code>A1 Vacuum 10
A2 Iron,Microwave 20,11
A3 Kettle,Dryer 13,3
</code>```

Link to working example on DotNetFiddle

Title: group and combine items using LINQ

Body:
public class Product
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Amount { get; set; }
}

public List<Product> Products = new List<Product>()
{
    new Product() { Code="A1", Name="Vacuum", Amount = "10" },
    new Product() { Code="A2", Name="Iron", Amount = "20" },
    new Product() { Code="A3", Name="Kettle", Amount = "13" },
    new Product() { Code="A2", Name="Microwave", Amount = "11" },
    new Product() { Code="A3", Name="Dryer", Amount = "3" }
};

I need to select all products without duplicate code. Products with the same code should be combined into one line, in this case name and amount should be separated by commas. How to modify the following code to make it more elegant

    var list1 = new List<Product>();
    var gl = Products.GroupBy(x => x.Code).Where(x => x.Count() > 1);
    gl.ToList().ForEach(x => list1.AddRange(x));

    var list2 = Products.Where(x => !list1.Contains(x)).ToList(); // uniq values

    var list3 = gl.Select(x =>
    {
        var p = new Product() { Code = x.Key };
        p.Name = string.Join(",", x.ToList().Select(r => r.Name).Distinct());
        p.Amount = string.Join(",", x.ToList().Select(r => r.Amount).Distinct());
        return p;
    }).ToList();

    list2.AddRange(list3);
    list2.ForEach(x =>
    {
        Console.WriteLine($"{x.Code.PadRight(20)},{x.Name.PadRight(20)},{x.Amount.PadRight(20)}");
    });

the result should be:

Code  Name              Amount
A1    Vacuum            10
A2    Iron, Microwave   20, 11
A3    Kettle, Dryer     13, 3

Body:
Use GroupBy on Code, then iterate over it to get the individual elements to combine using string.Join().

var results = products
    .GroupBy
    (
        p => p.Code
    )
    .Select
    (
        g => new
        {
            Code = g.Key,
            Name = string.Join
            (
                ",",
                g.Select( p => p.Name )
            ),
            Amount = string.Join
            (
                ",",
                g.Select( p => p.Amount.ToString() )
            )
        }
    );

Output:

A1 Vacuum 10
A2 Iron,Microwave 20,11
A3 Kettle,Dryer 13,3

Link to working example on DotNetFiddle


问:
Create multiple copies of an array in javascript
I want to create multiple copies of an array, copies would only be a maximum of 5. I've been trying to do it this way.

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = numbers;
}

console.log(numbersCopy);```

But I'm getting circular object reference. How can I solve this?

答:
This sounds like:  "I want a new array, which copies up to the first five elements of the old array".  The function for that is slice().

```<code>const oldArray = [0,1,2,3,4,5,6];
const newArray = oldArray.slice(0,5); // [0,1,2,3,4]
</code>```

You can use slice to create copies in theses ways:

oldArray.slice() = [0, 1, 2, 3, 4, 5] = make a copy, same a =[...oldArray]

oldArray.slice(-2) = [5,6] = the last two items of the array.

oldArray.slice(0,5) = [0, 1, 2, 3, 4] = the first five items

oldArray.slice(5) = take the rest after the first five = [5,6]

oldArray.slice(2,3) = take items 2 and 3 = [2,3]

Keep on hacking a JavaScript!

Body:
I want to create multiple copies of an array, copies would only be a maximum of 5. I've been trying to do it this way.

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = numbers;
}

console.log(numbersCopy);

But I'm getting circular object reference. How can I solve this?

Body:
This sounds like:  "I want a new array, which copies up to the first five elements of the old array".  The function for that is slice().

const oldArray = [0,1,2,3,4,5,6];
const newArray = oldArray.slice(0,5); // [0,1,2,3,4]

You can use slice to create copies in theses ways:

oldArray.slice() = [0, 1, 2, 3, 4, 5] = make a copy, same a =[...oldArray]

oldArray.slice(-2) = [5,6] = the last two items of the array.

oldArray.slice(0,5) = [0, 1, 2, 3, 4] = the first five items

oldArray.slice(5) = take the rest after the first five = [5,6]

oldArray.slice(2,3) = take items 2 and 3 = [2,3]

Keep on hacking a JavaScript!


问:
jQuery .keyup() function
I'm not receiving any output from this code. What could be the error.

terminal.html

```<code><html>
<head>
<link href="/css/webterminal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.5.2.js"/>
<script type="text/javascript">
function shell_execute(str) {
  $.ajax({
    url: 'exec.php',
    dataType: 'text',
    data: {
      q: str
    },
    success: function (response) {
      $('#txtOut').append(response);

  });
}
</script>
</head
<body">
    <div class="container">

    <h2>UNIX Web Based Terminal 1.0</h2>
        <br />
    <p><b>output</b></p>
<form>
<span id="User"></span>< <input type="text" id="txtcmd" onkeyup="shell_execute(this.value)" class="textbox" size="20" />
</form>
<div class="output">
<p><span id="txtOut"></span></p>

    </div>
</div>
</body>
</html>
</code>```

exec.php

```<code><?php

$q=$_GET["q"];
$output=shell_exec($q);
echo "```$output```";
?>
</code>```

答:
Not specifically your issue I believe but I would take the
onkeyup="shell_execute(this.value)"  out of the markup and put in the script part a jQuery event handler:

```<code>$("#txtcmd").keyup(function(){
  shell_execute($(this).val());
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery .keyup() function

Body:
I'm not receiving any output from this code. What could be the error.

terminal.html

<link href="/css/webterminal.css" rel="stylesheet" type="text/css" />

</head

UNIX Web Based Terminal 1.0

output

<form>
< <input type="text" id="txtcmd" onkeyup="shell_execute(this.value)" class="textbox" size="20" />
</form>

exec.php

<?php

$q=$_GET["q"];
$output=shell_exec($q);
echo "
$output
";
?>

Body:
Not specifically your issue I believe but I would take the
onkeyup="shell_execute(this.value)"  out of the markup and put in the script part a jQuery event handler:

$("#txtcmd").keyup(function(){
  shell_execute($(this).val());
});


问:
How to close the desktop application running in background when called from UWP app
I am working on UWP app where in I have added Fulltrust permissions to my app in order to get access to the desktop application using APpServiceConncetion. But whenever I call FullTrustProcessLauncher it creates a new instance of my desktop application under my UWP app in task manager and it looks like it consumes CPU memory for each desktop app.
How do I close/keep only one  instance of desktop app when I call it from UWP?

Also How can I kill desktop application from task manager/ background when I no more require this code using c# in UWP

答:
You are in full control of the lifetime of your desktop application process, assuming you own the code. So your process can shut itself down whenever it is no longer needed. A common good practice is to shutdown when the appservice connection gets closed (i.e. the UWP app goes away and the ServiceClosed event fires).

There is some details on this in this post (under "Handling Process Exit Scenarios - Scenario 2"):
https://stefanwick.com/2018/04/16/uwp-with-desktop-extension-part-3/


问:
colorbalance in an image using c++ and opencv
I'm trying to score the colorbalance of an image using c++ and opencv.

To do this the easiest way is to count the number of pixels in each color and then see if one of the colors is more prevalent.

I figured I should probably used calcHist and with the split function I can split a image in R, G, and B histograms. However I am unsure about what to do next. I could probably walk through all the bins and just see how many pixels are in there but this seems like a lot of work (I currently use 256 bins).

Is there a faster way to count the pixels in a color range? Also I am not sure how it would work if white or black are the more prevalant colors?

答:
Automatic color balance algorithm is described in this link http://web.stanford.edu/~sujason/ColorBalancing/simplestcb.html

For C++ Code you can refer to this link : https://www.morethantechnical.com/2015/01/14/simplest-color-balance-with-opencv-wcode/

```<code>/// perform the Simplest Color Balancing algorithm
void SimplestCB(Mat& in, Mat& out, float percent) {
    assert(in.channels() == 3);
    assert(percent > 0 && percent < 100);

    float half_percent = percent / 200.0f;

    vector<Mat> tmpsplit; split(in,tmpsplit);
    for(int i=0;i<3;i++) {
        //find the low and high precentile values (based on the input percentile)
        Mat flat; tmpsplit[i].reshape(1,1).copyTo(flat);
        cv::sort(flat,flat,CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
        int lowval = flat.at<uchar>(cvFloor(((float)flat.cols) * half_percent));
        int highval = flat.at<uchar>(cvCeil(((float)flat.cols) * (1.0 - half_percent)));
        cout << lowval << " " << highval << endl;

        //saturate below the low percentile and above the high percentile
        tmpsplit[i].setTo(lowval,tmpsplit[i] < lowval);
        tmpsplit[i].setTo(highval,tmpsplit[i] > highval);

        //scale the channel
        normalize(tmpsplit[i],tmpsplit[i],0,255,NORM_MINMAX);
    }
    merge(tmpsplit,out);
}

// Usage example
void main() {
    Mat tmp,im = imread("lily.png");

    SimplestCB(im,tmp,1);

    imshow("orig",im);
    imshow("balanced",tmp);
    waitKey(0);
    return;
}
</code>```

Body:
Automatic color balance algorithm is described in this link http://web.stanford.edu/~sujason/ColorBalancing/simplestcb.html

For C++ Code you can refer to this link : https://www.morethantechnical.com/2015/01/14/simplest-color-balance-with-opencv-wcode/

/// perform the Simplest Color Balancing algorithm
void SimplestCB(Mat& in, Mat& out, float percent) {
    assert(in.channels() == 3);
    assert(percent > 0 && percent < 100);

    float half_percent = percent / 200.0f;

    vector<Mat> tmpsplit; split(in,tmpsplit);
    for(int i=0;i<3;i++) {
        //find the low and high precentile values (based on the input percentile)
        Mat flat; tmpsplit[i].reshape(1,1).copyTo(flat);
        cv::sort(flat,flat,CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
        int lowval = flat.at<uchar>(cvFloor(((float)flat.cols) * half_percent));
        int highval = flat.at<uchar>(cvCeil(((float)flat.cols) * (1.0 - half_percent)));
        cout << lowval << " " << highval << endl;

        //saturate below the low percentile and above the high percentile
        tmpsplit[i].setTo(lowval,tmpsplit[i] < lowval);
        tmpsplit[i].setTo(highval,tmpsplit[i] > highval);

        //scale the channel
        normalize(tmpsplit[i],tmpsplit[i],0,255,NORM_MINMAX);
    }
    merge(tmpsplit,out);
}

// Usage example
void main() {
    Mat tmp,im = imread("lily.png");

    SimplestCB(im,tmp,1);

    imshow("orig",im);
    imshow("balanced",tmp);
    waitKey(0);
    return;
}


问:
Distinguish types of on-disk models
Tensorflow has several types of model formats:

TensorFlow SavedModel 2. Frozen Model 3. Session Bundle 4. Tensorflow Hub module

How can you distinguish between them on-disk? (to later use with tensorflowjs-converter)

And how is each model created?

答:
Yup, there are a LOT of different model types, and they all have good reasons.  I'm not going to claim that I have perfect clarity of each, but here's what I know (I think I know).

The .pb file:  PB stands for protobuff or Protocol Buffer.  This is the model structure, generally without the trained weights and is stored in a binary format.

The .pbtxt file: Nonbinary of the pb file for human reading.

Protobuff files that aren't frozen will need a checkpoint .ckpt file, too.  The Checkpoint file is the missing set of weights that the pb needs.

The .h5 file:  The model + weights from a Keras save

The .tflite file would be a TensorflowLite model

Frozen Model: A frozen model combines the pb with the weights file, so you don't have to manage two of them.  Usually, this means adding the word frozen to the filename.  I'm sure this can be inferred when loading the file, but on disk they are a bit more on the honor system and no ckpt file.  This strips out extraneous graph info; it's basically like the "Production Ready" version of the model.

Session Bundle:  Are a directory.  They are nolonger used, and rare.

Tensorflow Hub Module: These are pre-existing popular models that are very likely already exported to TFJS and don't require you to manually convert them.  I assume they are supported for Google's benefit, more so than ours.  But it's nice to know if you use hub, you can always convert it.

A multi-exported grouping of files looks like this image.   From here, you can see quite a few that you could turn into TFJS.

Title: Distinguish types of on-disk models


问:
Sprite Mask option doesn't appear
I want to create a Sprite Mask object. I follow the instructions on the unity docs:

To create a Sprite Mask select from the main menu GameObject > 2D Object > Sprite Mask

But the only option that appears is "Sprite". I am using the latest version of Unity (5.6.3p2)

答:
Use an earlier version of Unity, 5.6 is quite old.
Here is the link https://unity3d.com/get-unity/download/archive</p>

Title: Sprite Mask option doesn't appear


问:
How to add new item to hyperlink menu in Outlook 2007 with VBA?
I need to add new item to the hyperlink menu in Outlook 2007 (now it contains items like Copy, Select Hyperlink, Open Hyperlink, Copy Hyperlink, Who is).

How can I do it?
(it should be a VBA macro added to Outlook)

答: looked at http://msdn.microsoft.com/en-us/library/bb206754(v=office.12).aspx ?</p>


答:
If the array is a primitive array (containing no objects or arrays), you can use .slice():

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = numbers.slice();
}

console.log(numbersCopy);```
</div>
</div>
</p>

<p>If it's not a primitive array, use <code>JSON.parse(JSON.stringify())</code>:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let numbers = [[1], {a: 2}, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = JSON.parse(JSON.stringify(numbers));
}

numbers[0] = 0;

console.log(numbersCopy);</code>```

Title: Create multiple copies of an array in javascript

Body:
If the array is a primitive array (containing no objects or arrays), you can use .slice():

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = numbers.slice();
}

console.log(numbersCopy);

If it's not a primitive array, use JSON.parse(JSON.stringify()):

let numbers = [[1], {a: 2}, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = JSON.parse(JSON.stringify(numbers));
}

numbers[0] = 0;

console.log(numbersCopy);


问:
why I have issues in importing views in the urls.py file?
from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:

```<code>employee
  migrations folder
....other files
   views.py
hrdjango
 __init__.py
 settings.py
 urls.py
</code>```

I feel like the urls can't access my views
this is the views.py

```<code>from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
</code>```

```<code>
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('emp', views.emp),
    path('show',views.show),
    path('edit/<int:id>', views.edit),
    path('update/<int:id>', views.update),
    path('delete/<int:id>', views.destroy),
]
</code>```

urls.py

I am having unresolved import 'employee'message

答:
I think the better solution would be to use separate urls.py file for separate apps and then include them to your root urls.

create a urls.py in your app.

in your root urls.py

from django.urls import path,include

urlpatterns = [
   ...,
   ...,
   path('employee/', include('employee.urls')),
]

```

Body:
from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:

employee
  migrations folder
....other files
   views.py
hrdjango
 __init__.py
 settings.py
 urls.py

I feel like the urls can't access my views
this is the views.py

from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")

from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('emp', views.emp),
    path('show',views.show),
    path('edit/<int:id>', views.edit),
    path('update/<int:id>', views.update),
    path('delete/<int:id>', views.destroy),
]

urls.py

I am having unresolved import 'employee'message


问:
Hiding input spinner using styled-component
There are lot of solutions out there to hide the input spinner using css. One of them being:

```<code>input::-webkit-inner-spin-button, input::-webkit-outer-spin-button {
    -webkit-appearance: none !important;
    margin: 0 !important;
    -moz-appearance:textfield !important;
}
</code>```

I want to know how I can implement it in styled-component? Thanks

答:
Declare like this:

```<code>const Input = styled.input`
    ::-webkit-inner-spin-button{
        -webkit-appearance: none;
        margin: 0;
    }
    ::-webkit-outer-spin-button{
        -webkit-appearance: none;
        margin: 0;
    }
`;
</code>```

Use like this:

<Input type="number">

Body:
There are lot of solutions out there to hide the input spinner using css. One of them being:

input::-webkit-inner-spin-button, input::-webkit-outer-spin-button {
    -webkit-appearance: none !important;
    margin: 0 !important;
    -moz-appearance:textfield !important;
}

I want to know how I can implement it in styled-component? Thanks

Body:
Declare like this:

const Input = styled.input`
    ::-webkit-inner-spin-button{
        -webkit-appearance: none;
        margin: 0;
    }
    ::-webkit-outer-spin-button{
        -webkit-appearance: none;
        margin: 0;
    }
`;

Use like this:

<Input type="number">


问:
Java basics: a static function without a name, or return type
```<code>public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...
</code>```

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?

答: That's a Static Initialization Block which is run once when the class is loaded. It can be used to initialize static member variables.</p>

Body:
public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?


问:
How can i have more than one buttons on action with search view?
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

</code>```

this is xml of search view menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>
</code>```

this is xml of dropdown menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>
</code>```

答:
First try to run your shell/console of python like administrator to execute the script:
This code should work well:

```<code>import cv2 #to take photos or pre-process it with some computer vision technique
import os #to save images at any path i.g E:/myfolder/images/
import argparse #to receive parameters in the console
#Open the camera:
cam = cv2.VideoCapture(0)

ap = argparse.ArgumentParser()
ap.add_argument("-c", "--quantity", required=True, help="Set the quantity of images that you want to take p. ej. 350")
args = vars(ap.parse_args())

#set path where we are going to save the image.
outDirectory = "E:/alxor/"

def takePhoto(number):
    if cam.isOpened():
        print("Camera opened successfully!")
        #Get one image:
        ret, frame = cam.read()
        name = "image_"+str(number)+".jpg"
        print(name)
        cv2.imwrite(os.path.join(outDirectory, name), frame)
    else:
        print("[INFO] Can not open the camera :(")
c = int(args["quantity"])
j = 1
while j <= c: #introduciendo 's' salimos del bucle

    print ("[INFO] WRITE 's' TO EXIT: ")
    print ("[INFO] WRITE 'c' TO TAKE A PHOTO ")
    user_input = input() #leer entrada
    if user_input is 'c':

        takePhoto(j)
        print("[INFO] IMAGE #"+str(j)+" SAVED...")

    if user_input is 's':
        break
        print("[INFO] THE PROGRAM HAS FINISHED..")
    j+=1

#Turn off the camera..
cam.release()
print("[INFO] THE PROGRAM HAS FINISHED..")
</code>```

update 1. Using os library to save the image in the desir path.
update 2. option to take n images
I left this code also in github:
code

Body:
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

this is xml of search view menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>

this is xml of dropdown menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>

Body:
First try to run your shell/console of python like administrator to execute the script:
This code should work well:

import cv2 #to take photos or pre-process it with some computer vision technique
import os #to save images at any path i.g E:/myfolder/images/
import argparse #to receive parameters in the console
#Open the camera:
cam = cv2.VideoCapture(0)

ap = argparse.ArgumentParser()
ap.add_argument("-c", "--quantity", required=True, help="Set the quantity of images that you want to take p. ej. 350")
args = vars(ap.parse_args())

#set path where we are going to save the image.
outDirectory = "E:/alxor/"

def takePhoto(number):
    if cam.isOpened():
        print("Camera opened successfully!")
        #Get one image:
        ret, frame = cam.read()
        name = "image_"+str(number)+".jpg"
        print(name)
        cv2.imwrite(os.path.join(outDirectory, name), frame)
    else:
        print("[INFO] Can not open the camera :(")
c = int(args["quantity"])
j = 1
while j <= c: #introduciendo 's' salimos del bucle

    print ("[INFO] WRITE 's' TO EXIT: ")
    print ("[INFO] WRITE 'c' TO TAKE A PHOTO ")
    user_input = input() #leer entrada
    if user_input is 'c':

        takePhoto(j)
        print("[INFO] IMAGE #"+str(j)+" SAVED...")

    if user_input is 's':
        break
        print("[INFO] THE PROGRAM HAS FINISHED..")
    j+=1

#Turn off the camera..
cam.release()
print("[INFO] THE PROGRAM HAS FINISHED..")

update 1. Using os library to save the image in the desir path.
update 2. option to take n images
I left this code also in github:
code


问:
VBA: Search for text in IE, open link, find line copy text, insert in Excel
I'm a complete newbie. Can you guys help me with the following?
1. I have a spreadsheet with productcodes.
2. I have an active Internet Explorer session (logged in) on an index page filled with links that among others contain the said productcodes.
3. For each code, I need it to find the code, open the link. Then find a line containing the string "udsalg" and copy the complete line i.e. "Udsalg 10994"
4. Insert the string next to the productcode.
5. Enter IE and "go back" to index page.
5. Rinse and repeat until all productcodes have been searched.

I have no skill regarding this and hoping for help. I understand basic programming (php etc). I hope somebody can help or point in the right direction. Best regards.

答:
You can try to refer code example below will give you most of the answers for your above questions. Note that this is not the exact code.

```<code>'start a new subroutine called SearchBot
Sub SearchBot()

    'dimension (declare or set aside memory for) our variables
    Dim objIE As InternetExplorer 'special object variable representing the IE browser
    Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
    Dim y As Integer 'integer variable we'll use as a counter
    Dim result as String 'string variable that will hold our result link

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = New InternetExplorer

    'make IE browser visible (False would allow IE to run in the background)
    objIE.Visible = True

    'navigate IE to this web page (a pretty neat search engine really)
    objIE.navigate "https://duckduckgo.com"

    'wait here a few seconds while the browser is busy
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    'in the search box put cell "A2" value, the word "in" and cell "C1" value
    objIE.document.getElementById("search_form_input_homepage").Value = _
      Sheets("Sheet1").Range("A2").Value & " in " & Sheets("Sheet1").Range("C1").Value

    'click the 'go' button
    objIE.document.getElementById("search_button_homepage").Click

    'wait again for the browser
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    'the first search result will go in row 2
    y = 2

    'for each <a> element in the collection of objects with class of 'result__a'...
    For Each aEle In objIE.document.getElementsByClassName("result__a")

        '...get the href link and print it to the sheet in col C, row y
        result = aEle
        Sheets("Sheet1").Range("C" & y).Value = result

        '...get the text within the element and print it to the sheet in col D
        Sheets("Sheet1").Range("D" & y).Value = aEle.innerText
        Debug.Print aEle.innerText

        'is it a yellowpages link?
        If InStr(result, "yellowpages.com") > 0 Or InStr(result, "yp.com") > 0 Then
            'make the result red
            Sheets("Sheet1").Range("C" & y).Interior.ColorIndex = 3
            'place a 1 to the left
            Sheets("Sheet1").Range("B" & y).Value = 1
        End If

        'increment our row counter, so the next result goes below
        y = y + 1

    'repeat times the # of ele's we have in the collection
    Next

    'add up the yellowpages listings
    Sheets("Sheet1").Range("B1").Value = _
      Application.WorksheetFunction.Sum(Sheets("Sheet1").Range("B2:B100"))

    'close the browser
    objIE.Quit

'exit our SearchBot subroutine
End Sub
</code>```

You can try to refer the code and try to understand it. Then you can try to modify it based on your requirement. If you have any further questions than you can try to post your sample code. We will try to check it and try to provide you suggestions for it.

Helpful References to learn about IE VBA Automation.

(1) Excel + VBA + IE = web automation

(2) IE (Internet Explorer) Automation using Excel VBA

(3) Automate Internet Explorer (IE) Using VBA

Body:
You can try to refer code example below will give you most of the answers for your above questions. Note that this is not the exact code.

'start a new subroutine called SearchBot
Sub SearchBot()

    'dimension (declare or set aside memory for) our variables
    Dim objIE As InternetExplorer 'special object variable representing the IE browser
    Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
    Dim y As Integer 'integer variable we'll use as a counter
    Dim result as String 'string variable that will hold our result link

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = New InternetExplorer

    'make IE browser visible (False would allow IE to run in the background)
    objIE.Visible = True

    'navigate IE to this web page (a pretty neat search engine really)
    objIE.navigate "https://duckduckgo.com"

    'wait here a few seconds while the browser is busy
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    'in the search box put cell "A2" value, the word "in" and cell "C1" value
    objIE.document.getElementById("search_form_input_homepage").Value = _
      Sheets("Sheet1").Range("A2").Value & " in " & Sheets("Sheet1").Range("C1").Value

    'click the 'go' button
    objIE.document.getElementById("search_button_homepage").Click

    'wait again for the browser
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    'the first search result will go in row 2
    y = 2

    'for each <a> element in the collection of objects with class of 'result__a'...
    For Each aEle In objIE.document.getElementsByClassName("result__a")

        '...get the href link and print it to the sheet in col C, row y
        result = aEle
        Sheets("Sheet1").Range("C" & y).Value = result

        '...get the text within the element and print it to the sheet in col D
        Sheets("Sheet1").Range("D" & y).Value = aEle.innerText
        Debug.Print aEle.innerText

        'is it a yellowpages link?
        If InStr(result, "yellowpages.com") > 0 Or InStr(result, "yp.com") > 0 Then
            'make the result red
            Sheets("Sheet1").Range("C" & y).Interior.ColorIndex = 3
            'place a 1 to the left
            Sheets("Sheet1").Range("B" & y).Value = 1
        End If

        'increment our row counter, so the next result goes below
        y = y + 1

    'repeat times the # of ele's we have in the collection
    Next

    'add up the yellowpages listings
    Sheets("Sheet1").Range("B1").Value = _
      Application.WorksheetFunction.Sum(Sheets("Sheet1").Range("B2:B100"))

    'close the browser
    objIE.Quit

'exit our SearchBot subroutine
End Sub

You can try to refer the code and try to understand it. Then you can try to modify it based on your requirement. If you have any further questions than you can try to post your sample code. We will try to check it and try to provide you suggestions for it.

Helpful References to learn about IE VBA Automation.

(1) Excel + VBA + IE = web automation

(2) IE (Internet Explorer) Automation using Excel VBA

(3) Automate Internet Explorer (IE) Using VBA


问:
Will it be possible to update jhipster entity without overwriting custom code
According to the jhipster web site once we decide to update entity then the custom code will be overwriting.
Please suggest a way to update entity preserving the existing custom code.
https://www.jhipster.tech/creating-an-entity/</p>

答:
You could always extend the generated entity (but not the endoints as it is not possible)

EDIT: endopits can be extended.