问:
I need to mock a RabbitMQ in my unit Test
I am using a RabbitMQ in my project.

I have in my consumer the code of the client part of rabbitMQ and the connection need a tls1.1 to connect with the real MQ.

I want to test this code in my JUnit test and to mock the message delivery to my consumer.

I see in google several examples with different tools how camel rabbit or activeMQ but this tools works with amqp 1.0 and rabbitMQ only works in amqp 0.9 .

Someone had this problem?

Thanks!

UPDATE

This is the code to testing to receive a json from the queue.

```<code>package com.foo.foo.queue;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.security.*;
import java.security.cert.CertificateException;
import javax.net.ssl.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.foo.foo.Constants.Constants;
import com.foo.foo.core.ConfigurationContainer;
import com.foo.foo.policyfinders.PolicyFinder;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class BrokerThreadHLConsumer extends Thread {

private static BrokerThreadHLConsumer instance;

private static final Logger log = LogManager.getLogger(BrokerThreadHLConsumer.class);

private Channel channel;
private String queueName;
private PolicyFinder PolicyFinder;
private Connection connection;
private QueueingConsumer consumer;

private boolean loop;

private BrokerThreadHLConsumer() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    char[] keyPassphrase = "clientrabbit".toCharArray();
    KeyStore keyStoreCacerts;
    ConfigurationContainer configurationContainer = ConfigurationContainer.getInstance();
    String exchangeName = configurationContainer.getProperty(Constants.EXCHANGE_NAME);
    String rabbitHost = configurationContainer.getProperty(Constants.RABBITMQ_SERVER_HOST_VALUE);
    try {
        /* Public key cacerts to connect to message queue*/
        keyStoreCacerts = KeyStore.getInstance("PKCS12");
        URL resourcePublicKey = this.getClass().getClassLoader().getResource("certs/client.keycert.p12");
        File filePublicKey = new File(resourcePublicKey.toURI());
        keyStoreCacerts.load(new FileInputStream(filePublicKey), keyPassphrase);
        KeyManagerFactory keyManager;

        keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStoreCacerts, keyPassphrase);

        char[] trustPassphrase = "changeit".toCharArray();
        KeyStore tks;

        tks = KeyStore.getInstance("JCEKS");

        URL resourceCacerts = this.getClass().getClassLoader().getResource("certs/cacerts");
        File fileCacerts = new File(resourceCacerts.toURI());

        tks.load(new FileInputStream(fileCacerts), trustPassphrase);

        TrustManagerFactory tmf;
        tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(tks);

        SSLContext c = SSLContext.getInstance("TLSv1.1");
        c.init(keyManager.getKeyManagers(), tmf.getTrustManagers(), null);

        factory.setUri(rabbitHost);
        factory.useSslProtocol(c);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchangeName, "fanout");
        queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, exchangeName, "");

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e1) {
        e1.printStackTrace();
    } catch (Exception e) {
        log.error("Couldn't instantiate a channel with the broker installed in " + rabbitHost);
        log.error(e.getStackTrace());
        e.printStackTrace();
    }
}

public static BrokerThreadHLConsumer getInstance() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    if (instance == null)
        instance = new BrokerThreadHLConsumer();
    return instance;
}

public void run() {
    if (PolicyFinder != null) {
        try {
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
            log.info("Consumer broker started and waiting for messages");
            loop = true;
            while (loop) {
                try {
                    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                    String message = new String(delivery.getBody());
                    JSONObject obj = new JSONObject(message);
                    log.info("Message received from broker " + obj);
                    if (StringUtils.isNotEmpty(message) && !PolicyFinder.managePolicySet(obj)) {
                        log.error("PolicySet error: error upgrading the policySet");
                    }
                } catch (Exception e) {
                    log.error("Receiving message error");
                    log.error(e);
                }
            }
        } catch (IOException e) {
            log.error("Consumer couldn't start");
            log.error(e.getStackTrace());
        }
    } else {
        log.error("Consumer couldn't start cause of PolicyFinder is null");
    }
}

public void close() {
    loop = false;
    try {
        consumer.getChannel().basicCancel(consumer.getConsumerTag());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        connection.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void setLuxPolicyFinder(PolicyFinder PolicyFinder) {
    this.PolicyFinder = PolicyFinder;
}
}
</code>```

答:
So here is how i did it, some stuffs might be here and there in process of hiding the necessary class implementation details, but you would get a hint! :)

assumption for unit test:

RMQ is working fine and data send to it would be pushed in queue

Only thing to be tested is if the data generated is correct or not

and whether the call to RMQs send() is happening or not!

```<code> public class SomeClassTest {
        private Config config;
        private RmqConfig rmqConfig;
        private static final ObjectMapper mapper = new ObjectMapper();
        private JasperServerClient jasperServerClient;
    //    @Mock
        @InjectMocks
        private RabbitMQProducer rabbitMQProducer;
        private Connection phoenixConnection;
        private String targetNotificationMessage;
        SomeClass someClassObject;

        @Before
        public void setUp() {

            // Mock basic stuffs
            config = mock(Config.class);
            Connection = mock(Connection.class);
            rabbitMQProducer = mock(RabbitMQProducer.class); // Imp

            jasperServerClient = mock(JasperServerClient.class);

            rmqConfig = RmqConfig.builder()
                    .host("localhost")
                    .port(5672)
                    .userName("guest")
                    .password("guest")
                    .queueName("somequeue_name")
                    .prefetch(1)
                    .build();
            final String randomMessage = "This is a waste message";
            Message mockMsg = Message.forSending(randomMessage.getBytes(), null, rmqConfig.getQueueName(), rmqConfig.getQueueName(), "text/plain", "UTF-8", true); // prepare a mock message

            // Prepare service configs
            ConnectionConfig connectionConfig = RmqConfigUtil.getConfig(rmqConfig);
            ProducerConfig producerConfig = new ProducerConfigBuilder()
                    .exchange(rmqConfig.getQueueName())
                    .contentType("text/pain")
                    .contentEncoding("UTF-8")
                    .connection(connectionConfig).build();
            rabbitMQProducer.open(croducerConfig.asMap());

            // build the major stuff where the code resides
            someClassObject =  SomeClass.builder()
                    .phoenixConnection(phoenixConnection)
                    .userExchangeName(rmqConfig.getQueueName())
                    .userRabbitMQProducer(rabbitMQProducer)
                    .ftpConfig(config.getFtpConfig())
                    .jasperServerClient(jasperServerClient)
                    .objectMapper(new ObjectMapper())
                    .build();

            MockitoAnnotations.initMocks(this);
        }

        @Test
        public void testNotificationPub() throws Exception {

            // Prepare expected Values
            targetNotificationMessage = <<some message>>

            // Reflection -  my target functions were private
            Class cls = Class.forName("com.some.path.to.class");
            Object[] objForGetMessage = {<<stuffs>>, <<stuffs>>};

            Method getNotificationMessage = cls.getDeclaredMethod("private_fn_1", <<some class>>.class, <<some class>>.class);
            Method pubNotification = cls.getDeclaredMethod("private_fn_2", <<some class>>.class, RabbitMQProducer.class, String.class);

            getNotificationMessage.setAccessible(true);
            pubNotification.setAccessible(true);

            // Test Case #1
            final <<some class>> notificationMessage = (<<some class>>)getNotificationMessage.invoke(someClassObject, objForGetMessage);
            assertEquals(notificationMessage.getMessage(), targetNotificationMessage);

            // Test Case #2 -  this does RMQ call
            Object[] objPubMessage = {notificationMessage, rabbitMQProducer, rmqConfig.getQueueName()};
            final Object publishNotification = pubNotification.invoke(someClassObject, objPubMessage);
            assertEquals(publishNotificationResp, publishNotification); //viola

            //Important, since RabbitMQProducer is mocked, we need to checkup if function call is made to "send" function which send data to RMQ
            verify(rabbitMQProducer,times(1)).send(any());

        }

        @Test
        public void testMockCreation(){
            assertNotNull(rmqConfig);
            assertNotNull(config);
        }
</code>```

Body:
I am using a RabbitMQ in my project.

I have in my consumer the code of the client part of rabbitMQ and the connection need a tls1.1 to connect with the real MQ.

I want to test this code in my JUnit test and to mock the message delivery to my consumer.

I see in google several examples with different tools how camel rabbit or activeMQ but this tools works with amqp 1.0 and rabbitMQ only works in amqp 0.9 .

Someone had this problem?

Thanks!

UPDATE

This is the code to testing to receive a json from the queue.

package com.foo.foo.queue;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.security.*;
import java.security.cert.CertificateException;
import javax.net.ssl.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.foo.foo.Constants.Constants;
import com.foo.foo.core.ConfigurationContainer;
import com.foo.foo.policyfinders.PolicyFinder;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class BrokerThreadHLConsumer extends Thread {

private static BrokerThreadHLConsumer instance;

private static final Logger log = LogManager.getLogger(BrokerThreadHLConsumer.class);

private Channel channel;
private String queueName;
private PolicyFinder PolicyFinder;
private Connection connection;
private QueueingConsumer consumer;

private boolean loop;

private BrokerThreadHLConsumer() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    char[] keyPassphrase = "clientrabbit".toCharArray();
    KeyStore keyStoreCacerts;
    ConfigurationContainer configurationContainer = ConfigurationContainer.getInstance();
    String exchangeName = configurationContainer.getProperty(Constants.EXCHANGE_NAME);
    String rabbitHost = configurationContainer.getProperty(Constants.RABBITMQ_SERVER_HOST_VALUE);
    try {
        /* Public key cacerts to connect to message queue*/
        keyStoreCacerts = KeyStore.getInstance("PKCS12");
        URL resourcePublicKey = this.getClass().getClassLoader().getResource("certs/client.keycert.p12");
        File filePublicKey = new File(resourcePublicKey.toURI());
        keyStoreCacerts.load(new FileInputStream(filePublicKey), keyPassphrase);
        KeyManagerFactory keyManager;

        keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStoreCacerts, keyPassphrase);

        char[] trustPassphrase = "changeit".toCharArray();
        KeyStore tks;

        tks = KeyStore.getInstance("JCEKS");

        URL resourceCacerts = this.getClass().getClassLoader().getResource("certs/cacerts");
        File fileCacerts = new File(resourceCacerts.toURI());

        tks.load(new FileInputStream(fileCacerts), trustPassphrase);

        TrustManagerFactory tmf;
        tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(tks);

        SSLContext c = SSLContext.getInstance("TLSv1.1");
        c.init(keyManager.getKeyManagers(), tmf.getTrustManagers(), null);

        factory.setUri(rabbitHost);
        factory.useSslProtocol(c);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchangeName, "fanout");
        queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, exchangeName, "");

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e1) {
        e1.printStackTrace();
    } catch (Exception e) {
        log.error("Couldn't instantiate a channel with the broker installed in " + rabbitHost);
        log.error(e.getStackTrace());
        e.printStackTrace();
    }
}

public static BrokerThreadHLConsumer getInstance() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    if (instance == null)
        instance = new BrokerThreadHLConsumer();
    return instance;
}

public void run() {
    if (PolicyFinder != null) {
        try {
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
            log.info("Consumer broker started and waiting for messages");
            loop = true;
            while (loop) {
                try {
                    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                    String message = new String(delivery.getBody());
                    JSONObject obj = new JSONObject(message);
                    log.info("Message received from broker " + obj);
                    if (StringUtils.isNotEmpty(message) && !PolicyFinder.managePolicySet(obj)) {
                        log.error("PolicySet error: error upgrading the policySet");
                    }
                } catch (Exception e) {
                    log.error("Receiving message error");
                    log.error(e);
                }
            }
        } catch (IOException e) {
            log.error("Consumer couldn't start");
            log.error(e.getStackTrace());
        }
    } else {
        log.error("Consumer couldn't start cause of PolicyFinder is null");
    }
}

public void close() {
    loop = false;
    try {
        consumer.getChannel().basicCancel(consumer.getConsumerTag());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        connection.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void setLuxPolicyFinder(PolicyFinder PolicyFinder) {
    this.PolicyFinder = PolicyFinder;
}
}

Body:
So here is how i did it, some stuffs might be here and there in process of hiding the necessary class implementation details, but you would get a hint! :)

assumption for unit test:

RMQ is working fine and data send to it would be pushed in queue

Only thing to be tested is if the data generated is correct or not

and whether the call to RMQs send() is happening or not!

 public class SomeClassTest {
        private Config config;
        private RmqConfig rmqConfig;
        private static final ObjectMapper mapper = new ObjectMapper();
        private JasperServerClient jasperServerClient;
    //    @Mock
        @InjectMocks
        private RabbitMQProducer rabbitMQProducer;
        private Connection phoenixConnection;
        private String targetNotificationMessage;
        SomeClass someClassObject;

        @Before
        public void setUp() {

            // Mock basic stuffs
            config = mock(Config.class);
            Connection = mock(Connection.class);
            rabbitMQProducer = mock(RabbitMQProducer.class); // Imp

            jasperServerClient = mock(JasperServerClient.class);

            rmqConfig = RmqConfig.builder()
                    .host("localhost")
                    .port(5672)
                    .userName("guest")
                    .password("guest")
                    .queueName("somequeue_name")
                    .prefetch(1)
                    .build();
            final String randomMessage = "This is a waste message";
            Message mockMsg = Message.forSending(randomMessage.getBytes(), null, rmqConfig.getQueueName(), rmqConfig.getQueueName(), "text/plain", "UTF-8", true); // prepare a mock message

            // Prepare service configs
            ConnectionConfig connectionConfig = RmqConfigUtil.getConfig(rmqConfig);
            ProducerConfig producerConfig = new ProducerConfigBuilder()
                    .exchange(rmqConfig.getQueueName())
                    .contentType("text/pain")
                    .contentEncoding("UTF-8")
                    .connection(connectionConfig).build();
            rabbitMQProducer.open(croducerConfig.asMap());

            // build the major stuff where the code resides
            someClassObject =  SomeClass.builder()
                    .phoenixConnection(phoenixConnection)
                    .userExchangeName(rmqConfig.getQueueName())
                    .userRabbitMQProducer(rabbitMQProducer)
                    .ftpConfig(config.getFtpConfig())
                    .jasperServerClient(jasperServerClient)
                    .objectMapper(new ObjectMapper())
                    .build();

            MockitoAnnotations.initMocks(this);
        }

        @Test
        public void testNotificationPub() throws Exception {

            // Prepare expected Values
            targetNotificationMessage = <<some message>>

            // Reflection -  my target functions were private
            Class cls = Class.forName("com.some.path.to.class");
            Object[] objForGetMessage = {<<stuffs>>, <<stuffs>>};

            Method getNotificationMessage = cls.getDeclaredMethod("private_fn_1", <<some class>>.class, <<some class>>.class);
            Method pubNotification = cls.getDeclaredMethod("private_fn_2", <<some class>>.class, RabbitMQProducer.class, String.class);

            getNotificationMessage.setAccessible(true);
            pubNotification.setAccessible(true);

            // Test Case #1
            final <<some class>> notificationMessage = (<<some class>>)getNotificationMessage.invoke(someClassObject, objForGetMessage);
            assertEquals(notificationMessage.getMessage(), targetNotificationMessage);

            // Test Case #2 -  this does RMQ call
            Object[] objPubMessage = {notificationMessage, rabbitMQProducer, rmqConfig.getQueueName()};
            final Object publishNotification = pubNotification.invoke(someClassObject, objPubMessage);
            assertEquals(publishNotificationResp, publishNotification); //viola

            //Important, since RabbitMQProducer is mocked, we need to checkup if function call is made to "send" function which send data to RMQ
            verify(rabbitMQProducer,times(1)).send(any());

        }

        @Test
        public void testMockCreation(){
            assertNotNull(rmqConfig);
            assertNotNull(config);
        }


来源: stackexchange

问:
jQuery Year Picker
I have one form in that I have Year of passed out field for that I need to show only years drop down.

Is it possible to show only years in jQuery datepicker?? Otherwise is there any angular directive to show only years in drop down?

```<code>$("#date").datepicker({
  changeMonth: false,
  changeYear: true,
  dateFormat: 'dd/mm/yy',
  duration: 'fast',
  stepMonths: 0
});
</code>```

fiddle: http://jsfiddle.net/LttVe/628/

答:
As suggested in comments, why not to create a simple dropdown if only years need to be selected. Following is an example to create a directive for that.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.details = { year_of_completion: null, year_of_admission: null }
}).directive('yearPicker', function() {
  return {
    scope: {
      ngModel: '=',
      startYear: '@',
      totalYears: '@'
    },
    template: '<select ng-model="ngModel" ng-options="year for year in yearsRange"></select>',
    link: function(scope) {
      scope.yearsRange = [];
      for (var i = 0; i <= scope.totalYears; i++) {
        scope.yearsRange.push(scope.startYear++)
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl">
    <year-picker ng-model="details.year_of_admission" start-year="1997" total-years="20"></year-picker>
    Admission year: {{details.year_of_admission}}
    <br />
    <year-picker ng-model="details.year_of_completion" start-year="1997" total-years="20"></year-picker>
    Submission year: {{details.year_of_completion}}
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery Year Picker

Body:
I have one form in that I have Year of passed out field for that I need to show only years drop down.

Is it possible to show only years in jQuery datepicker?? Otherwise is there any angular directive to show only years in drop down?

$("#date").datepicker({
  changeMonth: false,
  changeYear: true,
  dateFormat: 'dd/mm/yy',
  duration: 'fast',
  stepMonths: 0
});

fiddle: http://jsfiddle.net/LttVe/628/

Body:
As suggested in comments, why not to create a simple dropdown if only years need to be selected. Following is an example to create a directive for that.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.details = { year_of_completion: null, year_of_admission: null }
}).directive('yearPicker', function() {
  return {
    scope: {
      ngModel: '=',
      startYear: '@',
      totalYears: '@'
    },
    template: '<select ng-model="ngModel" ng-options="year for year in yearsRange"></select>',
    link: function(scope) {
      scope.yearsRange = [];
      for (var i = 0; i <= scope.totalYears; i++) {
        scope.yearsRange.push(scope.startYear++)
      }
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl">
    <year-picker ng-model="details.year_of_admission" start-year="1997" total-years="20"></year-picker>
    Admission year: {{details.year_of_admission}}
    <br />
    <year-picker ng-model="details.year_of_completion" start-year="1997" total-years="20"></year-picker>
    Submission year: {{details.year_of_completion}}
  </div>
</div>


问:
What is the reason for the following error while I am calling a rest client in spring boot using rest template
My code snippet is here...

```<code>    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    PinsDTO pinsDTO = new PinsDTO();
    pinsDTO.setPin(pin);
    @SuppressWarnings({ "rawtypes", "unchecked" })
    HttpEntity<?> entity = new HttpEntity(pinsDTO, headers);

    StringBuilder url = new StringBuilder();
    url.append("url");

    URI uri = null;
    try {
        uri = new URI(url.toString());
    } catch (URISyntaxException e) {

    }
    String seskey = null;
    try {
        ResponseEntity<Object> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, entity, Object.class);

        ServiceResponse response = new ServiceResponse();
        response = (ServiceResponse) responseEntity.getBody();
        if (response.specifiedCode.equals("202")) {
            seskey = "";
        } else if (response.specifiedCode.equals("406")) {

            seskey = "INVALID";

        } else if (response.specifiedCode.equals("400")) {
            seskey = "NO";
        }

    } catch (RestClientException rce) {
        rce.printStackTrace();
    }
</code>```

Here is my error....

org.springframework.web.client.HttpClientErrorException: 406      at
  org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:92)
    at
  org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:77)
    at
  org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at
  org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:747)
    at
  org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:700)
    at
  org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
    at
  org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:592)
    at
  lk.dialog.ccs.retailloan.ussd.model.RetailLoanUssdManager.pinValidate(RetailLoanUssdManager.java:786)
    at
  lk.dialog.ccs.retailloan.ussd.controller.RetailLoanUssdController.pinvalidation(RetailLoanUssdController.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at
  org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at
  org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at
  org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at
  org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

答:
You have set the content type in your headers but you did not set the accept header. Apparently the service you are calling is returning with a non-implicit content type.

So find out what is that services content type and provide that in the client header config:

```<code>HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.xxx, MediaType.yyy));
</code>```

Body:
My code snippet is here...

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    PinsDTO pinsDTO = new PinsDTO();
    pinsDTO.setPin(pin);
    @SuppressWarnings({ "rawtypes", "unchecked" })
    HttpEntity<?> entity = new HttpEntity(pinsDTO, headers);

    StringBuilder url = new StringBuilder();
    url.append("url");

    URI uri = null;
    try {
        uri = new URI(url.toString());
    } catch (URISyntaxException e) {

    }
    String seskey = null;
    try {
        ResponseEntity<Object> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, entity, Object.class);

        ServiceResponse response = new ServiceResponse();
        response = (ServiceResponse) responseEntity.getBody();
        if (response.specifiedCode.equals("202")) {
            seskey = "";
        } else if (response.specifiedCode.equals("406")) {

            seskey = "INVALID";

        } else if (response.specifiedCode.equals("400")) {
            seskey = "NO";
        }

    } catch (RestClientException rce) {
        rce.printStackTrace();
    }

Here is my error....

org.springframework.web.client.HttpClientErrorException: 406      at
  org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:92)
    at
  org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:77)
    at
  org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at
  org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:747)
    at
  org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:700)
    at
  org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
    at
  org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:592)
    at
  lk.dialog.ccs.retailloan.ussd.model.RetailLoanUssdManager.pinValidate(RetailLoanUssdManager.java:786)
    at
  lk.dialog.ccs.retailloan.ussd.controller.RetailLoanUssdController.pinvalidation(RetailLoanUssdController.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at
  org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at
  org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at
  org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at
  org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

Body:
You have set the content type in your headers but you did not set the accept header. Apparently the service you are calling is returning with a non-implicit content type.

So find out what is that services content type and provide that in the client header config:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.xxx, MediaType.yyy));


问:
How can I retrieve MySQL temporary tables meta data within a single connection in JDBC?
And once again I have found an issue that I don't know how to fight with. Let's assume we have the following testing code:

```<code>private static final String CREATE_TEMPORARY_TABLE =
        "CREATE TEMPORARY TABLE T1 (\n" +
        "\tA FLOAT(4, 1),\n" +
        "\tB FLOAT(5, 2),\n" +
        "\tC FLOAT,\n" +
        "\tD INTEGER\n" +
        ") ENGINE = MEMORY;";

private final String[] SHOW_TABLE_TYPES = new String[] {
        //"TABLE",
        "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
};

private void createTemporaryTable(Connection connection) throws SQLException {
    final PreparedStatement statement = connection.prepareStatement(CREATE_TEMPORARY_TABLE);
    statement.execute();
    statement.close();
}

private void showTables(Connection connection) throws SQLException {
    final ResultSet set = connection.getMetaData().getTables(null, null, null, SHOW_TABLE_TYPES);
    while ( set.next() ) {
        out.println(format("%s %s %s %s %s",
                set.getString("TABLE_CAT"),
                set.getString("TABLE_SCHEM"),
                set.getString("TABLE_NAME"),
                set.getString("TABLE_TYPE"),
                set.getString("REMARKS")
        ));
    }
    set.close();
}

@Override
public void test(Connection connection) throws SQLException {
    createTemporaryTable(connection);
    showTables(connection);
}
</code>```

Expected result is writing the T1 table meta data into the out stream. But nothing happens, and it seems that getTables() does not take into account the temporary tables. Don't know how I can resolve it... Is a work-around there? Your help is really very appreciated. Thanks a lot in advance.

答: MySQL sometimes does not provide support even for stupid things. There is no solution for the issue. Closed.</p>

ContentLicense: CC BY-SA 2.5

Body:
And once again I have found an issue that I don't know how to fight with. Let's assume we have the following testing code:

private static final String CREATE_TEMPORARY_TABLE =
        "CREATE TEMPORARY TABLE T1 (\n" +
        "\tA FLOAT(4, 1),\n" +
        "\tB FLOAT(5, 2),\n" +
        "\tC FLOAT,\n" +
        "\tD INTEGER\n" +
        ") ENGINE = MEMORY;";

private final String[] SHOW_TABLE_TYPES = new String[] {
        //"TABLE",
        "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
};

private void createTemporaryTable(Connection connection) throws SQLException {
    final PreparedStatement statement = connection.prepareStatement(CREATE_TEMPORARY_TABLE);
    statement.execute();
    statement.close();
}

private void showTables(Connection connection) throws SQLException {
    final ResultSet set = connection.getMetaData().getTables(null, null, null, SHOW_TABLE_TYPES);
    while ( set.next() ) {
        out.println(format("%s %s %s %s %s",
                set.getString("TABLE_CAT"),
                set.getString("TABLE_SCHEM"),
                set.getString("TABLE_NAME"),
                set.getString("TABLE_TYPE"),
                set.getString("REMARKS")
        ));
    }
    set.close();
}

@Override
public void test(Connection connection) throws SQLException {
    createTemporaryTable(connection);
    showTables(connection);
}

Expected result is writing the T1 table meta data into the out stream. But nothing happens, and it seems that getTables() does not take into account the temporary tables. Don't know how I can resolve it... Is a work-around there? Your help is really very appreciated. Thanks a lot in advance.


问:
How to insert the values in google spreadheet in android
I have created a google spreadsheet by an android app. Now, I want to enter the values in that spreadsheet by an android app. </p>

答:
you can open the app in android webview and then input the values manually.

here's the snippet for webview

```<code>  setContentView(R.layout.activity_web);
  String url="Google spreadsheet url here";

    initWebView();

    webView.loadUrl(url);
</code>```

with the right url it will open the spreadsheet, now you may do whatever you want!

PS- if this does not answer your question please be more specific.

Body:
you can open the app in android webview and then input the values manually.

here's the snippet for webview

  setContentView(R.layout.activity_web);
  String url="Google spreadsheet url here";

    initWebView();

    webView.loadUrl(url);

with the right url it will open the spreadsheet, now you may do whatever you want!

PS- if this does not answer your question please be more specific.


问:
Understanding the condition for age validation logic
I am trying to calculate the age of the person based on the date of birth and doing some logic if its over 18 years. I had my code written and it was working fine, but I stumbled upon a code I found online and I am not getting one condition in that. The code is:

```<code>public class AgeValidation {
public static void main(String[] args) {
    getAge("29-12-1999");
}

private static void getAge(String dob1) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    Date dob;
    try {
        dob = format.parse(dob1);
        Calendar dob2 = Calendar.getInstance();
        dob2.setTime(dob);
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - dob2.get(Calendar.YEAR);

        if(dob2.after(today)) {
            System.out.println("Future date not allowed");
            System.exit(0);
        }

        if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH)) {
            System.out.println("First if condition");
            age--;
        } else if (today.get(Calendar.MONTH) == dob2.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) < dob2.get(Calendar.DAY_OF_MONTH)) {
            System.out.println("else if condition");
            age--;
        }

        if (age < 18) {
            System.out.println(age);
            System.out.println("Underage");
        } else {
            System.out.println(age);
            System.out.println("18 years");
            //Some logic
        }
    } catch (ParseException e) {

        e.printStackTrace();
    }
}
}
</code>```

Need addressing on below points:

I have added a condition if DOB year is after Current year it should not proceed.

```<code>if(dob2.after(today)) {
    System.out.println("Future date not allowed");
    System.exit(0);
}
</code>```

Is it correct to use System.exit(0); or is there some better approach to stop further execution.

In the code that I found online I saw a condition as

```<code>` if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH))`
</code>```

I am not getting in which scenario will this be executed.

Is there any use case in which this code will not work (I cannot think of any)

答:
I am giving you a solution which doesn't take care of leap year logic. But you can build upon this approach.</p>

```<code>public static void main(String[] args) throws Exception{
    String date ="11_10_1991";

    SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_yyyy");
    Date birthDate = sdf.parse(date);

    long ageInMillis = System.currentTimeMillis() - birthDate.getTime();

    long years = ageInMillis /(365 * 24*60*60*1000l);

    long leftover = ageInMillis %(365 * 24*60*60*1000l);
    long days = leftover/(24*60*60*1000l);

    System.out.println(years);
    System.out.println(days);

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to calculate the age of the person based on the date of birth and doing some logic if its over 18 years. I had my code written and it was working fine, but I stumbled upon a code I found online and I am not getting one condition in that. The code is:

public class AgeValidation {
public static void main(String[] args) {
    getAge("29-12-1999");
}

private static void getAge(String dob1) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    Date dob;
    try {
        dob = format.parse(dob1);
        Calendar dob2 = Calendar.getInstance();
        dob2.setTime(dob);
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - dob2.get(Calendar.YEAR);

        if(dob2.after(today)) {
            System.out.println("Future date not allowed");
            System.exit(0);
        }

        if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH)) {
            System.out.println("First if condition");
            age--;
        } else if (today.get(Calendar.MONTH) == dob2.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) < dob2.get(Calendar.DAY_OF_MONTH)) {
            System.out.println("else if condition");
            age--;
        }

        if (age < 18) {
            System.out.println(age);
            System.out.println("Underage");
        } else {
            System.out.println(age);
            System.out.println("18 years");
            //Some logic
        }
    } catch (ParseException e) {

        e.printStackTrace();
    }
}
}

Need addressing on below points:

I have added a condition if DOB year is after Current year it should not proceed.

if(dob2.after(today)) {
    System.out.println("Future date not allowed");
    System.exit(0);
}

Is it correct to use System.exit(0); or is there some better approach to stop further execution.

In the code that I found online I saw a condition as

` if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH))`

I am not getting in which scenario will this be executed.

Is there any use case in which this code will not work (I cannot think of any)

Body:
I am giving you a solution which doesn't take care of leap year logic. But you can build upon this approach.

public static void main(String[] args) throws Exception{
    String date ="11_10_1991";

    SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_yyyy");
    Date birthDate = sdf.parse(date);

    long ageInMillis = System.currentTimeMillis() - birthDate.getTime();

    long years = ageInMillis /(365 * 24*60*60*1000l);

    long leftover = ageInMillis %(365 * 24*60*60*1000l);
    long days = leftover/(24*60*60*1000l);

    System.out.println(years);
    System.out.println(days);

}


问:
Removing string using "preg_replace"
I want to remove some html/js tag using "preg_replace". Here's my html tag:

```<code><style type=text/css>' );document.write( '@media Print' );document.write( '{' );document.write( 'BODY {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TABLE {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TR {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TD {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( '}' );document.write( '</style>' );
</code>```

I want to remove tags from ' );.

My code is like this:

$result3 = preg_replace("(\

答:
You need to use preg_replace like below (Tested Offline):

```<code><?php
$string = "another text above here";
$string .= "<style type=text/css>' );document.write( '@media Print' );document.write( '{' );document.write( 'BODY {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TABLE {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TR {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TD {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( '}' );document.write( '</style>' );";

$string = preg_replace("/<!--.*?-->/", "", $string);
$string = preg_replace("/\([^)]+\)/","",$string);

echo $string;
?>

// Below Output will come
another text above here
</code>```

Title: Removing string using "preg_replace"

Body:
I want to remove some html/js tag using "preg_replace". Here's my html tag:

' );

I want to remove tags from ' );.

My code is like this:

$result3 = preg_replace("(\

Body:
You need to use preg_replace like below (Tested Offline):

<?php
$string = "another text above here";
$string .= "<style type=text/css>' );document.write( '@media Print' );document.write( '{' );document.write( 'BODY {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TABLE {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TR {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TD {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( '}' );document.write( '</style>' );";

$string = preg_replace("/<!--.*?-->/", "", $string);
$string = preg_replace("/\([^)]+\)/","",$string);

echo $string;
?>

// Below Output will come
another text above here


问:
Why col-4 and col-8 are not in the same line without any CSS?

I have two columns, col-4 and col-8 inside col-12 and row. But the two columns are not in the same row. I am not able to understand why this is happening even when I am not writing any CSS just the bootstrap grid.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

Home

About

Portfolio

Contact

```

答:
The additional parent container of 12 grid is not needed.

The div which is required to remove

```<code><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
</code>```

Also, attached working demo with snippet

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />

Home

About

Portfolio

Contact

```

Body:
The additional parent container of 12 grid is not needed.

The div which is required to remove

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

Also, attached working demo with snippet

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div class="row" id="first_row">
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
      <img src="img/nahid.jpg" class="img-fluid" alt="Responsive image" id="avater_main">
    </div>
    <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
      <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Home</div>
      <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">About</div>
      <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Portfolio</div>
      <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Contact</div>
    </div>
  </div>
</div>


问:
Time Complexity of Fibonacci Algorithm
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)</p>

```<code>public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}
</code>```

答:
O(2^n)?  I see only O(n) here.

I wonder why you'd continue to calculate and re-calculate these?  Wouldn't caching the ones you have be a good idea, as long as the memory requirements didn't become too odious?

Since they aren't changing, I'd generate a table and do lookups if speed mattered to me.

Title: Time Complexity of Fibonacci Algorithm

Body:
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)

public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}


问:
Converting unicode not working in c#
I am trying to convert unicode character in c# but it is not working

code:

```<code>using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Uri.UnescapeDataString(unicode);

            Console.WriteLine (str);
        }
    }
}
</code>```

Ouput:

```<code>Not Your Boyfriend's Tunic
</code>```

But expected output is this

Expected output:

```<code>Not Your Boyfriend's Tunic
</code>```

答:
Both solutions will work for you:

Using Server.HtmlDecode:

```<code> string unicode = "Not Your Boyfriend's Tunic";
 string str = Server.HtmlDecode(unicode);
 Console.WriteLine (str);
</code>```

reference link: This MSDN document.

Using HttpUtility.HtmlDecode:
hello

```<code>string unicode = "Not Your Boyfriend's Tunic";
string str = HttpUtility.HtmlDecode(unicode);
Console.WriteLine (str);
</code>```

reference link: This MSDN document.

Difference between both:

Both does same work but the only difference is: Server.HtmlDecode() is readily availalble at runtime from a web page whereas HttpUtility.HtmlDecode() is a static method that can be used from anywhere.

Title: Converting unicode not working in c#

Body:
I am trying to convert unicode character in c# but it is not working

code:

using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Uri.UnescapeDataString(unicode);

            Console.WriteLine (str);
        }
    }
}

Ouput:

Not Your Boyfriend's Tunic

But expected output is this

Expected output:

Not Your Boyfriend's Tunic

Body:
Both solutions will work for you:

Using Server.HtmlDecode:

 string unicode = "Not Your Boyfriend&#39;s Tunic";
 string str = Server.HtmlDecode(unicode);
 Console.WriteLine (str);

reference link: This MSDN document.

Using HttpUtility.HtmlDecode:
hello

string unicode = "Not Your Boyfriend&#39;s Tunic";
string str = HttpUtility.HtmlDecode(unicode);
Console.WriteLine (str);

reference link: This MSDN document.

Difference between both:

Both does same work but the only difference is: Server.HtmlDecode() is readily availalble at runtime from a web page whereas HttpUtility.HtmlDecode() is a static method that can be used from anywhere.


问:
I am looking to create instances of a class from user input
I Have this class:

class Bowler:

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)
```

<p>I need to get user input until a blank line is entered. Then use the data I got to create instances of a class. I was thinking something like:</p>

```def getData():
    name, score = input("Please enter your credentails (Name score): ").split()
    B1 = Bowler(name, score)
    print(B1.nameScore())
```

But then I would somehow have to loop it until I get a blank user input. Also I would somehow have to create B2 B3 B4 etc in the loop.

Sorry I am still really new to programming, maybe I am looking at this from the wrong angle.

答:
What you're looking for are Python Lists. With these you will be able to keep track of your newly created items while running the loop. To create a list we simply defined it like so:

our_bowlers = []
```

<p>Now we need to alter our <code>getData</code> function to return either <code>None</code> or a new <code>Bowler</code>:</p>

<pre class="lang-py prettyprint-override"><code>def getData():
    # Get the input
    our_input = input("Please enter your credentails (Name score): ").split()

    # Check if it is empty
    if our_input == '':
        return None

    # Otherwise, we split our data and create the Bowler
    name, score = our_input.split()
    return Bowler(name, score)
</code>```

and then we can run a loop, check for a new Bowler and if we didn't get anything, we can print all the Bowlers we created:

# Get the first line and try create a Bowler
bowler = getData()

# We loop until we don't have a valid Bowler
while bowler is not None:

    # Add the Bowler to our list and then try get the next one
    our_bowlers.append(bowler)
    bowler = getData()

# Print out all the collected Bowlers
for b in our_bowlers:
    print(b.nameScore())
```

Body:
I Have this class:

class Bowler:

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)

I need to get user input until a blank line is entered. Then use the data I got to create instances of a class. I was thinking something like:

def getData():
    name, score = input("Please enter your credentails (Name score): ").split()
    B1 = Bowler(name, score)
    print(B1.nameScore())

But then I would somehow have to loop it until I get a blank user input. Also I would somehow have to create B2 B3 B4 etc in the loop.

Sorry I am still really new to programming, maybe I am looking at this from the wrong angle.

Body:
What you're looking for are Python Lists. With these you will be able to keep track of your newly created items while running the loop. To create a list we simply defined it like so:

our_bowlers = []

Now we need to alter our getData function to return either None or a new Bowler:

def getData():
    # Get the input
    our_input = input("Please enter your credentails (Name score): ").split()

    # Check if it is empty
    if our_input == '':
        return None

    # Otherwise, we split our data and create the Bowler
    name, score = our_input.split()
    return Bowler(name, score)

and then we can run a loop, check for a new Bowler and if we didn't get anything, we can print all the Bowlers we created:

# Get the first line and try create a Bowler
bowler = getData()

# We loop until we don't have a valid Bowler
while bowler is not None:

    # Add the Bowler to our list and then try get the next one
    our_bowlers.append(bowler)
    bowler = getData()

# Print out all the collected Bowlers
for b in our_bowlers:
    print(b.nameScore())


问:
Visual studio 2012 tf command not working in logged off state
I'm using visual studio 2012 and tfs to do my development When I try to get the latest files using get command in tf.exe through batch in a logged off state, below error is shown.Where else running the batch manually in logged in state gets the latest file. Could anyone please help me on this regard. Thanks in advance

TF30063: You are not authorized to access

What I have tried:

I have tried to turn on alternate authentication credential also,
tried with correct -login:credentials

答:
Update

You have to use an Active Directory account for on-premise TFS -- you can't directly provide a hotmail account.

According to the error info, you need to specific credentials  with the command in the batch script.

Use /login option to specify credentials when running a command

Use the /login option to specify the Team Foundation Server user
  account to run a command. This option can be useful when you are
  working at the machine of another team member.

For example:

```<code>c:\code\SiteApp\Main\SolutionA\Project1>tf get program.cs  /login:JuliaI,JuliaPassword
</code>```

Body:
Update

You have to use an Active Directory account for on-premise TFS -- you can't directly provide a hotmail account.

According to the error info, you need to specific credentials  with the command in the batch script.

Use /login option to specify credentials when running a command

Use the /login option to specify the Team Foundation Server user
  account to run a command. This option can be useful when you are
  working at the machine of another team member.

For example:

c:\code\SiteApp\Main\SolutionA\Project1>tf get program.cs  /login:JuliaI,JuliaPassword


问:
Joining 3 tables and adding a total column in MySQL
I have three tables in a MySQL database

Table 1(vendors) contains all of my vendors

Table 2(puchaseorders) contains all of my purchaseorders and with a common column being 'vendor'

Table 3 contains all of the individual items from those orders with a common column being purchase_order

In the vendors table I have a historical balance that I want to add the running total to.

This is what I have right now. It works perfect but it only returns the vendors that are in the purchaseorders table.

I want to return all of the vendors in the vendors table. If there isn't a "running_total" don't do anything to the balance.

```<code>SELECT *, vendors.balance + vend.running_total AS total FROM vendors
INNER JOIN
(SELECT vendor, SUM(orderhistory.qty_received *
orderhistory.estimated_price) AS running_total FROM orderhistory
INNER JOIN purchaseorders ON
orderhistory.purchase_order=purchaseorders.purchase_order
GROUP BY purchaseorders.vendor) AS vend ON vend.vendor=vendors.vendor;
</code>```

答:
You can change the join outside to left join and use a coalesce around vend.running_total field so that it is treated as 0 if it is not present in the inner table and as a non-zero value if present. Try:

```<code>SELECT *, vendors.balance + COALESCE(vend.running_total,0) AS total
FROM vendors
LEFT JOIN
(SELECT vendor, SUM(orderhistory.qty_received * orderhistory.estimated_price) AS running_total
FROM orderhistory INNER JOIN purchaseorders
ON orderhistory.purchase_order = purchaseorders.purchase_order
GROUP BY purchaseorders.vendor) AS vend
ON vend.vendor=vendors.vendor;
</code>```

Body:
I have three tables in a MySQL database

Table 1(vendors) contains all of my vendors

Table 2(puchaseorders) contains all of my purchaseorders and with a common column being 'vendor'

Table 3 contains all of the individual items from those orders with a common column being purchase_order

In the vendors table I have a historical balance that I want to add the running total to.

This is what I have right now. It works perfect but it only returns the vendors that are in the purchaseorders table.

I want to return all of the vendors in the vendors table. If there isn't a "running_total" don't do anything to the balance.

SELECT *, vendors.balance + vend.running_total AS total FROM vendors
INNER JOIN
(SELECT vendor, SUM(orderhistory.qty_received *
orderhistory.estimated_price) AS running_total FROM orderhistory
INNER JOIN purchaseorders ON
orderhistory.purchase_order=purchaseorders.purchase_order
GROUP BY purchaseorders.vendor) AS vend ON vend.vendor=vendors.vendor;

Body:
You can change the join outside to left join and use a coalesce around vend.running_total field so that it is treated as 0 if it is not present in the inner table and as a non-zero value if present. Try:

SELECT *, vendors.balance + COALESCE(vend.running_total,0) AS total
FROM vendors
LEFT JOIN
(SELECT vendor, SUM(orderhistory.qty_received * orderhistory.estimated_price) AS running_total
FROM orderhistory INNER JOIN purchaseorders
ON orderhistory.purchase_order = purchaseorders.purchase_order
GROUP BY purchaseorders.vendor) AS vend
ON vend.vendor=vendors.vendor;


问:
Azure ARM Template to deploy website with cname and certificate
I'm trying to build a custom ARM template that deploys a new resource group (web,sql,redis,storage) that also creates a custom CNAME record in our dnsZone hosted in a different/existing resGroup.  Finally, I'd like to add a certificate binding (wildcard) from our KeyVault also stored in the other resGroup.

It seems there is support for adding a zone in the new resGroup, but can't find example of leveraging existing zone and just adding a CNAME record that points to my new web app.

It also seems there are examples of creating Key Vaults, but not binding a site up to an existing cert in an existing vault in a different resGroup.

This is a very common multi-tenant kind of scenario, sure seems it should be possible in our template, without having to rely on PowerShell or Azure CLI.

答:
Just wrap your dnsZone resource with a deployment resource and scope it to another group.

```<code>{
    "apiVersion": "2017-05-10",
    "name": "nestedTemplate",
    "type": "Microsoft.Resources/deployments",
    "resourceGroup": %%% resource group name goes here %%%,
    "properties": {
        "mode": "Incremental",
        "template": {
            "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
            "contentVersion": "1.0.0.0",
            "parameters": {},
            "variables": {},
            "resources": [
                %%%% dnsZone goes here %%%
            ]
        },
        "parameters": {}
    }
}
</code>```

For the KV, you can use the example from the quickstarts:

https://github.com/Azure/azure-quickstart-templates/blob/master/webapp-keyvault-ssl/azuredeploy.json

Body:
Just wrap your dnsZone resource with a deployment resource and scope it to another group.

{
    "apiVersion": "2017-05-10",
    "name": "nestedTemplate",
    "type": "Microsoft.Resources/deployments",
    "resourceGroup": %%% resource group name goes here %%%,
    "properties": {
        "mode": "Incremental",
        "template": {
            "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
            "contentVersion": "1.0.0.0",
            "parameters": {},
            "variables": {},
            "resources": [
                %%%% dnsZone goes here %%%
            ]
        },
        "parameters": {}
    }
}

For the KV, you can use the example from the quickstarts:

https://github.com/Azure/azure-quickstart-templates/blob/master/webapp-keyvault-ssl/azuredeploy.json


问:
How powerful is OpenGL?
I want to create an application which will capture one by camera and will manipulate the live images taken by it in milliseconds of the time.

The goal is that the application should change my clothes with some other clothes which I will supply.

I have few questions:

Does OpenGL have such power of modifying live images in a way it will change my clothes in the computer image? I will be moving my hands and the like, can it be that accurate so it'll just look like I am in changed clothes and not the original I am wearing?

答:
I think the question is more about the power of today's graphics cards (GPUs) than about OpenGL. OpenGL is just an API for accessing the GPU power.

The GPUs are very powerful today (see my favorite and already a bit outdated chart) and I think that they can handle the task you want from them quick enough.

Your objective is very (very) ambitious - you will need to modify the computer vision algorithms to work well on GPUs (parallelize them) and use them to detect segments with clothing and then replace those segments. Any of these tasks would suffice for a master thesis.

OpenGL can help you do the job but you have to code all the algorithms yourself using shaders (in GLSL) and rendering to texture.

Unlike others, I wouldn't recommend using OpenCV as it has some serious disadvantages for your use:

It is slow and you won't achieve interactive framerates for your task unless you have a very powerful CPU

It doesn't use the GPU power (at least the stable version)

The API is unintuitive - OpenCV is more a list of implemented CV algorithms than a framework. You still need to know how the algorithms work under the hood to use it properly.

Title: How powerful is OpenGL?


问:
Prometheus/ create list of tag from __meta_gce_tags
Im using relabeling in order to take the gce tag to Prometheus labels, by using the following code in Prometheus yml:

```<code> relabel_configs:
  - source_labels: [__meta_gce_tags]
    target_label: tags
</code>```

the tags look like this:

```<code>tags=",node_a,node_prod,node_centos,"
</code>```

The problem is that it gives a string list, while I wish to have list of tags so I can query it. for example, instead of using:

```<code>sum(elasticsearch_node_stats_up{tags=~".*?noda_a.*node_prod.?"})
</code>```

I will be able to use it without regex. Is there any way to do it?

答:
You can use regex to extract values from a label value during relabeling. So try this, which is not exactly DRY, but works:

```<code>relabel_configs:
  - source_labels: [__meta_gce_tags]
    regex: ",node_([a-z]+),node_[a-z]+,node_[a-z]+"
    target_label: node
    replacement: '${1}'
  - source_labels: [__meta_gce_tags]
    regex: ",node_[a-z]+,node_([a-z]+),node_[a-z]+"
    target_label: env
    replacement: '${1}'
  - source_labels: [__meta_gce_tags]
    regex: "",node_[a-z]+,node_[a-z]+,node_([a-z]+)""
    target_label: os
    replacement: '${1}'
</code>```

Note that there is probably a much more elegant regular expression to use.

If you can control the label values, here is a much more durable technique: https://www.robustperception.io/extracting-full-labels-from-consul-tags/

Body:
Im using relabeling in order to take the gce tag to Prometheus labels, by using the following code in Prometheus yml:

 relabel_configs:
  - source_labels: [__meta_gce_tags]
    target_label: tags

the tags look like this:

tags=",node_a,node_prod,node_centos,"

The problem is that it gives a string list, while I wish to have list of tags so I can query it. for example, instead of using:

sum(elasticsearch_node_stats_up{tags=~".*?noda_a.*node_prod.?"})

I will be able to use it without regex. Is there any way to do it?

Body:
You can use regex to extract values from a label value during relabeling. So try this, which is not exactly DRY, but works:

relabel_configs:
  - source_labels: [__meta_gce_tags]
    regex: ",node_([a-z]+),node_[a-z]+,node_[a-z]+"
    target_label: node
    replacement: '${1}'
  - source_labels: [__meta_gce_tags]
    regex: ",node_[a-z]+,node_([a-z]+),node_[a-z]+"
    target_label: env
    replacement: '${1}'
  - source_labels: [__meta_gce_tags]
    regex: "",node_[a-z]+,node_[a-z]+,node_([a-z]+)""
    target_label: os
    replacement: '${1}'

Note that there is probably a much more elegant regular expression to use.

If you can control the label values, here is a much more durable technique: https://www.robustperception.io/extracting-full-labels-from-consul-tags/


问:
Image resizes after async download AFNetworking UiTableView
i have implemented AFNetworking to async download the images to my table, everything works fine, but when i scroll down the table the image in the cell shrinks.

my code look like this:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSDictionary *dictionary = [self.json objectAtIndex:indexPath.row];
    cell.textLabel.text=[dictionary objectForKey:@"name"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"description"];

    NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    NSURL *url = [NSURL URLWithString:ruta];
    [cell.imageView setImageWithURL:url
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    return cell;
}
</code>```

here are some screenshots:

picture 1

picture 2

any tips will be vary apreciate.
regards.

答: go to cell and set uiimageview proper constraints like uiimageview hight and with</p>

Body:
i have implemented AFNetworking to async download the images to my table, everything works fine, but when i scroll down the table the image in the cell shrinks.

my code look like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSDictionary *dictionary = [self.json objectAtIndex:indexPath.row];
    cell.textLabel.text=[dictionary objectForKey:@"name"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"description"];

    NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    NSURL *url = [NSURL URLWithString:ruta];
    [cell.imageView setImageWithURL:url
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    return cell;
}

here are some screenshots:

picture 1

picture 2

any tips will be vary apreciate.
regards.


问:
How to change width of image css on the basis of portrait and landscape image
Implemented a logo in the box, where width should be 100% if the image is in portrait or square orientation and width should be auto if the image is in landscape orientation.</p>

答:
You can use media queries for this

```<code>@media (orientation: landscape) {
  img {
    width: auto;
  }
}

@media (orientation: portrait) {
  img {
    width: 100%;
  }
}
</code>```

Hope this may help you.

DEMO

@media (orientation: landscape) {
  img {
    width: auto;
  }
}

@media (orientation: portrait) {
  img {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://static.pexels.com/photos/371633/pexels-photo-371633.jpeg"></code>```

Body:
You can use media queries for this

@media (orientation: landscape) {
  img {
    width: auto;
  }
}

@media (orientation: portrait) {
  img {
    width: 100%;
  }
}

Hope this may help you.

DEMO

@media (orientation: landscape) {
  img {
    width: auto;
  }
}

@media (orientation: portrait) {
  img {
    width: 100%;
  }
}

<img src="https://static.pexels.com/photos/371633/pexels-photo-371633.jpeg">


问:
Set title background color
In my android application I want the standard/basic title bar to change color.

To change the text color you have setTitleColor(int color), is there a way to change the background color of the bar?

答:
Things seem to have gotten better/easier since Android 5.0 (API level 21).

I think what you're looking for is something like this:

```<code><style name="AppTheme" parent="AppBaseTheme">
    <!-- Top-top notification/status bar color: -->
    <!--<item name="colorPrimaryDark">#000000</item>-->
    <!-- App bar color: -->
    <item name="colorPrimary">#0000FF</item>
</style>
</code>```

See here for reference:

https://developer.android.com/training/material/theme.html#ColorPalette

Title: Set title background color

Body:
Things seem to have gotten better/easier since Android 5.0 (API level 21).

I think what you're looking for is something like this:

<style name="AppTheme" parent="AppBaseTheme">
    <!-- Top-top notification/status bar color: -->
    <!--<item name="colorPrimaryDark">#000000</item>-->
    <!-- App bar color: -->
    <item name="colorPrimary">#0000FF</item>
</style>

See here for reference:

https://developer.android.com/training/material/theme.html#ColorPalette


问:
a jQuery promise that always succeeds?
I have this code jQuery code fragment:

```<code>$.get('/api/' + currentPage).done(function(data) { ... })
                            .fail(...)
</code>```

I want to replace $.get('/api/'+currentPage) with a promise that always succeeds and returns a specific value for data. Something like:

```<code>let myData = { ... }  // value of data I want to pass to the done function

(new AlwaysSucceeds(myData)).done(function(data) { ... })
                            .fail(...)
</code>```

I could cobble up a dummy object, or I could extract out the done function but I want to keep changes to the code to a minimum.

Is there a way to do this?

UPDATE: To help clarify what's going, the code I am working with is (here). Normally this app is served from a nodejs server which implements the /api/... call, but I am converting it to be served
from a static page server. I know what is going to be returned from
the $.get call. To keep changes to the code clean I simply want to
change that line to:

```<code>let myData = {...}

// $.get('/api/' + currentPage) -- comment out the $.get call
(SOMETHINGHERE(myData)).done(function(data) {
</code>```

The SOMETHINGHERE expression needs to implement .done(f)
which will call the function f with myData and then return
some object which implements .fail(...) which does nothing.

答:
It's not clear what you actually want but be carufull using jQuery Deferred with native promises, the deferred has some non standard methods that native promises don't have.

So to be save I always assume there is a thenable, something that has a then with that you can pretty much do whatever you want.

jQuery Deferred do not behave like native promises either (depending on version):

```<code>$.Deferred().reject("hello world")
.then(
  undefined
  ,x=>x
)
.then(
  x=>console.log("Never happens",x)
)

Promise.reject("hello world")
.then(
  undefined
  ,x=>x
);
.then(
  x=>console.log("Well behaved",x)
);

Promise.resolve().then(x=>{throw "nope"})
.then(undefined,err=>console.warn(err));

$.Deferred().resolve().then(x=>{throw "nope"})//crashes
.then(undefined,err=>err);
</code>```

So it will be saver to use native promises and polyfill with something that behaves like native.

To answer the question about non failing promise, if you want to make a request but return a default when it rejects and keep returning the same once resolves or rejects you can do:

```<code>const get = (p=>{
  (url) => {
    p = p ||
    //return native promise or properly polyfilled one
    Promise.resolve($.get(url))
    .then(
      undefined,
      _=> {defaultobject:true}
    );
    return p;
  }
})();
</code>```

Your get function will return a native promise so no fail, done and other things that are non standard. Combining "promises" from different libraries and native promises it would be best to only use then

Title: a jQuery promise that always succeeds?

Body:
I have this code jQuery code fragment:

$.get('/api/' + currentPage).done(function(data) { ... })
                            .fail(...)

I want to replace $.get('/api/'+currentPage) with a promise that always succeeds and returns a specific value for data. Something like:

let myData = { ... }  // value of data I want to pass to the done function

(new AlwaysSucceeds(myData)).done(function(data) { ... })
                            .fail(...)

I could cobble up a dummy object, or I could extract out the done function but I want to keep changes to the code to a minimum.

Is there a way to do this?

UPDATE: To help clarify what's going, the code I am working with is (here). Normally this app is served from a nodejs server which implements the /api/... call, but I am converting it to be served
from a static page server. I know what is going to be returned from
the $.get call. To keep changes to the code clean I simply want to
change that line to:

let myData = {...}

// $.get('/api/' + currentPage) -- comment out the $.get call
(SOMETHINGHERE(myData)).done(function(data) {

The SOMETHINGHERE expression needs to implement .done(f)
which will call the function f with myData and then return
some object which implements .fail(...) which does nothing.

Body:
It's not clear what you actually want but be carufull using jQuery Deferred with native promises, the deferred has some non standard methods that native promises don't have.

So to be save I always assume there is a thenable, something that has a then with that you can pretty much do whatever you want.

jQuery Deferred do not behave like native promises either (depending on version):

$.Deferred().reject("hello world")
.then(
  undefined
  ,x=>x
)
.then(
  x=>console.log("Never happens",x)
)

Promise.reject("hello world")
.then(
  undefined
  ,x=>x
);
.then(
  x=>console.log("Well behaved",x)
);

Promise.resolve().then(x=>{throw "nope"})
.then(undefined,err=>console.warn(err));

$.Deferred().resolve().then(x=>{throw "nope"})//crashes
.then(undefined,err=>err);

So it will be saver to use native promises and polyfill with something that behaves like native.

To answer the question about non failing promise, if you want to make a request but return a default when it rejects and keep returning the same once resolves or rejects you can do:

const get = (p=>{
  (url) => {
    p = p ||
    //return native promise or properly polyfilled one
    Promise.resolve($.get(url))
    .then(
      undefined,
      _=> {defaultobject:true}
    );
    return p;
  }
})();

Your get function will return a native promise so no fail, done and other things that are non standard. Combining "promises" from different libraries and native promises it would be best to only use then


问:
How to get Running Total in MS Access query
I need help on how to code this on MS Access SQL Query Builder

Get the Running total of the points like below

sum the pts that is older than the current date then check if there is a reduce pts and subtract that to the total applicable only to those older than the reduce pts and will return 0 if reduce is greater than current running.

I have no idea on how to get the reduce pts work

edited Question:

I just need to make the November 23 running to be 1 instead of 0.5

答:
One way to do this is via a correlated subquery:</p>

```<code>SELECT
    [Emp ID], Date, Pts, Reduce,
    (SELECT IIF(SUM(IIF(t2.Pts IS NULL, 0, t2.Pts) -
                    IIF(t2.Reduce IS NULL, 0, t2.Reduce)) < 0, 0,
                SUM(IIF(t2.Pts IS NULL, 0, t2.Pts) -
                    IIF(t2.Reduce IS NULL, 0, t2.Reduce))
     FROM yourTable t2
     WHERE t2.Date <= t1.Date) Running
FROM yourTable t1;
</code>```

Body:
One way to do this is via a correlated subquery:

SELECT
    [Emp ID], Date, Pts, Reduce,
    (SELECT IIF(SUM(IIF(t2.Pts IS NULL, 0, t2.Pts) -
                    IIF(t2.Reduce IS NULL, 0, t2.Reduce)) < 0, 0,
                SUM(IIF(t2.Pts IS NULL, 0, t2.Pts) -
                    IIF(t2.Reduce IS NULL, 0, t2.Reduce))
     FROM yourTable t2
     WHERE t2.Date <= t1.Date) Running
FROM yourTable t1;


问:
css/sass :not(:first-of-type) not working, is hiding all elements of type
I have a sass block that i have tried several different ways:

I've tried this:

```<code>.progress-body {
    display: none;
    &:first-of-type {
        display: block;
    }
}
</code>```

and this:

```<code>.progress-body {
    &:not(:first-of-type) {
        display: none;
    }
}
</code>```

and this:

```<code>.progress-body:not(:first-of-type) {
    display: none;
}
</code>```

when applied to HTML that looks like this:

```<code><div class="panel">
    <div class="panel-heading">
    </div>
    <div class="panel-body progress-body">
            <div class="row">
                <div class="col-md-12">
                    <p class="lead">Step 1: Choose your template...</p>
                </div>
            </div>
    </div>
    <div class="panel-body progress-body">
            <div class="row">
                <div class="col-md-12">
                    <p class="lead">Step 2: Compose your email...</p>
                </div>
            </div>
    </div>
</div>
</code>```

the result is that it hides all the elements with the progress-body class. This is normally  pretty straight forward CSS so no idea what is wrong here...

答:
If you can't wrap as UncaughtTypeError wrote in his answer, youcan use (general) sibling selectors.

```<code>.progress-body + .progress-body {display: none;}
</code>```

or

```<code>.progress-body ~ .progress-body {display: none;}
</code>```

I expect the first is block by default, if you didn't change it elsewhere.

Body:
I have a sass block that i have tried several different ways:

I've tried this:

.progress-body {
    display: none;
    &:first-of-type {
        display: block;
    }
}

and this:

.progress-body {
    &:not(:first-of-type) {
        display: none;
    }
}

and this:

.progress-body:not(:first-of-type) {
    display: none;
}

when applied to HTML that looks like this:

Step 1: Choose your template...

Step 2: Compose your email...

the result is that it hides all the elements with the progress-body class. This is normally  pretty straight forward CSS so no idea what is wrong here...

Body:
If you can't wrap as UncaughtTypeError wrote in his answer, youcan use (general) sibling selectors.

.progress-body + .progress-body {display: none;}

or

.progress-body ~ .progress-body {display: none;}

I expect the first is block by default, if you didn't change it elsewhere.


问:
Rounded corner in Chrome - extraneous lines in corners
I am cracking my head over what causes the extraneous lines that show up around rounded corners in Chrome, IE a Safari. It does not happen in FF.

div.round-box {
  border-bottom: 1px solid #b3b3b3;
  height: 20px;
  margin-bottom: 15px;
  text-align: center;
  width: 100%;
}

div.round-box .steps {
  background-color: #0fa862;
  border: 20px solid white;
  border-radius: 32px;
  color: white;
  font-size: 1.7em;
  padding: 15px 25px;
  position: relative;
  outline: none;
  text-decoration: none;
  top: 10px;
  white-space: nowrap;
  -webkit-border-radius: 32px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="round-box">
  Follow 5 Easy Steps to Install XYZ
</div></code>```

Many thanks for any hints.

答:
This one is really helpful:

Add background-clip: padding-box;

to .steps

Body:
I am cracking my head over what causes the extraneous lines that show up around rounded corners in Chrome, IE a Safari. It does not happen in FF.

div.round-box {
  border-bottom: 1px solid #b3b3b3;
  height: 20px;
  margin-bottom: 15px;
  text-align: center;
  width: 100%;
}

div.round-box .steps {
  background-color: #0fa862;
  border: 20px solid white;
  border-radius: 32px;
  color: white;
  font-size: 1.7em;
  padding: 15px 25px;
  position: relative;
  outline: none;
  text-decoration: none;
  top: 10px;
  white-space: nowrap;
  -webkit-border-radius: 32px;
}

  Follow 5 Easy Steps to Install XYZ

Many thanks for any hints.


问:
How can I display the three level div in turn by using z-index?
The html code is as follow:

```<code><div class="first common">
    i am the first div.
    <div class="second common">
        i am the second div.
        <div class="third common">
            i am the third div.
        </div>
    </div>
</div>
</code>```

css:

```<code>.common {
    position: absolute;
    left: 50px;
    top: 50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #8EE5EE;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #0000AA;
}
</code>```

The results are as follows

And now I want to put the first div in the front, the second div in the middle and the third div at the back (reverse) by using z-index if I could .
But I don't know how to do.

答:
```<code><div class="common">
    <div class="first">i am the first div.</div>
    <div class="second">i am the second div.</div>
    <div class="third">i am the third div.</div>
</div>

.common {
position: relative;
color: #fff;
}

.first {
position: absolute;
background-color: #8EE5EE;
z-index:1;
left:50px;
top:50px;
width:200px;
height:200px;
}

.second {
background-color: #7A67EE;
position: absolute;
z-index:2;
width:200px;
height:200px;
left:100px;
top:100px;
}

.third {
background-color: #0000AA;
position: absolute;
z-index:3;
left:150px;
top:150px;
width:200px;
height:200px;
}
</code>```

Body:
The html code is as follow:

    i am the first div.

        i am the second div.

            i am the third div.

css:

.common {
    position: absolute;
    left: 50px;
    top: 50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #8EE5EE;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #0000AA;
}

The results are as follows

And now I want to put the first div in the front, the second div in the middle and the third div at the back (reverse) by using z-index if I could .
But I don't know how to do.


问:
Custom Post Type - Get posts by category
I am using the following code to return all posts from my custom post type "portfolio".

```<code><?php global $wp_query;

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array('post_type' => 'portfolio', 'posts_per_page' => 3, 'paged' => $paged);

$wp_query = new WP_Query($args); ?> ...
</code>```

On other pages i would like to return posts by a category of my custom post type, of which i have created a taxonomy for. I am using the following code below but still returning all custom posts.

```<code><?php global $wp_query;

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array('post_type' => 'portfolio', 'taxonomy' => 'portfolio_categories', 'category' => '5', 'posts_per_page' => 3, 'paged' => $paged);

$wp_query = new WP_Query($args); ?>
</code>```

Any help or direction would be appreciated.

答:
You should use tax_query if you want to list the posts under a category:</p>

```<code> $args = array(
        'posts_per_page'  =>  3,
        'tax_query' => array(
        array(
                'taxonomy' => 'portfolio_categories',
                'terms' => '5'
            ),
         ),
        'post_type'        => 'portfolio',
        'post_status'      => 'publish'
        );
</code>```

Body:
I am using the following code to return all posts from my custom post type "portfolio".

<?php global $wp_query;

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array('post_type' => 'portfolio', 'posts_per_page' => 3, 'paged' => $paged);

$wp_query = new WP_Query($args); ?> ...

On other pages i would like to return posts by a category of my custom post type, of which i have created a taxonomy for. I am using the following code below but still returning all custom posts.

<?php global $wp_query;

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array('post_type' => 'portfolio', 'taxonomy' => 'portfolio_categories', 'category' => '5', 'posts_per_page' => 3, 'paged' => $paged);

$wp_query = new WP_Query($args); ?>

Any help or direction would be appreciated.

Body:
You should use tax_query if you want to list the posts under a category:

 $args = array(
        'posts_per_page'  =>  3,
        'tax_query' => array(
        array(
                'taxonomy' => 'portfolio_categories',
                'terms' => '5'
            ),
         ),
        'post_type'        => 'portfolio',
        'post_status'      => 'publish'
        );


问:
Does Bison allow "?" in its syntax
I am trying to write Grammar for java specification
for example:-

```<code>COMPILATION_UNIT: PACKAGE_DEC? IMPORT_DECS? TYPE_DECS?
</code>```

but it doesn't work
I have the following error:

invalid character: `?'

for each question mark I use in my file.y

I know that Bison has special characters and it should handle it

Please help

答:
Bison does not allow a ? meaning that the prior token is optional, you have to write out the grammar with the optional elements:

```<code>package_decl_opt: %empty
| SOME_TOKEN
;
package: package)_dec_opt TOKEN_PACKAGE TOKEN_IDENTIFIER
;
</code>```

would allow both of the following:

```<code>SOME_TOKEN TOKEN_PACKAGE TOKEN_IDENTIFIER
TOKEN_PACKAGE TOKEN_IDENTIFIER
</code>```

Title: Does Bison allow "?" in its syntax

Body:
I am trying to write Grammar for java specification
for example:-

COMPILATION_UNIT: PACKAGE_DEC? IMPORT_DECS? TYPE_DECS?

but it doesn't work
I have the following error:

invalid character: `?'

for each question mark I use in my file.y

I know that Bison has special characters and it should handle it

Please help

Body:
Bison does not allow a ? meaning that the prior token is optional, you have to write out the grammar with the optional elements:

package_decl_opt: %empty
| SOME_TOKEN
;
package: package)_dec_opt TOKEN_PACKAGE TOKEN_IDENTIFIER
;

would allow both of the following:

SOME_TOKEN TOKEN_PACKAGE TOKEN_IDENTIFIER
TOKEN_PACKAGE TOKEN_IDENTIFIER