问:
Cybersource org.apache.cxf.binding.soap.SoapFault: Security processing failed USING CXF
```<code>    package com.cybersource.schemas.transaction_data.transactionprocessor;

    import java.io.IOException;
    import java.math.BigInteger;
    import java.net.MalformedURLException;
    import java.net.URL;
    imp ort java.rmi.RemoteException;
    import java.util.HashMap;
    import java.util.Map;

    import org.apache.cxf.version.Version;

    import com.cybersource.schemas.transaction_data_1.BillTo;
    import com.cybersource.schemas.transaction_data_1.CCAuthService;
    import com.cybersource.schemas.transaction_data_1.Card;
    import com.cybersource.schemas.transaction_data_1.Item;
    import com.cybersource.schemas.transaction_data_1.PurchaseTotals;
    import com.cybersource.schemas.transaction_data_1.ReplyMessage;
    import com.cybersource.schemas.transaction_data_1.RequestMessage;

    import org.apache.cxf.endpoint.Client;
    import org.apache.cxf.endpoint.Endpoint;
    import org.apache.cxf.frontend.ClientProxy;
    import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
    import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
    import org.apache.ws.security.WSConstants;
    import org.apache.ws.security.WSPasswordCallback;
    //import org.apache.wss4j.common.ext.WSPasswordCallback;
    import org.apache.ws.security.handler.WSHandlerConstants;

    import javax.security.auth.callback.Callback;
    import javax.security.auth.callback.CallbackHandler;
    import javax.security.auth.callback.UnsupportedCallbackException;
    public class CybersourceClientExample {

        // Replace the MERCHANT_ID and MERCHANT_KEY with the appropriate --donevalues.

        private static final String MERCHANT_ID = "MERCHANT_ID ";
        private static final String MERCHANT_KEY = "MERCHANT_KEY ";

        private static final String SERVER_URL = "https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.142.wsdl";

        private static final String CLIENT_LIB_VERSION = Version.getCompleteVersionString() + "/1.5.10"; // CXF Version / WSS4J Version
        private static final String CLIENT_LIBRARY = "Java CXF WSS4J";
        private static final String CLIENT_ENV = System.getProperty("os.name") + "/" +
                                                System.getProperty("os.version") + "/" +
                                                System.getProperty("java.vendor") + "/" +
                                                System.getProperty("java.version");

        public static void main(String[] args) throws RemoteException, MalformedURLException {
            RequestMessage request = new RequestMessage();

            // To help Cybersource troubleshoot any problems that you may encounter,
            // include the following information about the client.
            addClientLibraryInfo(request);

            request.setMerchantID(MERCHANT_ID);

            // Internal Transaction Reference Code for the Merchant
            request.setMerchantReferenceCode("222222");

            // Here we are telling the client that we are going to run an AUTH.
            request.setCcAuthService(new CCAuthService());
            request.getCcAuthService().setRun("true");

            request.setBillTo(buildBillTo());
            request.setCard(buildCard());
            request.setPurchaseTotals(buildPurchaseTotals());

            request.getItem().add(buildItem("0", "12.34", "2"));
            request.getItem().add(buildItem("1", "56.78", "1"));

            ITransactionProcessor processor = new TransactionProcessor(new URL(SERVER_URL)).getPortXML();

            //  Add WS-Security Headers to the Request
            addSecurityValues(processor);

            ReplyMessage reply = processor.runTransaction(request);

            System.out.println("decision = " + reply.getDecision());
            System.out.println("reasonCode = " + reply.getReasonCode());
            System.out.println("requestID = " + reply.getRequestID());
            System.out.println("requestToken = " + reply.getRequestToken());
            System.out.println("ccAuthReply.reasonCode = " + reply.getCcAuthReply().getReasonCode());
        }

        private static void addClientLibraryInfo(RequestMessage request) {
            request.setClientLibrary(CLIENT_LIBRARY);
            request.setClientLibraryVersion(CLIENT_LIB_VERSION);
            request.setClientEnvironment(CLIENT_ENV);
        }

        private static Item buildItem(String id, String unitPrice, String quantity) {
            Item item = new Item();
            item.setId(new BigInteger(id));
            item.setUnitPrice(unitPrice);
            item.setQuantity(quantity);
            return item;
        }

        private static PurchaseTotals buildPurchaseTotals() {
            PurchaseTotals purchaseTotals = new PurchaseTotals();
            purchaseTotals.setCurrency("USD");
            purchaseTotals.setGrandTotalAmount("100");
            return purchaseTotals;
        }

        private static Card buildCard() {
            Card card = new Card();
            card.setAccountNumber("4111111111111111");
            card.setExpirationMonth(new BigInteger("12"));
            card.setExpirationYear(new BigInteger("2020"));
            return card;
        }

        private static BillTo buildBillTo() {
            BillTo billTo = new BillTo();
            billTo.setFirstName("John");
            billTo.setLastName("Doe");
            billTo.setStreet1("1295 Charleston Road");
            billTo.setCity("Mountain View");
            billTo.setState("CA");
            billTo.setPostalCode("94043");
            billTo.setCountry("US");
            billTo.setEmail("null@cybersource.com");
            billTo.setIpAddress("10.7.111.111");
            return billTo;
        }

        private static void addSecurityValues(ITransactionProcessor processor) {
            Client client = ClientProxy.getClient(processor);
            Endpoint endpoint = client.getEndpoint();

            // We'll have to add the Username and Password properties to an OutInterceptor
            HashMap<String, Object> outHeaders = new HashMap<String, Object>();
            outHeaders.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
            outHeaders.put(WSHandlerConstants.USER, MERCHANT_ID);
            outHeaders.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
            outHeaders.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName());

            WSS4JOutInterceptor interceptor = new WSS4JOutInterceptor(outHeaders);
            endpoint.getOutInterceptors().add(interceptor);
        }

        public static class ClientPasswordHandler implements CallbackHandler {

            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if ((WSPasswordCallback)callback instanceof WSPasswordCallback) {
                    WSPasswordCallback passwordCallback = (WSPasswordCallback) callback;
                    passwordCallback.setPassword(MERCHANT_KEY);
                    }
                }
            }
        }
        }
</code>```

I am facing the following error. Please help.

Dec 04, 2017 8:15:00 AM org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
  INFO: Creating Service {urn:schemas-cybersource-com:transaction-data:TransactionProcessor}TransactionProcessor from WSDL: https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.142.wsdl
  Dec 04, 2017 8:15:03 AM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
  WARNING: Interceptor for {urn:schemas-cybersource-com:transaction-data:TransactionProcessor}TransactionProcessor#{urn:schemas-cybersource-com:transaction-data:TransactionProcessor}runTransaction has thrown exception, unwinding now
  org.apache.cxf.binding.soap.SoapFault: Security processing failed.
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:269)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:135)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:122)
      at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
      at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:518)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:427)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:328)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:281)
      at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
      at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
      at com.sun.proxy.$Proxy36.runTransaction(Unknown Source)
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample.main(CybersourceClientExample.java:77)
  Caused by: org.apache.wss4j.common.ext.WSSecurityException: WSHandler: password callback failed
  Original Exception was java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1172)
      at org.apache.wss4j.dom.handler.WSHandler.getPasswordCB(WSHandler.java:1130)
      at org.apache.wss4j.dom.action.UsernameTokenAction.execute(UsernameTokenAction.java:43)
      at org.apache.wss4j.dom.handler.WSHandler.doSenderAction(WSHandler.java:234)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor.access$100(WSS4JOutInterceptor.java:54)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:261)
      ... 11 more
  Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample$ClientPasswordHandler.handle(CybersourceClientExample.java:152)
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1170)
      ... 16 more
  Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Security processing failed.
      at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
      at com.sun.proxy.$Proxy36.runTransaction(Unknown Source)
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample.main(CybersourceClientExample.java:77)
  Caused by: org.apache.wss4j.common.ext.WSSecurityException: WSHandler: password callback failed
  Original Exception was java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1172)
      at org.apache.wss4j.dom.handler.WSHandler.getPasswordCB(WSHandler.java:1130)
      at org.apache.wss4j.dom.action.UsernameTokenAction.execute(UsernameTokenAction.java:43)
      at org.apache.wss4j.dom.handler.WSHandler.doSenderAction(WSHandler.java:234)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor.access$100(WSS4JOutInterceptor.java:54)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:261)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:135)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:122)
      at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
      at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:518)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:427)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:328)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:281)
      at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
      at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
      ... 2 more
  Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample$ClientPasswordHandler.handle(CybersourceClientExample.java:152)
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1170)
      ... 16 more

答: "Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback at " - looks like you are mixing WSS4J versions incorrectly. Have you verified that all of the WSS4J jars on the classpath have the same version? Also have you checked that the WSS4J version is the correct one that should be used with the version of CXF you are using?</p>

Body:
    package com.cybersource.schemas.transaction_data.transactionprocessor;

    import java.io.IOException;
    import java.math.BigInteger;
    import java.net.MalformedURLException;
    import java.net.URL;
    imp ort java.rmi.RemoteException;
    import java.util.HashMap;
    import java.util.Map;

    import org.apache.cxf.version.Version;

    import com.cybersource.schemas.transaction_data_1.BillTo;
    import com.cybersource.schemas.transaction_data_1.CCAuthService;
    import com.cybersource.schemas.transaction_data_1.Card;
    import com.cybersource.schemas.transaction_data_1.Item;
    import com.cybersource.schemas.transaction_data_1.PurchaseTotals;
    import com.cybersource.schemas.transaction_data_1.ReplyMessage;
    import com.cybersource.schemas.transaction_data_1.RequestMessage;

    import org.apache.cxf.endpoint.Client;
    import org.apache.cxf.endpoint.Endpoint;
    import org.apache.cxf.frontend.ClientProxy;
    import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
    import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
    import org.apache.ws.security.WSConstants;
    import org.apache.ws.security.WSPasswordCallback;
    //import org.apache.wss4j.common.ext.WSPasswordCallback;
    import org.apache.ws.security.handler.WSHandlerConstants;

    import javax.security.auth.callback.Callback;
    import javax.security.auth.callback.CallbackHandler;
    import javax.security.auth.callback.UnsupportedCallbackException;
    public class CybersourceClientExample {

        // Replace the MERCHANT_ID and MERCHANT_KEY with the appropriate --donevalues.

        private static final String MERCHANT_ID = "MERCHANT_ID ";
        private static final String MERCHANT_KEY = "MERCHANT_KEY ";

        private static final String SERVER_URL = "https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.142.wsdl";

        private static final String CLIENT_LIB_VERSION = Version.getCompleteVersionString() + "/1.5.10"; // CXF Version / WSS4J Version
        private static final String CLIENT_LIBRARY = "Java CXF WSS4J";
        private static final String CLIENT_ENV = System.getProperty("os.name") + "/" +
                                                System.getProperty("os.version") + "/" +
                                                System.getProperty("java.vendor") + "/" +
                                                System.getProperty("java.version");

        public static void main(String[] args) throws RemoteException, MalformedURLException {
            RequestMessage request = new RequestMessage();

            // To help Cybersource troubleshoot any problems that you may encounter,
            // include the following information about the client.
            addClientLibraryInfo(request);

            request.setMerchantID(MERCHANT_ID);

            // Internal Transaction Reference Code for the Merchant
            request.setMerchantReferenceCode("222222");

            // Here we are telling the client that we are going to run an AUTH.
            request.setCcAuthService(new CCAuthService());
            request.getCcAuthService().setRun("true");

            request.setBillTo(buildBillTo());
            request.setCard(buildCard());
            request.setPurchaseTotals(buildPurchaseTotals());

            request.getItem().add(buildItem("0", "12.34", "2"));
            request.getItem().add(buildItem("1", "56.78", "1"));

            ITransactionProcessor processor = new TransactionProcessor(new URL(SERVER_URL)).getPortXML();

            //  Add WS-Security Headers to the Request
            addSecurityValues(processor);

            ReplyMessage reply = processor.runTransaction(request);

            System.out.println("decision = " + reply.getDecision());
            System.out.println("reasonCode = " + reply.getReasonCode());
            System.out.println("requestID = " + reply.getRequestID());
            System.out.println("requestToken = " + reply.getRequestToken());
            System.out.println("ccAuthReply.reasonCode = " + reply.getCcAuthReply().getReasonCode());
        }

        private static void addClientLibraryInfo(RequestMessage request) {
            request.setClientLibrary(CLIENT_LIBRARY);
            request.setClientLibraryVersion(CLIENT_LIB_VERSION);
            request.setClientEnvironment(CLIENT_ENV);
        }

        private static Item buildItem(String id, String unitPrice, String quantity) {
            Item item = new Item();
            item.setId(new BigInteger(id));
            item.setUnitPrice(unitPrice);
            item.setQuantity(quantity);
            return item;
        }

        private static PurchaseTotals buildPurchaseTotals() {
            PurchaseTotals purchaseTotals = new PurchaseTotals();
            purchaseTotals.setCurrency("USD");
            purchaseTotals.setGrandTotalAmount("100");
            return purchaseTotals;
        }

        private static Card buildCard() {
            Card card = new Card();
            card.setAccountNumber("4111111111111111");
            card.setExpirationMonth(new BigInteger("12"));
            card.setExpirationYear(new BigInteger("2020"));
            return card;
        }

        private static BillTo buildBillTo() {
            BillTo billTo = new BillTo();
            billTo.setFirstName("John");
            billTo.setLastName("Doe");
            billTo.setStreet1("1295 Charleston Road");
            billTo.setCity("Mountain View");
            billTo.setState("CA");
            billTo.setPostalCode("94043");
            billTo.setCountry("US");
            billTo.setEmail("null@cybersource.com");
            billTo.setIpAddress("10.7.111.111");
            return billTo;
        }

        private static void addSecurityValues(ITransactionProcessor processor) {
            Client client = ClientProxy.getClient(processor);
            Endpoint endpoint = client.getEndpoint();

            // We'll have to add the Username and Password properties to an OutInterceptor
            HashMap<String, Object> outHeaders = new HashMap<String, Object>();
            outHeaders.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
            outHeaders.put(WSHandlerConstants.USER, MERCHANT_ID);
            outHeaders.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
            outHeaders.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName());

            WSS4JOutInterceptor interceptor = new WSS4JOutInterceptor(outHeaders);
            endpoint.getOutInterceptors().add(interceptor);
        }

        public static class ClientPasswordHandler implements CallbackHandler {

            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if ((WSPasswordCallback)callback instanceof WSPasswordCallback) {
                    WSPasswordCallback passwordCallback = (WSPasswordCallback) callback;
                    passwordCallback.setPassword(MERCHANT_KEY);
                    }
                }
            }
        }
        }

I am facing the following error. Please help.

Dec 04, 2017 8:15:00 AM org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
  INFO: Creating Service {urn:schemas-cybersource-com:transaction-data:TransactionProcessor}TransactionProcessor from WSDL: https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.142.wsdl
  Dec 04, 2017 8:15:03 AM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
  WARNING: Interceptor for {urn:schemas-cybersource-com:transaction-data:TransactionProcessor}TransactionProcessor#{urn:schemas-cybersource-com:transaction-data:TransactionProcessor}runTransaction has thrown exception, unwinding now
  org.apache.cxf.binding.soap.SoapFault: Security processing failed.
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:269)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:135)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:122)
      at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
      at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:518)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:427)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:328)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:281)
      at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
      at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
      at com.sun.proxy.$Proxy36.runTransaction(Unknown Source)
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample.main(CybersourceClientExample.java:77)
  Caused by: org.apache.wss4j.common.ext.WSSecurityException: WSHandler: password callback failed
  Original Exception was java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1172)
      at org.apache.wss4j.dom.handler.WSHandler.getPasswordCB(WSHandler.java:1130)
      at org.apache.wss4j.dom.action.UsernameTokenAction.execute(UsernameTokenAction.java:43)
      at org.apache.wss4j.dom.handler.WSHandler.doSenderAction(WSHandler.java:234)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor.access$100(WSS4JOutInterceptor.java:54)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:261)
      ... 11 more
  Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample$ClientPasswordHandler.handle(CybersourceClientExample.java:152)
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1170)
      ... 16 more
  Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Security processing failed.
      at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
      at com.sun.proxy.$Proxy36.runTransaction(Unknown Source)
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample.main(CybersourceClientExample.java:77)
  Caused by: org.apache.wss4j.common.ext.WSSecurityException: WSHandler: password callback failed
  Original Exception was java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1172)
      at org.apache.wss4j.dom.handler.WSHandler.getPasswordCB(WSHandler.java:1130)
      at org.apache.wss4j.dom.action.UsernameTokenAction.execute(UsernameTokenAction.java:43)
      at org.apache.wss4j.dom.handler.WSHandler.doSenderAction(WSHandler.java:234)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor.access$100(WSS4JOutInterceptor.java:54)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:261)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:135)
      at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:122)
      at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
      at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:518)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:427)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:328)
      at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:281)
      at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
      at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
      ... 2 more
  Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
      at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample$ClientPasswordHandler.handle(CybersourceClientExample.java:152)
      at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1170)
      ... 16 more


来源: stackexchange

问:
how to show default selected option in select box
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

```<code>[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]
</code>```

and HTML code like this..

```<code><select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>
</code>```

Any response which is related to this will help me alot.
Thanks to you inAdvance

答:
You need to create a variable to store the value being selected. Then when you initialize the component, assign the default value to that variable. Inside your html you need to include [(ngModel)].

*.component.ts

```<code>public selectedValue: any; //not sure what the value type is

constructor() {
    this.selectedValue = "default value";
}
</code>```

*.component.html

```<code><select formControlName="controlFordropdwn" [(ngModel)]="selectedValue">
    <option value="" disabled  hidden>Select</option>
    <option *ngFor="let type of dropdown" [value]="type.value" [selected]='type.value == type.selected'>
        {{type.value}}
    </option>
</select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]

and HTML code like this..

<select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>

Any response which is related to this will help me alot.
Thanks to you inAdvance

Body:
You need to create a variable to store the value being selected. Then when you initialize the component, assign the default value to that variable. Inside your html you need to include [(ngModel)].

*.component.ts

public selectedValue: any; //not sure what the value type is

constructor() {
    this.selectedValue = "default value";
}

*.component.html

<select formControlName="controlFordropdwn" [(ngModel)]="selectedValue">
    <option value="" disabled  hidden>Select</option>
    <option *ngFor="let type of dropdown" [value]="type.value" [selected]='type.value == type.selected'>
        {{type.value}}
    </option>
</select>


问:
Django TemplateDoesNotExist
Ok so I have a project called tvlistings and an app called progguide.

In my tvlistings directory I have the following in these files

settings.py

```<code>TEMPLATE_DIRS = (
    '/home/paul/tvlistings/progguide/templates',
)
</code>```

urls.py

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^progguide/', include('progguide.urls')),
)
</code>```

In my progguide directory I have

urls.py

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('progguide.views',
    (r'^$', 'index'),
    (r'^(?P<prog_id>\d+)/$', 'programme'),
)
</code>```

views.py

```<code>from django.shortcuts import render_to_response
from progguide.models import *

def index(request):
    chan_prog_list = ChannelProgramme.objects.all().order_by('progdate','starttime')[:5]
    return render_to_response('progguide/index.html', {'chan_prog_list': chan_prog_list})
</code>```

And in /home/paul/tvlistings/progguide/templates I have

index.html

```<code>{% if chan_prog_list % }
    <ul>
    {% for prog in chan_prog_list %}
        <li>{{ prog.channelid.channelname}} {{ prog.programmeid.progtitle }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No programmes.</p>
{% endif %}
</code>```

If I try to load http://localhost:8000/progguide I get

TemplateDoesNotExist at /progguide/

progguide/index.html

Request Method:  GET Request URL:
   http://127.0.0.1:8000/progguide/
  Django Version:  1.2.4 Exception Type:
   TemplateDoesNotExist Exception Value:

progguide/index.html

Still very new to this, the above looks ok from what I understand. What am I missing?

答:
Are you missing the templates folder?
You can use:</p>

```<code>return render_to_response('progguide/templates/index.html', {'chan_prog_list': chan_prog_list})
</code>```

ContentLicense: CC BY-SA 2.5

Title: Django TemplateDoesNotExist

Body:
Ok so I have a project called tvlistings and an app called progguide.

In my tvlistings directory I have the following in these files

settings.py

TEMPLATE_DIRS = (
    '/home/paul/tvlistings/progguide/templates',
)

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^progguide/', include('progguide.urls')),
)

In my progguide directory I have

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('progguide.views',
    (r'^$', 'index'),
    (r'^(?P<prog_id>\d+)/$', 'programme'),
)

views.py

from django.shortcuts import render_to_response
from progguide.models import *

def index(request):
    chan_prog_list = ChannelProgramme.objects.all().order_by('progdate','starttime')[:5]
    return render_to_response('progguide/index.html', {'chan_prog_list': chan_prog_list})

And in /home/paul/tvlistings/progguide/templates I have

index.html

{% if chan_prog_list % }

    {% for prog in chan_prog_list %}

{{ prog.channelid.channelname}} {{ prog.programmeid.progtitle }}

    {% endfor %}

{% else %}

No programmes.

{% endif %}

If I try to load http://localhost:8000/progguide I get

TemplateDoesNotExist at /progguide/

progguide/index.html

Request Method:  GET Request URL:
   http://127.0.0.1:8000/progguide/
  Django Version:  1.2.4 Exception Type:
   TemplateDoesNotExist Exception Value:

progguide/index.html

Still very new to this, the above looks ok from what I understand. What am I missing?

Body:
Are you missing the templates folder?
You can use:

return render_to_response('progguide/templates/index.html', {'chan_prog_list': chan_prog_list})


问:
CCTV integration to my page in angular2
Can any one help me how to intergrate the cctv to my angular2 webapp. I have the ip and port as input based on that i need to show it in my page . Can anyone worked on it or any idea please help me on this. With any sample example. Mine is a angular-cli webapplication.</p>

答:
HTML code    </p>

```<code><button type="button" class="btn" [ngClass]="{'btn-info': item.status>0, 'btn-default': item.status==0}" (click)="openCCTV(url)">VIEW</button>
</code>```

<p>ts code </p>

```<code>public openCCTV(urlToOpen: string) {
    let url: string = '';
    if (!/^http[s]?:\/\//.test(urlToOpen)) {
       url += 'http://';
    }

    url += urlToOpen;
    window.open(url, '_blank');
  };
</code>```

Title: CCTV integration to my page in angular2

Body:
HTML code

<button type="button" class="btn" [ngClass]="{'btn-info': item.status>0, 'btn-default': item.status==0}" (click)="openCCTV(url)">VIEW</button>

ts code

public openCCTV(urlToOpen: string) {
    let url: string = '';
    if (!/^http[s]?:\/\//.test(urlToOpen)) {
       url += 'http://';
    }

    url += urlToOpen;
    window.open(url, '_blank');
  };


问:
$_GET doesn't work
I have a really odd problem with $_GET. I'm fairly new to the HTML/CSS/PHP/MySQL stack. I've not used $_GET before and I'm trying to write a page that is used by a link in an email that confirms the user's email. The link contains a single parameter which is a GUID that I cross-reference against a database entry. While developing this, I've had problems getting hold of the $_GET parameters, so I've cut the page down to a test page thus:

```<code><html>
    <head>
    </head>
    <body>
        Hullo.<br/>
        <?php
            echo $_GET['testparam'];
        ?>
        <br/>
        World.
        <br/>
    </body>
</html>
</code>```

I am then calling this with:

```<code>http://mywebsite/dev/test.html?testparam=2
</code>```

I get the following output:

Hullo.

World.

What is going on? I cannot make the test simpler. I'm using PHP 7.1 if that helps. Any advice very gratefully received.

答:
I'm not sure your page is interpretted as PHP by the server until you declare .html files to be interpretted as PHP (in apache or whatever).

Write <-?php echo "2"; ?> in your page to be sure.

REname your page test.php and it should work if it's your problem.

Title: $_GET doesn't work

Body:
I have a really odd problem with $_GET. I'm fairly new to the HTML/CSS/PHP/MySQL stack. I've not used $_GET before and I'm trying to write a page that is used by a link in an email that confirms the user's email. The link contains a single parameter which is a GUID that I cross-reference against a database entry. While developing this, I've had problems getting hold of the $_GET parameters, so I've cut the page down to a test page thus:

        Hullo.

        <?php
            echo $_GET['testparam'];
        ?>

        World.

I am then calling this with:

http://mywebsite/dev/test.html?testparam=2

I get the following output:

Hullo.

World.

What is going on? I cannot make the test simpler. I'm using PHP 7.1 if that helps. Any advice very gratefully received.


问:
3D Line Segment and Plane Intersection - Contd
After advice from krlzlx I have posted it as a new question.

From here:

3D Line Segment and Plane Intersection

I have a problem with this algorithm, I have implemented it like so:

```<code>template <class T>
class AnyCollision {
   public:
    std::pair<bool, T> operator()(Point3d &ray, Point3d &rayOrigin, Point3d &normal, Point3d &coord) const {

    // get d value
    float d = (normal.x * coord.x) + (normal.y * coord.y) + (normal.z * coord.z);

    if (((normal.x * ray.x) + (normal.y * ray.y) + (normal.z * ray.z)) == 0) {
        return std::make_pair(false, T());
    }

    // Compute the X value for the directed line ray intersecting the plane
    float a = (d - ((normal.x * rayOrigin.x) + (normal.y * rayOrigin.y) + (normal.z * rayOrigin.z)) / ((normal.x * ray.x) + (normal.y * ray.y) + (normal.z * ray.z)));

    // output contact point
    float rayMagnitude = (sqrt(pow(ray.x, 2) + pow(ray.y, 2) + pow(ray.z, 2)));
    Point3d rayNormalised((ray.x / rayMagnitude), (ray.y / rayMagnitude), (ray.z / rayMagnitude));
    Point3d contact((rayOrigin.x + (rayNormalised.x * a)), (rayOrigin.y + (rayNormalised.y * a)), (rayOrigin.z + (rayNormalised.z * a))); //Make sure the ray vector is normalized
    return std::make_pair(true, contact);

};
</code>```

Point3d is defined as:

```<code>class Point3d {
   public:
    double x;
    double y;
    double z;

    /**
     * constructor
     *
     * 0 all elements
     */
    Point3d() {
        x = 0.0;
        y = 0.0;
        z = 0.0;
    }
</code>```

I am forced to use this structure, because in the larger system my component runs in it is defined like this and it cannot be changed.

My code compiles fine, but testing I get incorrect values for the point. The ratio of x, y, z is correct but the magnitude is wrong.

For example if:

```<code>rayOrigin.x = 0;
rayOrigin.y = 0;
rayOrigin.z = 0;

ray.x = 3;
ray.y = -5;
ray.z = 12;

normal.x = -3;
normal.y = 12;
normal.z = 0;

coord.x = 7;
coord.y = -5;
coord.z = 10;
</code>```

I expect the point to be:

```<code>(0.63, 1.26, 1.89)
</code>```

However, it is:

```<code>(3.52, -5.87, 14.09)
</code>```

A magnitude of 5.09 too big.

And I also tested:

```<code>rayOrigin.x = 0;
rayOrigin.y = 0;
rayOrigin.z = 0;

ray.x = 2;
ray.y = 3;
ray.z = 3;

normal.x = 4;
normal.y = 1;
normal.z = 0;

p0.x = 2;
p0.y = 1;
p0.z = 5;
</code>```

I expect the point to be:

```<code>(1.64, 2.45, 2.45)
</code>```

However, it is:

```<code>(3.83761, 5.75642, 5.75642)
</code>```

A magnitude of 2.34 too big?

答:
Pseudocode (does not require vector normalization):

```<code> Diff = PlaneBaseCoordinate - RayOrigin
 d = Normal.dot.Diff
 e = Normal.dot.RayVector

if (e)
   IntersectionPoint = RayOrigin + RayVector * d / e
otherwise
  ray belongs to the plane or is parallel
</code>```

Quick check:

```<code>Ray (0,0,0)  (2,2,2)    //to catch possible scale issues
Plane (0,1,0) (0,3,0)   //plane y=1
Diff = (0,1,0)
d = 3
e = 6
IntersectionPoint = (0,0,0) + (2,2,2) * 3 / 6 = (1, 1, 1)
</code>```

Body:
After advice from krlzlx I have posted it as a new question.

From here:

3D Line Segment and Plane Intersection

I have a problem with this algorithm, I have implemented it like so:

template <class T>
class AnyCollision {
   public:
    std::pair<bool, T> operator()(Point3d &ray, Point3d &rayOrigin, Point3d &normal, Point3d &coord) const {

    // get d value
    float d = (normal.x * coord.x) + (normal.y * coord.y) + (normal.z * coord.z);

    if (((normal.x * ray.x) + (normal.y * ray.y) + (normal.z * ray.z)) == 0) {
        return std::make_pair(false, T());
    }

    // Compute the X value for the directed line ray intersecting the plane
    float a = (d - ((normal.x * rayOrigin.x) + (normal.y * rayOrigin.y) + (normal.z * rayOrigin.z)) / ((normal.x * ray.x) + (normal.y * ray.y) + (normal.z * ray.z)));

    // output contact point
    float rayMagnitude = (sqrt(pow(ray.x, 2) + pow(ray.y, 2) + pow(ray.z, 2)));
    Point3d rayNormalised((ray.x / rayMagnitude), (ray.y / rayMagnitude), (ray.z / rayMagnitude));
    Point3d contact((rayOrigin.x + (rayNormalised.x * a)), (rayOrigin.y + (rayNormalised.y * a)), (rayOrigin.z + (rayNormalised.z * a))); //Make sure the ray vector is normalized
    return std::make_pair(true, contact);

};

Point3d is defined as:

class Point3d {
   public:
    double x;
    double y;
    double z;

    /**
     * constructor
     *
     * 0 all elements
     */
    Point3d() {
        x = 0.0;
        y = 0.0;
        z = 0.0;
    }

I am forced to use this structure, because in the larger system my component runs in it is defined like this and it cannot be changed.

My code compiles fine, but testing I get incorrect values for the point. The ratio of x, y, z is correct but the magnitude is wrong.

For example if:

rayOrigin.x = 0;
rayOrigin.y = 0;
rayOrigin.z = 0;

ray.x = 3;
ray.y = -5;
ray.z = 12;

normal.x = -3;
normal.y = 12;
normal.z = 0;

coord.x = 7;
coord.y = -5;
coord.z = 10;

I expect the point to be:

(0.63, 1.26, 1.89)

However, it is:

(3.52, -5.87, 14.09)

A magnitude of 5.09 too big.

And I also tested:

rayOrigin.x = 0;
rayOrigin.y = 0;
rayOrigin.z = 0;

ray.x = 2;
ray.y = 3;
ray.z = 3;

normal.x = 4;
normal.y = 1;
normal.z = 0;

p0.x = 2;
p0.y = 1;
p0.z = 5;

I expect the point to be:

(1.64, 2.45, 2.45)

However, it is:

(3.83761, 5.75642, 5.75642)

A magnitude of 2.34 too big?

Body:
Pseudocode (does not require vector normalization):

 Diff = PlaneBaseCoordinate - RayOrigin
 d = Normal.dot.Diff
 e = Normal.dot.RayVector

if (e)
   IntersectionPoint = RayOrigin + RayVector * d / e
otherwise
  ray belongs to the plane or is parallel

Quick check:

Ray (0,0,0)  (2,2,2)    //to catch possible scale issues
Plane (0,1,0) (0,3,0)   //plane y=1
Diff = (0,1,0)
d = 3
e = 6
IntersectionPoint = (0,0,0) + (2,2,2) * 3 / 6 = (1, 1, 1)


问:
Implement Markov's algorithm using random letters till letters makeup one word in the string?
I am trying to use the Markov chain to display random letters till the letters make up one of the words found in the string. I think I’m on the right track, but instead of stopping when it reaches one word it just prints the whole string of random.

I believe there will be a check to see if characters match with the print out, but not sure…

What am I doing wrong here?

```<code>public class Main {

    public static void main(String[] args) {

        final int NUMBER_OF_CHARS = 100000;
        String[] words = { "at", "is", "he", "we", "up", "on" };

        for (int i = 0; i < NUMBER_OF_CHARS; i++) {
            char ch = main.getRandomLowerCaseLetter();
            if ((i + 1) % 40 == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char ch2) {
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomLowerCaseLetter() {
        return getRandomCharacter('a', 'z');
    }
}
</code>```

答:
There are probably better methods out there for doing this but here is something quick that solves your problem, as suggested by Keara you need to store each character as you go, then loop through and check if you have found something that you are looking for. As (in the example you gave anyway) the words you are looking for are a maximum of 2 characters long it makes it simple to reset the string every time you have found an invalid combination.

```<code>import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {

    final int NUMBER_OF_CHARS = 100000;
    String[] words = {"at", "is", "he", "we", "up", "on"};
    List<Character> characters = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_CHARS; i++) {
        char ch = getRandomLowerCaseLetter();
        characters.add(ch);

        if ((i + 1) % 40 == 0) {
            System.out.println(ch);
            if (contains(characters, words)) {
                System.exit(0);
            }
        } else {
            System.out.print(ch);
            if (contains(characters, words)) {
                System.exit(0);
            }
        }
    }
}

public static boolean contains(List<Character> characters, String[] words) {
    String st = "";
    int count = 0;
    for (Character c : characters) {
        st += c;
        count++;
        if (count == 2) {
            for (String s : words) {
                if (st.equals(s)) {
                    System.out.println(" Found: " + s);
                    return true;
                }
            }
            count = 0;
            st = "";
        }
    }
    return false;
}

public static char getRandomCharacter(char ch1, char ch2) {
    return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}

public static char getRandomLowerCaseLetter() {
    return getRandomCharacter('a', 'z');
}
}
</code>```

Kind Regards and happy programming!

Body:
I am trying to use the Markov chain to display random letters till the letters make up one of the words found in the string. I think I’m on the right track, but instead of stopping when it reaches one word it just prints the whole string of random.

I believe there will be a check to see if characters match with the print out, but not sure…

What am I doing wrong here?

public class Main {

    public static void main(String[] args) {

        final int NUMBER_OF_CHARS = 100000;
        String[] words = { "at", "is", "he", "we", "up", "on" };

        for (int i = 0; i < NUMBER_OF_CHARS; i++) {
            char ch = main.getRandomLowerCaseLetter();
            if ((i + 1) % 40 == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char ch2) {
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomLowerCaseLetter() {
        return getRandomCharacter('a', 'z');
    }
}

Body:
There are probably better methods out there for doing this but here is something quick that solves your problem, as suggested by Keara you need to store each character as you go, then loop through and check if you have found something that you are looking for. As (in the example you gave anyway) the words you are looking for are a maximum of 2 characters long it makes it simple to reset the string every time you have found an invalid combination.

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {

    final int NUMBER_OF_CHARS = 100000;
    String[] words = {"at", "is", "he", "we", "up", "on"};
    List<Character> characters = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_CHARS; i++) {
        char ch = getRandomLowerCaseLetter();
        characters.add(ch);

        if ((i + 1) % 40 == 0) {
            System.out.println(ch);
            if (contains(characters, words)) {
                System.exit(0);
            }
        } else {
            System.out.print(ch);
            if (contains(characters, words)) {
                System.exit(0);
            }
        }
    }
}

public static boolean contains(List<Character> characters, String[] words) {
    String st = "";
    int count = 0;
    for (Character c : characters) {
        st += c;
        count++;
        if (count == 2) {
            for (String s : words) {
                if (st.equals(s)) {
                    System.out.println(" Found: " + s);
                    return true;
                }
            }
            count = 0;
            st = "";
        }
    }
    return false;
}

public static char getRandomCharacter(char ch1, char ch2) {
    return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}

public static char getRandomLowerCaseLetter() {
    return getRandomCharacter('a', 'z');
}
}

Kind Regards and happy programming!


问:
MS ACCESS, VBA SQL Insert command semicolon issue
I am trying to sort out some VBA in Access today with very limited knowledge. I have constructed the code below for a simple insert into a table within the same access database.

I am getting the error
"Missing semicolon (;) at end of SQL statement."

However I have the semicolon in there. I can only assume I have made a rookie error with syntax somewhere but after spending far too long trying I am stumped, any pointers much appreciated!

```<code>Dim StrSQL As String
Dim InDate As Date
Dim VacNum As String
Dim Stage As String

InDate = Now()
VacNum = Me.Vacancy_No
Stage = Me.Current_Stage

StrSQL = "INSERT INTO Stage (Vacancy_ID,StageDate,Stage) VALUES ('" & VacNum & "','" & InDate & "','" & Stage & "' );"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
</code>```

答:
Your syntax is at risk for SQL injection, and that's probably why you're getting this message.

The likely cause of this error is that one of your field contains a single quote, making the SQL malfunction.

The proper solution to this is to parameterize:

```<code>Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "INSERT INTO Stage (Vacancy_ID,StageDate,Stage) VALUES (@Value1,@Value2,@Value3 );")
qdf.Parameters("@Value1") = VacNum
qdf.Parameters("@Value2") = InDate
qdf.Parameters("@Value3") = Stage
qdf.Execute
</code>```

Body:
I am trying to sort out some VBA in Access today with very limited knowledge. I have constructed the code below for a simple insert into a table within the same access database.

I am getting the error
"Missing semicolon (;) at end of SQL statement."

However I have the semicolon in there. I can only assume I have made a rookie error with syntax somewhere but after spending far too long trying I am stumped, any pointers much appreciated!

Dim StrSQL As String
Dim InDate As Date
Dim VacNum As String
Dim Stage As String

InDate = Now()
VacNum = Me.Vacancy_No
Stage = Me.Current_Stage

StrSQL = "INSERT INTO Stage (Vacancy_ID,StageDate,Stage) VALUES ('" & VacNum & "','" & InDate & "','" & Stage & "' );"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

Body:
Your syntax is at risk for SQL injection, and that's probably why you're getting this message.

The likely cause of this error is that one of your field contains a single quote, making the SQL malfunction.

The proper solution to this is to parameterize:

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "INSERT INTO Stage (Vacancy_ID,StageDate,Stage) VALUES (@Value1,@Value2,@Value3 );")
qdf.Parameters("@Value1") = VacNum
qdf.Parameters("@Value2") = InDate
qdf.Parameters("@Value3") = Stage
qdf.Execute


问:
Bootstrap dynamic input generation using jQuery "form-row" is not working
When i clicking Add Wings/Blocks button the dynamic fields will created with using jQuery, those are the BootStrap components.

I want arrange a 3 fields from (left to right) in a single row, I made code for that also, but "form-row" is not arranging the fields, normally it is working, but from the dynamic code only is not working, it is arranging the fields one below one.

Here is a sample image

Sample codes

 var wrapper         = $("#addingInp"); //Fields wrapper
    var add_button      = $("#addButton"); //Add button ID

    var x = 0; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed

            $(wrapper).append('
'
              +'
'
              +'Block'
              +'<input id="block'+x+'"  type="text" class="form-control block" placeholder="Enter Name" style="width:auto"/>'
              +'
'

              +'
'
              +'No of floors'
              +'<input id="floorstart'+x+'"  type="text" class="form-control floor" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
              +'<input id="floorend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
              +'
'

              +'
'
              +'No/Name of flats'
              +'<input id="flatstart'+x+'"  type="text"  class="form-control flatstart" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
              +'<input id="flatend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
              +'
'

               +' X '
              +'
 '); //add input box
            x++; //text box increment now x=1 after x++ x=2,so next code 2%2==0 is true
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="margin-left: 4px;" class="form-group col-md-12">
    <input type='button' class="btn-primary form-control" value='Add Wings/Blocks' id='addButton' style="width:auto" />
</div>

<div id="addingInp" class="form-row col-md-12">
</div></code>```

答:
you have missed the =  sign in your append() method

```<code> $(wrapper).append('<div class="form-row">'
                +'<div class="form-group col-md-3">'
                +'<label for="block'+x+'">Block</label>'
                +'<input id="block'+x+'"  type="text" class="form-control block" placeholder="Enter Name" style="width:auto"/>'
                +'</div>'

                +'<div class="form-group col-md-4">'
                +'<label for="floor'+x+'">No of floors</label>'
                +'<input id="floorstart'+x+'"  type="text" class="form-control floor" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
                +'<input id="floorend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
                +'</div>'

                +'<div class="form-group col-md-4">'
                +'<label for="flats'+x+'">No/Name of flats</label>'
                +'<input id="flatstart'+x+'"  type="text"  class="form-control flatstart" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
                +'<input id="flatend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
                +'</div>'

                    +'<a href="#" class="remove_field col-md-1"> X </a>'
                +'</div> ');
</code>```

Body:
When i clicking Add Wings/Blocks button the dynamic fields will created with using jQuery, those are the BootStrap components.

I want arrange a 3 fields from (left to right) in a single row, I made code for that also, but "form-row" is not arranging the fields, normally it is working, but from the dynamic code only is not working, it is arranging the fields one below one.

Here is a sample image

Sample codes

 var wrapper         = $("#addingInp"); //Fields wrapper
    var add_button      = $("#addButton"); //Add button ID

    var x = 0; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed

            $(wrapper).append('
'
              +'
'
              +'Block'
              +'<input id="block'+x+'"  type="text" class="form-control block" placeholder="Enter Name" style="width:auto"/>'
              +'
'

              +'
'
              +'No of floors'
              +'<input id="floorstart'+x+'"  type="text" class="form-control floor" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
              +'<input id="floorend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
              +'
'

              +'
'
              +'No/Name of flats'
              +'<input id="flatstart'+x+'"  type="text"  class="form-control flatstart" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
              +'<input id="flatend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
              +'
'

               +' X '
              +'
 '); //add input box
            x++; //text box increment now x=1 after x++ x=2,so next code 2%2==0 is true
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })

    <input type='button' class="btn-primary form-control" value='Add Wings/Blocks' id='addButton' style="width:auto" />

Body:
you have missed the =  sign in your append() method

 $(wrapper).append('<div class="form-row">'
                +'<div class="form-group col-md-3">'
                +'<label for="block'+x+'">Block</label>'
                +'<input id="block'+x+'"  type="text" class="form-control block" placeholder="Enter Name" style="width:auto"/>'
                +'</div>'

                +'<div class="form-group col-md-4">'
                +'<label for="floor'+x+'">No of floors</label>'
                +'<input id="floorstart'+x+'"  type="text" class="form-control floor" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
                +'<input id="floorend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
                +'</div>'

                +'<div class="form-group col-md-4">'
                +'<label for="flats'+x+'">No/Name of flats</label>'
                +'<input id="flatstart'+x+'"  type="text"  class="form-control flatstart" placeholder="Start (Ex : A or 1)" style="width:auto"/>'
                +'<input id="flatend'+x+'"  type="text"  class="form-control flatend" placeholder="End (Ex : Z or 100)" style="width:auto"/>'
                +'</div>'

                    +'<a href="#" class="remove_field col-md-1"> X </a>'
                +'</div> ');


问:
Text renders wrong in Chrome and Opera

Our webshop has a menu with rendering problems in Chrome and Opera, since a few weeks, I don't had any problems before.

As you can see in the screenshot the text is not rendered correctly.

When I hover the text items (witch have a :hover effect with a different color)  the text items are showing correct, also when the mouse leaves the text.

At some places also the title is not showing correct but they don't have a hover effect so I need to select the text and after deselecting it will be correct.

Does anyone have the same problems in Chrome or Opera and knows how to fix it?

I tried adding z-index to the items but that doesn't help.

Edit:

I don't add code first because I just hope somebody has the same problems thanks to a Chrome update and they know how to fix it.

Also the css is pretty big because it is a menu plugin with a lot of css rules.

As said there is also no change in the code happened in the last few weeks, and everything was fine.

答:
Different browsers may render fonts slightly differently. You can't change that.

Try using this:

```<code>@font-face {font-family: 'fontname';
src: url('../../includes/fonts/fontname.eot');
src: url('../../includes/fonts/fontname?#iefix') format('eot'),
url('../../includes/fonts/fontname.woff') format('woff'),
url('../../includes/fonts/fontname.ttf') format('truetype'),
url('../../includes/fonts/fontname.svg') format('svg');
font-weight: normal;
font-style: normal;}

@media screen and (-webkit-min-device-pixel-ratio:0) {@font-face {font-family: 'chunk-webfont';
src: url('../../includes/fontsfontname.svg') format('svg');
}}
</code>```

I know Arial is a web font But can generate the font face and try the same.

Title: Text renders wrong in Chrome and Opera

Body:
Different browsers may render fonts slightly differently. You can't change that.

Try using this:

@font-face {font-family: 'fontname';
src: url('../../includes/fonts/fontname.eot');
src: url('../../includes/fonts/fontname?#iefix') format('eot'),
url('../../includes/fonts/fontname.woff') format('woff'),
url('../../includes/fonts/fontname.ttf') format('truetype'),
url('../../includes/fonts/fontname.svg') format('svg');
font-weight: normal;
font-style: normal;}

@media screen and (-webkit-min-device-pixel-ratio:0) {@font-face {font-family: 'chunk-webfont';
src: url('../../includes/fontsfontname.svg') format('svg');
}}

I know Arial is a web font But can generate the font face and try the same.


问:
Unable to use webpack dynamic import because of static publicPath
I love the ability to dynamically import a chunk using the import command in webpack 3. Unfortunately it seems as if it can only be used if the resources are in a rather static directory configuration on the server.

In my environment the html pages generated dynamically in the backend (let's say http:/localhost/app). All other resources (js, css, images, etc.) are in a different directory (let's say http:/localhost/res) but additionally res is not static but can rather change dynamically in the backend.

As long as I do not use any dynamic imports everything works as expected but when trying to dynamically load any chunks this fails because webpack by default expects the chunks to be in http:/localhost/app and I cannot use publicPath because the url where the resources are is dynamic.

Is there any way to (runtime) configure webpack into loading the resources relative to the path where the current resource is located.
If for example the chunk page1.js located in http:/localhost/resA dynamically loads the chunk sub1.js he should look for it in http:/localhost/resA instead of http:/localhost/app.

generated html will be available at http:/localhost/app/page1:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script src="http:/localhost/resA/page1.bundle.js"></script>
    </body>
</html>
</code>```

file src/page1.js will be available as http:/localhost/resA/page1.bundle.js:

```<code>import(/* webpackChunkName: "sub1" */ './sub1').then(({MyClass}) => {/*...*/});
</code>```

file src/sub1 will be available as http:/localhost/resA/sub1.bundle.js:

```<code>export class MyClass {};
</code>```

file `webpack.config.js':

```<code>const path = require('path');
const webpack = require('webpack');

function config(env) {
    return {
        entry: {
            index: ['./src/page1.js']
        },
        output: {
            filename: '[name].bundle.js',
            chunkFilename: '[name].bundle.js',
            path: path.resolve(__dirname, 'dist'),
            publicPath: './'
        },
        module: {
            rules: [
                {
                    test: /\.js$/i,
                    include: /src/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader'
                    }
                }
            ]
        },
        devtool: 'source-map'
    };
}

module.exports = config;
</code>```

答: The solution is to use __webpack_public_path__ as described in https://webpack.js.org/guides/public-path.

Body:
I love the ability to dynamically import a chunk using the import command in webpack 3. Unfortunately it seems as if it can only be used if the resources are in a rather static directory configuration on the server.

In my environment the html pages generated dynamically in the backend (let's say http:/localhost/app). All other resources (js, css, images, etc.) are in a different directory (let's say http:/localhost/res) but additionally res is not static but can rather change dynamically in the backend.

As long as I do not use any dynamic imports everything works as expected but when trying to dynamically load any chunks this fails because webpack by default expects the chunks to be in http:/localhost/app and I cannot use publicPath because the url where the resources are is dynamic.

Is there any way to (runtime) configure webpack into loading the resources relative to the path where the current resource is located.
If for example the chunk page1.js located in http:/localhost/resA dynamically loads the chunk sub1.js he should look for it in http:/localhost/resA instead of http:/localhost/app.

generated html will be available at http:/localhost/app/page1:

<!DOCTYPE html>

        <meta charset="utf-8">

file src/page1.js will be available as http:/localhost/resA/page1.bundle.js:

import(/* webpackChunkName: "sub1" */ './sub1').then(({MyClass}) => {/*...*/});

file src/sub1 will be available as http:/localhost/resA/sub1.bundle.js:

export class MyClass {};

file `webpack.config.js':

const path = require('path');
const webpack = require('webpack');

function config(env) {
    return {
        entry: {
            index: ['./src/page1.js']
        },
        output: {
            filename: '[name].bundle.js',
            chunkFilename: '[name].bundle.js',
            path: path.resolve(__dirname, 'dist'),
            publicPath: './'
        },
        module: {
            rules: [
                {
                    test: /\.js$/i,
                    include: /src/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader'
                    }
                }
            ]
        },
        devtool: 'source-map'
    };
}

module.exports = config;


问:
Promise error in ASP.NET Boilerplate (Core 2.0 + Angular 5) Free Template
I have been using ASP.NET Boilerplate to do CRUD Operations with the database with a REST API client like Postman using custom APIs and so far , it's working quite well.

But then when I move on to the frontend part, there is an unhandled exception in Users Component after logging in with an Admin account. First of all, I can see the list of users that I added, from which I can say the Create and Get operations are running properly (I also tested editing the users and it worked well). When I get to "Deleting" the users, I can see an exception in the console output as shown in the picture:

I thought I had somehow messed up some of the codes, so I redownloaded the whole template and started freshly to performed the delete operation again. The error still persists.

Moreover, when I add my own service class in the service-proxies.tx and export it in its service-proxy.module.ts, and inject the service into the app.component and console.log the response in the constructor, I still get the same exception.

Please help me dig to the root of the problem. Thank you.

Edit 1:

Here is the code in HTML line: 50:

```<code><li>
    <a href="javascript:void(0);" class="waves-effect waves-block" (click)="delete(user)">
       <i class="material-icons">delete_sweep</i>{{l('Delete')}}</a>
</li>
</code>```

On, the TS side, it is calling the delete function with User DTO.
On the TS side, the delete(User) looks like:

```<code>protected delete(user: UserDto): void {
    abp.message.confirm(
        "Delete user '" + user.fullName + "'?",
        (result: boolean) => {
            if (result) {
                this._userService.delete(user.id)
                    .subscribe(() => {
                        abp.notify.info("Deleted User: " + user.fullName);
                        this.refresh();
                    });
            }
        }
    );
}
</code>```

Edit 2:

I upgraded the SweetAlert version from 1.1.3 to 2.0.8 and the application fails to even compile. According to some GitHub threads, I'm supposed to override some functions related to the SweetAlert module. But then the error messages say the application cannot even locate .....node_modules\sweetalert\dist\sweetalert.css.js

答:
ABP v3.2.0 had a few Breaking Changes:

#2145 Upgrade to sweetalert v2.x. Existing applications should upgrade sweetalert packages to v2.x.

The free template may not have upgraded that yet.

You can upgrade to SweetAlert v2.0.8. Remove the node_modules folder before using yarn.

Update

You can now download v3.4.1 of the template with the SweetAlert upgrade.

Body:
I have been using ASP.NET Boilerplate to do CRUD Operations with the database with a REST API client like Postman using custom APIs and so far , it's working quite well.

But then when I move on to the frontend part, there is an unhandled exception in Users Component after logging in with an Admin account. First of all, I can see the list of users that I added, from which I can say the Create and Get operations are running properly (I also tested editing the users and it worked well). When I get to "Deleting" the users, I can see an exception in the console output as shown in the picture:

I thought I had somehow messed up some of the codes, so I redownloaded the whole template and started freshly to performed the delete operation again. The error still persists.

Moreover, when I add my own service class in the service-proxies.tx and export it in its service-proxy.module.ts, and inject the service into the app.component and console.log the response in the constructor, I still get the same exception.

Please help me dig to the root of the problem. Thank you.

Edit 1:

Here is the code in HTML line: 50:

       delete_sweep{{l('Delete')}}

On, the TS side, it is calling the delete function with User DTO.
On the TS side, the delete(User) looks like:

protected delete(user: UserDto): void {
    abp.message.confirm(
        "Delete user '" + user.fullName + "'?",
        (result: boolean) => {
            if (result) {
                this._userService.delete(user.id)
                    .subscribe(() => {
                        abp.notify.info("Deleted User: " + user.fullName);
                        this.refresh();
                    });
            }
        }
    );
}

Edit 2:

I upgraded the SweetAlert version from 1.1.3 to 2.0.8 and the application fails to even compile. According to some GitHub threads, I'm supposed to override some functions related to the SweetAlert module. But then the error messages say the application cannot even locate .....node_modules\sweetalert\dist\sweetalert.css.js


问:
Ensuring availability in Kubernetes with high-variance memory / CPU load?
Problem: the code we're running on Kubernetes Pods have a very high variance across it's runtime; specifically, it has occasional CPU & Memory spikes when certain conditions are triggered. These triggers involve user queries with hard realtime requirements (system has to respond within <5 seconds).

Under conditions where the node serving the spiking pod doesn't have enough CPU/RAM, Kubernetes responds to these excessive requests by killing the pod altogether; which results in no output across any time whatsoever.

In what way can we ensure, that these spikes are being taken into account when pods are allocated; and more critically, that no pod shutdown happens for these reasons?

Thanks!

答:
Limit is a limit, it's expected to do that, period.

What you can do is either run without limit - it will then behave like in any other situation when run on the node - OOM will happen when Node, not Pod reaches memory limit. But this sounds like asking for trouble. And mind that even if you'd set a high limit it's the request that actualy guarantees some resources to pod, so even with limit of 2Gi on Pod it can OOM on 512Mi if request was 128Mi

You should design your app in a way that will not generate such spikes or that will tolerate OOMs on pods. Hard to tell what your soft does exactly, but some things that come to mind that could help cracking this are request throttling, horizontal pod autoscaler or running asynchronously with some kind of message queue.


问:
Read a JSON from cakephp
I´m using a ajax requisition to take data from a Controller. The controller returns a json encode with the this data:

```<code>[{"Cliente":{"id":"1","nome":"Andre Figueredo","nome_representante":"Andre Figuerdo","email":"avs.fox@gmail.com","empresa":"Fox","area_atuacao":"Mocuton"},"Telefone":{"id":"1","cliente_id":"1","telefone":"11 33613529","telefone_representante":"11 97666-9899"},"Endereco":{"id":"1","cliente_id":"1","logradouro":"Av Washington","numero":"109","complemento":"","bairro":"santa luzia","municipio":"sao paulo","estado":"sp","cep":"02802-120"}}]
</code>```

How can i read this json?

thanks!

答:
In your controller method encode and return the result of $content['Cliente'] instead of $content.

```<code>    $content = $this->Content->find('first', $options);
    return json_encode($content['Cliente']);
</code>```

Now the result of json_encode will look like this which is appropriate for json_decode

```<code>  {"id":"1","nome":"Andre Figueredo","nome_representante":"Andre Figuerdo","email":"avs.fox@gmail.com","empresa":"Fox","area_atuacao":"Mocuton"},"Telefone":{"id":"1","cliente_id":"1","telefone":"11 33613529","telefone_representante":"11 97666-9899"},"Endereco":{"id":"1","cliente_id":"1","logradouro":"Av Washington","numero":"109","complemento":"","bairro":"santa luzia","municipio":"sao paulo","estado":"sp","cep":"02802-120"}
</code>```

Title: Read a JSON from cakephp

Body:
I´m using a ajax requisition to take data from a Controller. The controller returns a json encode with the this data:

[{"Cliente":{"id":"1","nome":"Andre Figueredo","nome_representante":"Andre Figuerdo","email":"avs.fox@gmail.com","empresa":"Fox","area_atuacao":"Mocuton"},"Telefone":{"id":"1","cliente_id":"1","telefone":"11 33613529","telefone_representante":"11 97666-9899"},"Endereco":{"id":"1","cliente_id":"1","logradouro":"Av Washington","numero":"109","complemento":"","bairro":"santa luzia","municipio":"sao paulo","estado":"sp","cep":"02802-120"}}]

How can i read this json?

thanks!

Body:
In your controller method encode and return the result of $content['Cliente'] instead of $content.

    $content = $this->Content->find('first', $options);
    return json_encode($content['Cliente']);

Now the result of json_encode will look like this which is appropriate for json_decode

  {"id":"1","nome":"Andre Figueredo","nome_representante":"Andre Figuerdo","email":"avs.fox@gmail.com","empresa":"Fox","area_atuacao":"Mocuton"},"Telefone":{"id":"1","cliente_id":"1","telefone":"11 33613529","telefone_representante":"11 97666-9899"},"Endereco":{"id":"1","cliente_id":"1","logradouro":"Av Washington","numero":"109","complemento":"","bairro":"santa luzia","municipio":"sao paulo","estado":"sp","cep":"02802-120"}


问:
Include a jquery plugin in a rails app: styling isn't applied
I'm looking for advice on how to get a jquery plugin to work with a rails app.  Specifically I'm trying to run the below plugin but I would also appreciate general advice on how to get the job done.  it seems like you you may have to require it in application.js and put it in the vendor/assets/javascript directory?  Am I missing anything else?

I can't get this jquery plugin to work in my rails app https://www.jqueryscript.net/time-clock/Minimal-jQuery-Count-Up-Plugin-CoutUpCircle.html

I've never installed a plugin before but I downloaded the jquery.countupcircle.min.js file and placed it in 'vendor/assets/javascripts'

in 'app/assets/javascripts' I updated application.js below (should I have another one of these files in vendor/assets/javascripts?)

```<code>//= require jquery
//= require jquery3
//= require jquery_ujs
//= require jquery.countupcircle.min
//= require popper
//= require turbolinks
//= require tether
//= require bootstrap
//= require_tree .
</code>```

on my page I have

```<code><div class="container-fluid">
  <div class="row">

    <div class="wrapper">
      <div id="count-box">19</div>
    </div>

    <script type="text/javascript">
    $(document).ready(function(){
    $('#count-box').CountUpCircle({
    duration: 500, // In ms, default: 5000
    opacity_anim: false,
    step_divider: 1
    });
    });
    </script>

  </div>
</div>
</code>```

the number counts up on the page and I see "19" but no circle and no styling is applied either.

in my styles.css file I have

```<code>  #count-box {
    display: block;
    border: 2px #ccc solid;
    color: #ccc;
    font-size: 4em;
    border-radius: 50%;
    line-height: 200px;
    height: 200px;
    width: 200px;
    text-align: center;
  }
</code>```

答:
Try running rake assets:precompile and restart the server.
If still not working bootstrap is overriding your plugin classes.
Try
//= require jquery.countupcircle.min
After you require bootstrap

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for advice on how to get a jquery plugin to work with a rails app.  Specifically I'm trying to run the below plugin but I would also appreciate general advice on how to get the job done.  it seems like you you may have to require it in application.js and put it in the vendor/assets/javascript directory?  Am I missing anything else?

I can't get this jquery plugin to work in my rails app https://www.jqueryscript.net/time-clock/Minimal-jQuery-Count-Up-Plugin-CoutUpCircle.html

I've never installed a plugin before but I downloaded the jquery.countupcircle.min.js file and placed it in 'vendor/assets/javascripts'

in 'app/assets/javascripts' I updated application.js below (should I have another one of these files in vendor/assets/javascripts?)

//= require jquery
//= require jquery3
//= require jquery_ujs
//= require jquery.countupcircle.min
//= require popper
//= require turbolinks
//= require tether
//= require bootstrap
//= require_tree .

on my page I have

19

the number counts up on the page and I see "19" but no circle and no styling is applied either.

in my styles.css file I have

  #count-box {
    display: block;
    border: 2px #ccc solid;
    color: #ccc;
    font-size: 4em;
    border-radius: 50%;
    line-height: 200px;
    height: 200px;
    width: 200px;
    text-align: center;
  }


问:
merge data from rows to columns
I have a source table like so:

```<code>id | code | description | parent_code | level
1    111     testone      null           1
2    222     testtwo      null           1
3    333     testthree    111            2
4    444     testfour     222            2
</code>```

Which I will have to upload to a new table with the result like so:

```<code>id | codelevel1 | descriptionlevel1 | codeleve2 | descriptionlevel2
1    111          testone              333        testthree
2    222          testtwo              444        testfour
</code>```

Please note I have a total of 6 levels, so in the target table, I have ...CodeLevel6 DescriptionLevel6 as the last two columns

I investigated the use of WITH AS recursive queries, but am currently stuck on how the codelevel1...codelevel6 fields will be filled in for a unique existing ID.

答:
You need a hierarchical query to get all rows with the same root element and then use PIVOT to transform the data:

```<code>SELECT *
FROM
(
  SELECT CONNECT_BY_ROOT id AS root_id, code, description, lvl
  FROM t
  CONNECT BY parent_code = PRIOR code
  START WITH parent_code IS NULL
)
PIVOT
(
  MIN(code) AS code, MIN(description) AS description
  FOR lvl IN ( 1, 2, 3, 4, 5, 6 )
)
</code>```

With lvl IN ( 1, 2 ) this returns:

```<code>   ROOT_ID     1_CODE 1_DESCRIPTION     2_CODE 2_DESCRIPTION
---------- ---------- ------------- ---------- -------------
         1        111 testone              333 testthree
         2        222 testtwo              444 testfour
</code>```

Title: merge data from rows to columns

Body:
I have a source table like so:

id | code | description | parent_code | level
1    111     testone      null           1
2    222     testtwo      null           1
3    333     testthree    111            2
4    444     testfour     222            2

Which I will have to upload to a new table with the result like so:

id | codelevel1 | descriptionlevel1 | codeleve2 | descriptionlevel2
1    111          testone              333        testthree
2    222          testtwo              444        testfour

Please note I have a total of 6 levels, so in the target table, I have ...CodeLevel6 DescriptionLevel6 as the last two columns

I investigated the use of WITH AS recursive queries, but am currently stuck on how the codelevel1...codelevel6 fields will be filled in for a unique existing ID.

Body:
You need a hierarchical query to get all rows with the same root element and then use PIVOT to transform the data:

SELECT *
FROM
(
  SELECT CONNECT_BY_ROOT id AS root_id, code, description, lvl
  FROM t
  CONNECT BY parent_code = PRIOR code
  START WITH parent_code IS NULL
)
PIVOT
(
  MIN(code) AS code, MIN(description) AS description
  FOR lvl IN ( 1, 2, 3, 4, 5, 6 )
)

With lvl IN ( 1, 2 ) this returns:

   ROOT_ID     1_CODE 1_DESCRIPTION     2_CODE 2_DESCRIPTION
---------- ---------- ------------- ---------- -------------
         1        111 testone              333 testthree
         2        222 testtwo              444 testfour


问:
How to pause the animation on mouse hover on image
Please I need help to stop the animation on mouse hover and to continue on mouse out. Please see the url below to view the code. thanks

http://jsfiddle.net/AbdiasSoftware/F8x4p/

```<code>        $(window).load(function(){
        var pos = $('#center').position(),
        radiusSat = $('#sat1').width() * 0.5,
        radius = $('#center').width() * 0.5,
        cx = pos.left + radius,
        cy = pos.top + radius,
        x, y, angle = 0,
        angles = [],
        spc = 360 / 25,
        deg2rad = Math.PI / 180,
        i = 0;

    for(;i < 25; i++) {
        angles.push(angle);
        angle += spc;
    }

    /// space out radius
    radius += (radiusSat + 25);

    loop();

    function loop() {
    for(var i = 0; i < angles.length; i++) {

        angle = angles[i];

        x = cx + radius * Math.cos(angle * deg2rad);
        y = cy + radius * Math.sin(angle * deg2rad);

        $('#sat' + i).css({left:x - radiusSat, top:y - radiusSat});

    angles[i] += 0.1;
        if (angles[i] > 360) angles[i] = 0;
    }

    requestAnimationFrame(loop);

}
});
</code>```

答:
You could create a variable to keep track on whether the mouse is inside, and use events to change the variable.

Firstly, wrap your markup in a containing div so the event listener can easily be applied to all the elements:

```<code><div class="container">
  <div id="center"></div>
  <div id="sat0"></div>
  <div id="sat1"></div>
  <div id="sat2"></div>
  <div id="sat3"></div>
  <div id="sat4"></div>
</div>
</code>```

Then add a new variable, called mouseEntered, and set it to false.

Then create two event listeners - one to set the mouseEntered variable to true when the mouse enters the container, and one to set it to false when the mouse leaves.

```<code>document.querySelector('.container').addEventListener('mouseenter', function() {
    mouseEntered = true
})
document.querySelector('.container').addEventListener('mouseleave', function() {
    mouseEntered = false
})
</code>```

Finally, wrap everything in your loop function, apart from requestAnimationFrame, in an if statement that checks if mouseEntered is false.

```<code>function loop() {
    if (mouseEntered === false) {
      for(var i = 0; i < angles.length; i++) {

          angle = angles[i];

          x = cx + radius * Math.cos(angle * deg2rad);
          y = cy + radius * Math.sin(angle * deg2rad);

          $('#sat' + i).css({left:x - radiusSat, top:y - radiusSat});

          angles[i] = angles[i] + 1;
          if (angles[i] > 360) angles[i] = 0;
      }
    }

    requestAnimationFrame(loop);
}
</code>```

Fiddle with the changes: http://jsfiddle.net/pbobbr5h/

Body:
Please I need help to stop the animation on mouse hover and to continue on mouse out. Please see the url below to view the code. thanks

http://jsfiddle.net/AbdiasSoftware/F8x4p/

        $(window).load(function(){
        var pos = $('#center').position(),
        radiusSat = $('#sat1').width() * 0.5,
        radius = $('#center').width() * 0.5,
        cx = pos.left + radius,
        cy = pos.top + radius,
        x, y, angle = 0,
        angles = [],
        spc = 360 / 25,
        deg2rad = Math.PI / 180,
        i = 0;

    for(;i < 25; i++) {
        angles.push(angle);
        angle += spc;
    }

    /// space out radius
    radius += (radiusSat + 25);

    loop();

    function loop() {
    for(var i = 0; i < angles.length; i++) {

        angle = angles[i];

        x = cx + radius * Math.cos(angle * deg2rad);
        y = cy + radius * Math.sin(angle * deg2rad);

        $('#sat' + i).css({left:x - radiusSat, top:y - radiusSat});

    angles[i] += 0.1;
        if (angles[i] > 360) angles[i] = 0;
    }

    requestAnimationFrame(loop);

}
});

Body:
You could create a variable to keep track on whether the mouse is inside, and use events to change the variable.

Firstly, wrap your markup in a containing div so the event listener can easily be applied to all the elements:

<div class="container">
  <div id="center"></div>
  <div id="sat0"></div>
  <div id="sat1"></div>
  <div id="sat2"></div>
  <div id="sat3"></div>
  <div id="sat4"></div>
</div>

Then add a new variable, called mouseEntered, and set it to false.

Then create two event listeners - one to set the mouseEntered variable to true when the mouse enters the container, and one to set it to false when the mouse leaves.

document.querySelector('.container').addEventListener('mouseenter', function() {
    mouseEntered = true
})
document.querySelector('.container').addEventListener('mouseleave', function() {
    mouseEntered = false
})

Finally, wrap everything in your loop function, apart from requestAnimationFrame, in an if statement that checks if mouseEntered is false.

function loop() {
    if (mouseEntered === false) {
      for(var i = 0; i < angles.length; i++) {

          angle = angles[i];

          x = cx + radius * Math.cos(angle * deg2rad);
          y = cy + radius * Math.sin(angle * deg2rad);

          $('#sat' + i).css({left:x - radiusSat, top:y - radiusSat});

          angles[i] = angles[i] + 1;
          if (angles[i] > 360) angles[i] = 0;
      }
    }

    requestAnimationFrame(loop);
}

Fiddle with the changes: http://jsfiddle.net/pbobbr5h/


问:
Unwanted Checkbox selections in RecyclerView in Kotlin (Android)
In my app I have a RecyclerView which contains 15 static items consisting of a TextView and a CheckBox:

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="82dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:scrollbars="vertical" />
</code>```

On click on the item, the according checkbox is set to checked and the item is added to a selection-list.

The problem:
When I scroll down and select an item, scroll up again I alwys see another checkbox checked. While debugging I noticed, that only my actually selected item has been added to the list, but nethertheless its a bad user experience when other items are checked/"selected" in the UI randomly.

How can I stop this strange behaviour?

I am using a view holder to manage the item views:

```<code>private inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val checkBox: CheckBox = view.findViewById(R.id.checkbox)
            val text: TextView = view.findViewById(R.id.text)

            init {
                view.setOnClickListener { checkBox.isChecked = !checkBox.isChecked }
                checkBox.setOnCheckedChangeListener { _, isChecked ->
                    val itemText = dataset[adapterPosition]
                    logger.debug("state change $isChecked for $itemText")
                    if (isChecked) selectedItems.add(itemText)
                    else {
                        if (selectedItems.contains(itemText)) selectedItems.remove(itemText)
                    }
                }
            }
        }
</code>```

My onBindViewHolder()-method contains the following:

```<code>override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
            val itemText = dataset[position]
            holder?.text?.text = itemText
        }
</code>```

答:
This is probably happening because of the RecyclerView recycling logic. When you scroll up, a view that disappears to the bottom is added to the top. In your case: the view with a checked checkbox is recycled (bound) to be used at another spot, which is not what you want. To fix this you need to keep tracked of what views should have a checked checkbox. Only change the state of the checkbox in a view depending on the data state associated with that view. Since you're already keeping track of items that should be checked in the selectedItems array, just add the following code to onBindViewHolder.

holder?.checkbox?.isChecked = selectedItems.contains(itemText)

Body:
In my app I have a RecyclerView which contains 15 static items consisting of a TextView and a CheckBox:

<android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="82dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:scrollbars="vertical" />

On click on the item, the according checkbox is set to checked and the item is added to a selection-list.

The problem:
When I scroll down and select an item, scroll up again I alwys see another checkbox checked. While debugging I noticed, that only my actually selected item has been added to the list, but nethertheless its a bad user experience when other items are checked/"selected" in the UI randomly.

How can I stop this strange behaviour?

I am using a view holder to manage the item views:

private inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val checkBox: CheckBox = view.findViewById(R.id.checkbox)
            val text: TextView = view.findViewById(R.id.text)

            init {
                view.setOnClickListener { checkBox.isChecked = !checkBox.isChecked }
                checkBox.setOnCheckedChangeListener { _, isChecked ->
                    val itemText = dataset[adapterPosition]
                    logger.debug("state change $isChecked for $itemText")
                    if (isChecked) selectedItems.add(itemText)
                    else {
                        if (selectedItems.contains(itemText)) selectedItems.remove(itemText)
                    }
                }
            }
        }

My onBindViewHolder()-method contains the following:

override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
            val itemText = dataset[position]
            holder?.text?.text = itemText
        }


问:
How can I change vim status line color?
I'm tring to change vim's status line color by editing my .vimrc .

By using the command au, I tried to change the color of the status line when      entering or leaving insert mode; by using this command nothing happens:

hi StatusLine guibg=whatevercolourIwant

By changing the status line color directly, without any au command, the background remains the same.

Is there reason why by executing

:hi StatusLine guibg=red,

for instance, the background of the status bar still remains greenish?

答:
This is indeed a awesome bit of code!!

I have modified it to suit my needs. I have added some wording to my buffer state:

[saved] or [modified].

I set my status bar color based on buffer change event. DarkSlateGray for unchanged/normal. OrangeRed4 if there were any modifications done.

Here is my modified code:

```<code>" Some funky status bar code its seems
" https://stackoverflow.com/questions/9065941/how-can-i-change-vim-status-line-colour
set laststatus=2            " set the bottom status bar

function! ModifiedColor()
    if &mod == 1
        hi statusline guibg=White ctermfg=8 guifg=OrangeRed4 ctermbg=15
    else
        hi statusline guibg=White ctermfg=8 guifg=DarkSlateGray ctermbg=15
    endif
endfunction

au InsertLeave,InsertEnter,BufWritePost   * call ModifiedColor()
" default the statusline when entering Vim
hi statusline guibg=White ctermfg=8 guifg=DarkSlateGray ctermbg=15

" Formats the statusline
set statusline=%f                           " file name
set statusline+=[%{strlen(&fenc)?&fenc:'none'}, "file encoding
set statusline+=%{&ff}] "file format
set statusline+=%y      "filetype
set statusline+=%h      "help file flag
set statusline+=[%{getbufvar(bufnr('%'),'&mod')?'modified':'saved'}]
"modified flag

set statusline+=%r      "read only flag

set statusline+=\ %=                        " align left
set statusline+=Line:%l/%L[%p%%]            " line X of Y [percent of file]
set statusline+=\ Col:%c                    " current column
set statusline+=\ Buf:%n                    " Buffer number
set statusline+=\ [%b][0x%B]\               " ASCII and byte code under cursor
</code>```

Title: How can I change vim status line color?

Body:
This is indeed a awesome bit of code!!

I have modified it to suit my needs. I have added some wording to my buffer state:

[saved] or [modified].

I set my status bar color based on buffer change event. DarkSlateGray for unchanged/normal. OrangeRed4 if there were any modifications done.

Here is my modified code:

" Some funky status bar code its seems
" https://stackoverflow.com/questions/9065941/how-can-i-change-vim-status-line-colour
set laststatus=2            " set the bottom status bar

function! ModifiedColor()
    if &mod == 1
        hi statusline guibg=White ctermfg=8 guifg=OrangeRed4 ctermbg=15
    else
        hi statusline guibg=White ctermfg=8 guifg=DarkSlateGray ctermbg=15
    endif
endfunction

au InsertLeave,InsertEnter,BufWritePost   * call ModifiedColor()
" default the statusline when entering Vim
hi statusline guibg=White ctermfg=8 guifg=DarkSlateGray ctermbg=15

" Formats the statusline
set statusline=%f                           " file name
set statusline+=[%{strlen(&fenc)?&fenc:'none'}, "file encoding
set statusline+=%{&ff}] "file format
set statusline+=%y      "filetype
set statusline+=%h      "help file flag
set statusline+=[%{getbufvar(bufnr('%'),'&mod')?'modified':'saved'}]
"modified flag

set statusline+=%r      "read only flag

set statusline+=\ %=                        " align left
set statusline+=Line:%l/%L[%p%%]            " line X of Y [percent of file]
set statusline+=\ Col:%c                    " current column
set statusline+=\ Buf:%n                    " Buffer number
set statusline+=\ [%b][0x%B]\               " ASCII and byte code under cursor