问:
Slave configuration for listening to messages in spring batch using spring integration
Can I have a job with just the slaves and no master and listen to a rabbitmq queue? I want to listen to a queue and process the messages in chunk oriented manner using spring batch and spring integration in a spring boot app.

I want to use the chunkProcessorChunkHandler configuration explained in the RemoteChunking example for Spring batch by Michael Minella (https://www.youtube.com/watch?v=30Tdp1mfR0g), but without a master configuration.

Below is my configuration for the job.

```<code>@Configuration
@EnableIntegration
public class QueueIntegrationConfiguration {

  @Autowired
  private CassandraItemWriter cassandraItemWriter;
  @Autowired
  private VendorProcessor vendorProcessor;

  @Autowired
  ConnectionFactory connectionFactory;

  @Bean
  public AmqpInboundChannelAdapter inboundChannelAdapter(
      SimpleMessageListenerContainer listenerContainer) {
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    adapter.setOutputChannel(inboundQueueChannel());
    adapter.setAutoStartup(true);

    return adapter;
  }

 @Bean
  public SimpleMessageListenerContainer listenerContainer(ConnectionFactory connectionFactory, MessageConverter jsonMessageConverter) {

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
        connectionFactory);
    container.setQueueNames("ProductStore_Partial");
    container.setAutoStartup(true);
    container.setMessageConverter(jsonMessageConverter);

    return container;
  }

  @Bean
  @ServiceActivator(inputChannel = "ProductStore_Partial")
  public ChunkProcessorChunkHandler chunkProcessorChunkHandler()
      throws Exception {
    SimpleChunkProcessor chunkProcessor = new SimpleChunkProcessor(vendorProcessor,
        cassandraItemWriter);
    chunkProcessor.afterPropertiesSet();

    ChunkProcessorChunkHandler<Vendor> chunkHandler = new ChunkProcessorChunkHandler<>();
    chunkHandler.setChunkProcessor(chunkProcessor);
    chunkHandler.afterPropertiesSet();

    return chunkHandler;
  }

  @Bean
  public QueueChannel inboundQueueChannel() {
    return new QueueChannel().;
  }

}
</code>```

Below is my Application.java class for spring boot.

```<code>@SpringBootApplication
@EnableBatchProcessing
public class BulkImportProductApplication {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(BulkImportProductApplication.class);
    app.setWebEnvironment(false);
    app.run(args).close();
  }

}
</code>```

From what I understand from spring integration, I have an AmqpInboundChannelAdapter for listening to messages from the queue. A ServiceActivator, an inboundQueueChannel, autowired ItemProcessor and ItemWriter. I am not sure what am I missing here.

The batch job starts, consumes one message from the queue and get a cancelOk and my  job terminates without processing the message.

I am also sharing my debug logging if that would help.

```<code>2017-12-04 09:58:49.679  INFO 7450 --- [           main] c.a.s.p.b.BulkImportProductApplication   : Started BulkImportProductApplication in 9.412 seconds (JVM running for 10.39)
2017-12-04 09:58:49.679  INFO 7450 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@31c88ec8: startup date [Mon Dec 04 09:58:40 PST 2017]; root of context hierarchy
2017-12-04 09:58:49.679 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'org.springframework.integration.config.IdGeneratorConfigurer#0'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'inboundChannelAdapter'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'listenerContainer'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'integrationHeaderChannelRegistry'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'org.springframework.amqp.rabbit.config.internalRabbitListenerEndpointRegistry'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean '_org.springframework.integration.errorLogger'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'queueIntegrationConfiguration.chunkProcessorChunkHandler.serviceActivator.handler'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'queueIntegrationConfiguration.chunkProcessorChunkHandler.serviceActivator'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'lifecycleProcessor'
2017-12-04 09:58:49.680  INFO 7450 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Asking bean 'inboundChannelAdapter' of type [class org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter] to stop
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Shutting down Rabbit listener container
2017-12-04 09:58:49.814 DEBUG 7450 --- [pool-1-thread-5] o.s.a.r.listener.BlockingQueueConsumer   : Storing delivery for Consumer@7c52fc81: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035], acknowledgeMode=AUTO local queue size=0
2017-12-04 09:58:49.814 DEBUG 7450 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Received message: (Body:'[B@358a5358(byte[618])' MessageProperties [headers={__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=json, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=NON_PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=ProductStore, receivedRoutingKey=, receivedDelay=null, deliveryTag=2, messageCount=0, consumerTag=amq.ctag-nWGbRxjFiaeTEoZylv6Hrg, consumerQueue=null])
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedDeliveryMode] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_contentEncoding] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedExchange] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_deliveryTag] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[json__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_redelivered] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[contentType] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : preSend on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[618], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_redelivered=false, id=a4868670-240f-ddf2-8a8c-ac4b8d234cdd, amqp_consumerTag=amq.ctag-nWGbRxjFiaeTEoZylv6Hrg, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512410329815}]
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : postSend (sent=true) on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[618], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_redelivered=false, id=a4868670-240f-ddf2-8a8c-ac4b8d234cdd, amqp_consumerTag=amq.ctag-nWGbRxjFiaeTEoZylv6Hrg, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512410329815}]
2017-12-04 09:58:49.853  INFO 7450 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2017-12-04 09:58:49.853 DEBUG 7450 --- [pool-1-thread-6] o.s.a.r.listener.BlockingQueueConsumer   : Received cancelOk for tag amq.ctag-nWGbRxjFiaeTEoZylv6Hrg (null); Consumer@7c52fc81: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035], acknowledgeMode=AUTO local queue size=0
2017-12-04 09:58:49.853 DEBUG 7450 --- [enerContainer-1] o.s.a.r.l.SimpleMessageListenerContainer : Cancelling Consumer@7c52fc81: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035], acknowledgeMode=AUTO local queue size=0
2017-12-04 09:58:49.853 DEBUG 7450 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Closing Rabbit Channel: Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035]
2017-12-04 09:58:49.853 DEBUG 7450 --- [enerContainer-1] o.s.a.r.c.CachingConnectionFactory       : Closing cached Channel: AMQChannel(amqp://admin@xxxx:5672/,2)
2017-12-04 09:58:50.027  INFO 7450 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2017-12-04 09:58:50.027 DEBUG 7450 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Bean 'inboundChannelAdapter' completed its stop procedure
</code>```

What am I missing here? Why is my message getting processed? Please correct me if I'm missing out something here? Also feel free to ask any other configuration that you feel would help analyze the situation here.

EDIT: After removing the code that closes the application context manually( app.run(args).close() ), I was able to receive the messages, but looks like they are lost after a successful retrieve. sharing the debug log for this behavior.

```<code>2017-12-04 14:39:11.297 DEBUG 1498 --- [pool-1-thread-5] o.s.a.r.listener.BlockingQueueConsumer   : Storing delivery for Consumer@7219ac49: tags=[{amq.ctag-Z8siptJMdxGU6sXdOHkVCA=ProductStore_Partial}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@6df20ade Shared Rabbit Connection: SimpleConnection@7ba63fe5 [delegate=amqp://admin@xxxx:5672/, localPort= 51172], acknowledgeMode=AUTO local queue size=0
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Received message: (Body:'[B@347c8f87(byte[624])' MessageProperties [headers={__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=json, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=NON_PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=ProductStore, receivedRoutingKey=, receivedDelay=null, deliveryTag=2, messageCount=0, consumerTag=amq.ctag-Z8siptJMdxGU6sXdOHkVCA, consumerQueue=ProductStore_Partial])
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedDeliveryMode] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_contentEncoding] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedExchange] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_deliveryTag] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[json__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_redelivered] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[contentType] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : preSend on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[624], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_consumerQueue=ProductStore_Partial, amqp_redelivered=false, id=540399a5-62a6-7178-2524-e274bad4ed13, amqp_consumerTag=amq.ctag-Z8siptJMdxGU6sXdOHkVCA, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512427151297}]
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : postSend (sent=true) on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[624], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_consumerQueue=ProductStore_Partial, amqp_redelivered=false, id=540399a5-62a6-7178-2524-e274bad4ed13, amqp_consumerTag=amq.ctag-Z8siptJMdxGU6sXdOHkVCA, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512427151297}]
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Retrieving delivery for Consumer@7219ac49: tags=[{amq.ctag-Z8siptJMdxGU6sXdOHkVCA=ProductStore_Partial}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@6df20ade Shared Rabbit Connection: SimpleConnection@7ba63fe5 [delegate=amqp://admin@xxxx:5672/, localPort= 51172], acknowledgeMode=AUTO local queue size=0
</code>```

This goes on repeating and new messages are consumed, but the messages are not getting processed and written to the data-store using the itemWriter provided. Now come to think of it, since I have not provided the tasklet/step bean reference anywhere in this code, is that something I am missing out here?

答:
app.run(args).close();

You are explicitly closing the application context, which shuts everything down.

Closing org.springframework.context.annotation.AnnotationConfigApplicationContext.

Body:
Can I have a job with just the slaves and no master and listen to a rabbitmq queue? I want to listen to a queue and process the messages in chunk oriented manner using spring batch and spring integration in a spring boot app.

I want to use the chunkProcessorChunkHandler configuration explained in the RemoteChunking example for Spring batch by Michael Minella (https://www.youtube.com/watch?v=30Tdp1mfR0g), but without a master configuration.

Below is my configuration for the job.

@Configuration
@EnableIntegration
public class QueueIntegrationConfiguration {

  @Autowired
  private CassandraItemWriter cassandraItemWriter;
  @Autowired
  private VendorProcessor vendorProcessor;

  @Autowired
  ConnectionFactory connectionFactory;

  @Bean
  public AmqpInboundChannelAdapter inboundChannelAdapter(
      SimpleMessageListenerContainer listenerContainer) {
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    adapter.setOutputChannel(inboundQueueChannel());
    adapter.setAutoStartup(true);

    return adapter;
  }

 @Bean
  public SimpleMessageListenerContainer listenerContainer(ConnectionFactory connectionFactory, MessageConverter jsonMessageConverter) {

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
        connectionFactory);
    container.setQueueNames("ProductStore_Partial");
    container.setAutoStartup(true);
    container.setMessageConverter(jsonMessageConverter);

    return container;
  }

  @Bean
  @ServiceActivator(inputChannel = "ProductStore_Partial")
  public ChunkProcessorChunkHandler chunkProcessorChunkHandler()
      throws Exception {
    SimpleChunkProcessor chunkProcessor = new SimpleChunkProcessor(vendorProcessor,
        cassandraItemWriter);
    chunkProcessor.afterPropertiesSet();

    ChunkProcessorChunkHandler<Vendor> chunkHandler = new ChunkProcessorChunkHandler<>();
    chunkHandler.setChunkProcessor(chunkProcessor);
    chunkHandler.afterPropertiesSet();

    return chunkHandler;
  }

  @Bean
  public QueueChannel inboundQueueChannel() {
    return new QueueChannel().;
  }

}

Below is my Application.java class for spring boot.

@SpringBootApplication
@EnableBatchProcessing
public class BulkImportProductApplication {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(BulkImportProductApplication.class);
    app.setWebEnvironment(false);
    app.run(args).close();
  }

}

From what I understand from spring integration, I have an AmqpInboundChannelAdapter for listening to messages from the queue. A ServiceActivator, an inboundQueueChannel, autowired ItemProcessor and ItemWriter. I am not sure what am I missing here.

The batch job starts, consumes one message from the queue and get a cancelOk and my  job terminates without processing the message.

I am also sharing my debug logging if that would help.

2017-12-04 09:58:49.679  INFO 7450 --- [           main] c.a.s.p.b.BulkImportProductApplication   : Started BulkImportProductApplication in 9.412 seconds (JVM running for 10.39)
2017-12-04 09:58:49.679  INFO 7450 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@31c88ec8: startup date [Mon Dec 04 09:58:40 PST 2017]; root of context hierarchy
2017-12-04 09:58:49.679 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'org.springframework.integration.config.IdGeneratorConfigurer#0'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'inboundChannelAdapter'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'listenerContainer'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'integrationHeaderChannelRegistry'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'org.springframework.amqp.rabbit.config.internalRabbitListenerEndpointRegistry'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean '_org.springframework.integration.errorLogger'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'queueIntegrationConfiguration.chunkProcessorChunkHandler.serviceActivator.handler'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'queueIntegrationConfiguration.chunkProcessorChunkHandler.serviceActivator'
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'lifecycleProcessor'
2017-12-04 09:58:49.680  INFO 7450 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Asking bean 'inboundChannelAdapter' of type [class org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter] to stop
2017-12-04 09:58:49.680 DEBUG 7450 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Shutting down Rabbit listener container
2017-12-04 09:58:49.814 DEBUG 7450 --- [pool-1-thread-5] o.s.a.r.listener.BlockingQueueConsumer   : Storing delivery for Consumer@7c52fc81: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035], acknowledgeMode=AUTO local queue size=0
2017-12-04 09:58:49.814 DEBUG 7450 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Received message: (Body:'[B@358a5358(byte[618])' MessageProperties [headers={__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=json, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=NON_PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=ProductStore, receivedRoutingKey=, receivedDelay=null, deliveryTag=2, messageCount=0, consumerTag=amq.ctag-nWGbRxjFiaeTEoZylv6Hrg, consumerQueue=null])
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedDeliveryMode] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_contentEncoding] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedExchange] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_deliveryTag] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[json__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_redelivered] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[contentType] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : preSend on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[618], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_redelivered=false, id=a4868670-240f-ddf2-8a8c-ac4b8d234cdd, amqp_consumerTag=amq.ctag-nWGbRxjFiaeTEoZylv6Hrg, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512410329815}]
2017-12-04 09:58:49.815 DEBUG 7450 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : postSend (sent=true) on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[618], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_redelivered=false, id=a4868670-240f-ddf2-8a8c-ac4b8d234cdd, amqp_consumerTag=amq.ctag-nWGbRxjFiaeTEoZylv6Hrg, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512410329815}]
2017-12-04 09:58:49.853  INFO 7450 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2017-12-04 09:58:49.853 DEBUG 7450 --- [pool-1-thread-6] o.s.a.r.listener.BlockingQueueConsumer   : Received cancelOk for tag amq.ctag-nWGbRxjFiaeTEoZylv6Hrg (null); Consumer@7c52fc81: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035], acknowledgeMode=AUTO local queue size=0
2017-12-04 09:58:49.853 DEBUG 7450 --- [enerContainer-1] o.s.a.r.l.SimpleMessageListenerContainer : Cancelling Consumer@7c52fc81: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035], acknowledgeMode=AUTO local queue size=0
2017-12-04 09:58:49.853 DEBUG 7450 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Closing Rabbit Channel: Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@26f1249d Shared Rabbit Connection: SimpleConnection@680bddf5 [delegate=amqp://admin@xxxx:5672/, localPort= 65035]
2017-12-04 09:58:49.853 DEBUG 7450 --- [enerContainer-1] o.s.a.r.c.CachingConnectionFactory       : Closing cached Channel: AMQChannel(amqp://admin@xxxx:5672/,2)
2017-12-04 09:58:50.027  INFO 7450 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2017-12-04 09:58:50.027 DEBUG 7450 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Bean 'inboundChannelAdapter' completed its stop procedure

What am I missing here? Why is my message getting processed? Please correct me if I'm missing out something here? Also feel free to ask any other configuration that you feel would help analyze the situation here.

EDIT: After removing the code that closes the application context manually( app.run(args).close() ), I was able to receive the messages, but looks like they are lost after a successful retrieve. sharing the debug log for this behavior.

2017-12-04 14:39:11.297 DEBUG 1498 --- [pool-1-thread-5] o.s.a.r.listener.BlockingQueueConsumer   : Storing delivery for Consumer@7219ac49: tags=[{amq.ctag-Z8siptJMdxGU6sXdOHkVCA=ProductStore_Partial}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@6df20ade Shared Rabbit Connection: SimpleConnection@7ba63fe5 [delegate=amqp://admin@xxxx:5672/, localPort= 51172], acknowledgeMode=AUTO local queue size=0
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Received message: (Body:'[B@347c8f87(byte[624])' MessageProperties [headers={__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=json, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=NON_PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=ProductStore, receivedRoutingKey=, receivedDelay=null, deliveryTag=2, messageCount=0, consumerTag=amq.ctag-Z8siptJMdxGU6sXdOHkVCA, consumerQueue=ProductStore_Partial])
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedDeliveryMode] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_contentEncoding] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_receivedExchange] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_deliveryTag] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[json__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[amqp_redelivered] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[contentType] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] s.i.m.AbstractHeaderMapper$HeaderMatcher : headerName=[__TypeId__] WILL be mapped, matched pattern=*
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : preSend on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[624], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_consumerQueue=ProductStore_Partial, amqp_redelivered=false, id=540399a5-62a6-7178-2524-e274bad4ed13, amqp_consumerTag=amq.ctag-Z8siptJMdxGU6sXdOHkVCA, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512427151297}]
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.integration.channel.QueueChannel     : postSend (sent=true) on channel 'inboundQueueChannel', message: GenericMessage [payload=byte[624], headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_contentEncoding=UTF-8, amqp_receivedExchange=ProductStore, amqp_deliveryTag=2, json__TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, amqp_consumerQueue=ProductStore_Partial, amqp_redelivered=false, id=540399a5-62a6-7178-2524-e274bad4ed13, amqp_consumerTag=amq.ctag-Z8siptJMdxGU6sXdOHkVCA, contentType=json, __TypeId__=com.art.service.product.bulkimportproduct.data.model.Vendor, timestamp=1512427151297}]
2017-12-04 14:39:11.297 DEBUG 1498 --- [enerContainer-1] o.s.a.r.listener.BlockingQueueConsumer   : Retrieving delivery for Consumer@7219ac49: tags=[{amq.ctag-Z8siptJMdxGU6sXdOHkVCA=ProductStore_Partial}], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@xxxx:5672/,2), conn: Proxy@6df20ade Shared Rabbit Connection: SimpleConnection@7ba63fe5 [delegate=amqp://admin@xxxx:5672/, localPort= 51172], acknowledgeMode=AUTO local queue size=0

This goes on repeating and new messages are consumed, but the messages are not getting processed and written to the data-store using the itemWriter provided. Now come to think of it, since I have not provided the tasklet/step bean reference anywhere in this code, is that something I am missing out here?


来源: stackexchange

问:
How to create a data frame in R where I have to associate different txt files with a sample ID from a separate file?
I have 2 data sets I am working with in R.
In the first, I have multiple txt files with expression values for different genes. Each file has the same column and row names.

```<code>gene_ID   expression_value
gene_1    expression_value_1
...       ...
</code>```

In the second, I have a master chart (csv file) which associates the name of each txt file with a patient ID.

```<code>name_txt_file    patient_ID
txt_file_1       patient_1
</code>```

I am trying to create a master file with the gene expression values for all patients for each gene.

```<code>patient_ID      gene_1                 gene_2   ...
patient_1       expression_value_1     expression_value_2
patient_2       expression_value_x     expression_value_y
</code>```

So far I have created an empty data frame with the correct column and row names, but I do not know how to associate the name of each txt file with a patient ID from the master chart (csv file) and fill in the expression values for this empty data frame. I am assuming some sort of for loop function could be used, but do not know how to write functions which will associate the data in a file with a patient ID based on the file's name. Any help would be greatly appreciated.

答:
make sure yout .txt-filea are readable in R (I prefer csv)

Then i use code like this:

```<code>df.files <- data.frame( filename = list.files( path = "./data", pattern="*.txt" ) )
df.files["filepath"] <- paste0( getwd(), "/data/", df.files$filename )

df1 <- data.frame( gene_ID = character(0),
                   expression_value = character(0) )

for ( f in df.files$filepath ) {
  df.temp <- read.csv2(f)
  filename <- gsub(".*/","",f)
  df.temp["filename"] <- strtrim( filename, nchar( filename ) - 4 )
  df1 <- rbind( df1, df.temp )
}

df2 <- data.frame( filename = c( "text_1", "text_2" ),
                   patiend_ID = c( "patient_1", "patient_2" ),
                   stringsAsFactors = FALSE )

require(tidyverse)
df.total <- df1 %>%
  left_join( df2, by = "filename" ) %>%
  spread( gene_ID, expression_value ) %>%
  select( -filename )
</code>```

Which leads to this:

ContentLicense: CC BY-SA 3.0

Body:
I have 2 data sets I am working with in R.
In the first, I have multiple txt files with expression values for different genes. Each file has the same column and row names.

gene_ID   expression_value
gene_1    expression_value_1
...       ...

In the second, I have a master chart (csv file) which associates the name of each txt file with a patient ID.

name_txt_file    patient_ID
txt_file_1       patient_1

I am trying to create a master file with the gene expression values for all patients for each gene.

patient_ID      gene_1                 gene_2   ...
patient_1       expression_value_1     expression_value_2
patient_2       expression_value_x     expression_value_y

So far I have created an empty data frame with the correct column and row names, but I do not know how to associate the name of each txt file with a patient ID from the master chart (csv file) and fill in the expression values for this empty data frame. I am assuming some sort of for loop function could be used, but do not know how to write functions which will associate the data in a file with a patient ID based on the file's name. Any help would be greatly appreciated.

Body:
make sure yout .txt-filea are readable in R (I prefer csv)

Then i use code like this:

df.files <- data.frame( filename = list.files( path = "./data", pattern="*.txt" ) )
df.files["filepath"] <- paste0( getwd(), "/data/", df.files$filename )

df1 <- data.frame( gene_ID = character(0),
                   expression_value = character(0) )

for ( f in df.files$filepath ) {
  df.temp <- read.csv2(f)
  filename <- gsub(".*/","",f)
  df.temp["filename"] <- strtrim( filename, nchar( filename ) - 4 )
  df1 <- rbind( df1, df.temp )
}

df2 <- data.frame( filename = c( "text_1", "text_2" ),
                   patiend_ID = c( "patient_1", "patient_2" ),
                   stringsAsFactors = FALSE )

require(tidyverse)
df.total <- df1 %>%
  left_join( df2, by = "filename" ) %>%
  spread( gene_ID, expression_value ) %>%
  select( -filename )

Which leads to this:


问:
How to display a TImage as a background of a TGrid on Firemonkey?
I have a TGrid on a form.
I need to display a TImage inside that grid, as it´s background.
I know that in Firemonkey framework, controls are containers to other controls. Having that in mind, I dragged the TImage Object to the TGrid Obect using the structure pannel. Now the TImage´s parent is the TGrid object.
In design time, it´s fine, I can see the TImage "inside" the TGrid, but when I run the application, the TImage is gone.

Have spent all weekend googling for an answer and despite finding a lot of vcl oriented solutions, and all of them trying to put a TImage inside a TDBGrid or TStringGrid column, I couldn´t find anything that can help me.

Am I using the correct approach?

How can I accomplish my goal?

To test, is very simple:

Just drag a TGrid to a FMX form.
Crate a couple of columns inside it.
Drag a TImage to the form. Now in the scruture panel, find the TImage Obect and drag it to make it child of the TGrid component.
Assign a Bitmap to it, and send it to back.

You will see the image as a background of the grid, but when you run the application, the image disapears.

Thanks.

答:
As suggested by Hans, I´ve inverted the parent/child relationship, making the image, parent of the grid.

After tunning a litte bit with the Opacity properties of both obects, I managed to get the result I needed.

Thank you Hans!


问:
Entity Framework .First() Caches Query Data
According to Entity Framework documents, Entity Framework will only cache data when using .Find() to query data.

In the following sample I got query data cached when using .First():

```<code>  static void Main(string[] args)
    {
        var trxScope = new TransactionScope();
        var context = new SekhavatDBEntities();

        //the value of Balance is Zero
        var account =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;

        context.SaveChanges();
        trxScope.Dispose();

        var trxScope2 = new TransactionScope();
        var account2 =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));

        //Balance of account2 Is 50 Now!
        trxScope2.Dispose();
    }
</code>```

Why is account2's Balance 50? According to my considerations, it should be 0.

Thanks in advance

答:
Here is relevant quote from documentation:

Note that DbSet and IDbSet always create queries against the database
and will always involve a round trip to the database even if the
entities returned already exist in the context

...

When results are returned from the database, objects that do not exist
in the context are attached to the context. If an object is already in
the context, the existing object is returned (the current and original
values of the object's properties in the entry are not overwritten
with database values).

Using transaction or not is not relevant. What is relevant is:

EF will not change values back to original on transaction rollback (I don't think it's even possible for it to do that, but anyway). Doesn't matter if you use TransactionScope or ctx.Database.BeginTransaction.

Your account with id 79B7AAC6-AD2D-4824-907E-16ADB4C41EE1 is already tracked by context by the time you make your second query. As per documentation above - query will be made against database but results of this query will be discarded and will not overwrite values of currently tracked entity. Instead, entity will be returned as is (with Balance equals to 50).

To prevent this either:

Use separate contexts for separate operations and avoid reusing context as much as possible.

Use AsNoTracking. This will prevent behavior described above and will always return entity as it is in database now.

Use Reload:

```<code> context.Entry(account).Reload();
</code>```

This will query database for this entity and overwrite all values with current database values.

Body:
According to Entity Framework documents, Entity Framework will only cache data when using .Find() to query data.

In the following sample I got query data cached when using .First():

  static void Main(string[] args)
    {
        var trxScope = new TransactionScope();
        var context = new SekhavatDBEntities();

        //the value of Balance is Zero
        var account =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;

        context.SaveChanges();
        trxScope.Dispose();

        var trxScope2 = new TransactionScope();
        var account2 =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));

        //Balance of account2 Is 50 Now!
        trxScope2.Dispose();
    }

Why is account2's Balance 50? According to my considerations, it should be 0.

Thanks in advance

Body:
Here is relevant quote from documentation:

Note that DbSet and IDbSet always create queries against the database
and will always involve a round trip to the database even if the
entities returned already exist in the context

...

When results are returned from the database, objects that do not exist
in the context are attached to the context. If an object is already in
the context, the existing object is returned (the current and original
values of the object's properties in the entry are not overwritten
with database values).

Using transaction or not is not relevant. What is relevant is:

EF will not change values back to original on transaction rollback (I don't think it's even possible for it to do that, but anyway). Doesn't matter if you use TransactionScope or ctx.Database.BeginTransaction.

Your account with id 79B7AAC6-AD2D-4824-907E-16ADB4C41EE1 is already tracked by context by the time you make your second query. As per documentation above - query will be made against database but results of this query will be discarded and will not overwrite values of currently tracked entity. Instead, entity will be returned as is (with Balance equals to 50).

To prevent this either:

Use separate contexts for separate operations and avoid reusing context as much as possible.

Use AsNoTracking. This will prevent behavior described above and will always return entity as it is in database now.

Use Reload:

 context.Entry(account).Reload();

This will query database for this entity and overwrite all values with current database values.


问:
How to use an array from file A in file B
What is the right way to use an array from file A in file B?

When u use the example below, i get aan error (in Zend "Notice: Undefined variable: prefs")
Then, if i var_dump $prefs, it shows me the correct array of type array.

Example:

FILE A

```<code>$prefs = array('test', 'anothertest');
</code>```

FILE B

```<code>require_once('PATH_TO_FILE_A');
echo $prefs[0];
//output: test
</code>```

答:
If you're asking if that's the right way to do that, then yes, it is. Your code should work as written.

When you require or include files into a PHP document, PHP treats them as if they were literally part of the master document. In your case, imagine copy and pasting the contents of File A into the top of File B. That's how PHP will treat it.

ContentLicense: CC BY-SA 2.5

Body:
What is the right way to use an array from file A in file B?

When u use the example below, i get aan error (in Zend "Notice: Undefined variable: prefs")
Then, if i var_dump $prefs, it shows me the correct array of type array.

Example:

FILE A

$prefs = array('test', 'anothertest');

FILE B

require_once('PATH_TO_FILE_A');
echo $prefs[0];
//output: test


问:
Why is JavaScript adding extra square brackets when I push a sub array into another array?
I am working on a CodeWars kata that involves multidimensional arrays.
I have an array with three elements. Each element is an array with a name (string) and a sum (number).
I am checking the numbers. If they exceed a certain amount, I want to remove the sub array with that number and put it at the end of the array. I used splice() and push().

In a test case that had a sub array that had to be moved, the sub array was pushed to the end of the parent array. But, it had an extra set of brackets. I was wondering why this happened. Is JavaScript automatically adding the brackets when the push takes place because the parent array has only sub arrays as elements?

Here is a link to some screenshots of the Chrome Dev Tools and one from CodeWars. I combined them into one image.
The sub array at index 2 in the pop out window shows the sub array at the end that was moved/pushed in the first screenshot.
The second screenshot shows the expanded view.
The final screenshot I am attaching is the result shown in CodeWars where you can see the double brackets on the last sub array.

I cannot get the image to upload. So, here is a link to it online.
https://sta.sh/01tp7y7zaayi

Here is the section of code where this is happening.
I included the sort. But, I don't think it is affecting anything.

Note: I had a loop to go through the three elements to check them where the comment is located. But, I removed it because one shouldn't loop through an array and make changes to that array. I am coding a map() method for this to return a new array. But, I noticed that the double brackets were appearing. So, I didn't finish the map() part. I am trying to figure out what is happening in that splice() / push() section first.

```<code>var arrNew = [["Ben", sumBen], ["Amy", sumAmy], ["Sam", sumSam]];

arrNew.sort(function (a,b) {
    if (a[1] < b[1]) return  1;
    if (a[1] > b[1]) return -1;
    if (a[0] > b[0]) return  1;
    if (a[0] < b[0]) return -1;
    return 0;
});

// If someone's score is over 21, move them to the back.
var forMoving = arrNew.splice(0, 1);
arrNew.push(forMoving);
</code>```

答:
Use Array.concat instead of push to concat arrays.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Body:
I am working on a CodeWars kata that involves multidimensional arrays.
I have an array with three elements. Each element is an array with a name (string) and a sum (number).
I am checking the numbers. If they exceed a certain amount, I want to remove the sub array with that number and put it at the end of the array. I used splice() and push().

In a test case that had a sub array that had to be moved, the sub array was pushed to the end of the parent array. But, it had an extra set of brackets. I was wondering why this happened. Is JavaScript automatically adding the brackets when the push takes place because the parent array has only sub arrays as elements?

Here is a link to some screenshots of the Chrome Dev Tools and one from CodeWars. I combined them into one image.
The sub array at index 2 in the pop out window shows the sub array at the end that was moved/pushed in the first screenshot.
The second screenshot shows the expanded view.
The final screenshot I am attaching is the result shown in CodeWars where you can see the double brackets on the last sub array.

I cannot get the image to upload. So, here is a link to it online.
https://sta.sh/01tp7y7zaayi

Here is the section of code where this is happening.
I included the sort. But, I don't think it is affecting anything.

Note: I had a loop to go through the three elements to check them where the comment is located. But, I removed it because one shouldn't loop through an array and make changes to that array. I am coding a map() method for this to return a new array. But, I noticed that the double brackets were appearing. So, I didn't finish the map() part. I am trying to figure out what is happening in that splice() / push() section first.

var arrNew = [["Ben", sumBen], ["Amy", sumAmy], ["Sam", sumSam]];

arrNew.sort(function (a,b) {
    if (a[1]  b[1]) return -1;
    if (a[0] > b[0]) return  1;
    if (a[0] < b[0]) return -1;
    return 0;
});

// If someone's score is over 21, move them to the back.
var forMoving = arrNew.splice(0, 1);
arrNew.push(forMoving);


问:
Deleting primary key in Room
I'm trying to set my primary key to one after deleting all items in table:

```<code>@Query("DELETE FROM myTable")
fun deleteTable()

@Query("DELETE FROM sqlite_sequence WHERE name = 'myTable'")
fun clearPrimaryKey()
</code>```

but it doesn't work and after adding items again, their number don't start from 1. Any idea how to clear primary key in Room library?

答:
Let us say your table name is myTable. Then just do this:

```<code>@Query("ALTER TABLE myTable AUTO_INCREMENT = 1")
fun clearPrimaryKey()
</code>```

It resets the number of auto-generated primary key.

UPDATE:

Another way to do both deleting and resetting is this:

```<code>@Query("TRUNCATE TABLE myTable;")
fun deleteAndResetPrimaryKey()
</code>```

Title: Deleting primary key in Room

Body:
I'm trying to set my primary key to one after deleting all items in table:

@Query("DELETE FROM myTable")
fun deleteTable()

@Query("DELETE FROM sqlite_sequence WHERE name = 'myTable'")
fun clearPrimaryKey()

but it doesn't work and after adding items again, their number don't start from 1. Any idea how to clear primary key in Room library?

Body:
Let us say your table name is myTable. Then just do this:

@Query("ALTER TABLE myTable AUTO_INCREMENT = 1")
fun clearPrimaryKey()

It resets the number of auto-generated primary key.

UPDATE:

Another way to do both deleting and resetting is this:

@Query("TRUNCATE TABLE myTable;")
fun deleteAndResetPrimaryKey()


问:
Tweet params with twitter API
I want to have this template to tweet a String+Params like this:

```<code>    <td><a  class="fa fa-twitter" aria-hidden="true"
 href="https://twitter.com/intent/tweet?text=I%20found%20an%20object"+{{itemFound.type}}
data-size="large"></a></td>
</code>```

What am I doing wrong?

Thanks in advance

答:
Apparently it was like this:</p>

```<code>  <td><a  class="fa fa-twitter" aria-hidden="true"
 href="https://twitter.com/intent/tweet?text=I%20found%20an%20object+{{itemFound.type}}"
data-size="large"></a></td>
</code>```

Title: Tweet params with twitter API

Body:
I want to have this template to tweet a String+Params like this:

What am I doing wrong?

Thanks in advance

Body:
Apparently it was like this:

  <td><a  class="fa fa-twitter" aria-hidden="true"
 href="https://twitter.com/intent/tweet?text=I%20found%20an%20object+{{itemFound.type}}"
data-size="large"></a></td>


问:
Git Commit Log graph - confused
I am a relatively newbie to GIT and having issues understanding Commit Log graph.

I am under the feeling that each parallel line is a branch.While my source has only 2 branches..I see 3-4 parallel lines in the commit log graph provided below(Microsoft Team Services).Can someone help me understanding this?

答:
In git, branches are names of so called "heads" – they are related to the top most commits (which – in a simple case – do not have any further, or child, commits). In your case currently you have one branch, but previously there were 4 branches (at the moment of 4e31eddd), then 3 branches (d9effc23), and so on until it became one branch at 09d65a15.

However, even if a branch is merged into another branch it can still be a "head".

Title: Git Commit Log graph - confused


问:
Sum of entire column in new column om SQL Server, not running sum
Here is the data I have:

I want a 3rd column that has the total of the OpId column so I can do a percent of total in a 4th column. Thus, I want column 3 to read 80,801 all the way down. 80,801 is the sum of the entire OpId column

Thank you for the help

答:
You are talking about an over clause.

```<code>Sum(OpId) over (order by (select null))
</code>```

If you want to group / partition this into segments, like the sum of OpId per each incidencetype then add a partition by clause.

```<code>Sum(OpId) over (partition by incidencetype order by (select null))
</code>```

Body:
You are talking about an over clause.

Sum(OpId) over (order by (select null))

If you want to group / partition this into segments, like the sum of OpId per each incidencetype then add a partition by clause.

Sum(OpId) over (partition by incidencetype order by (select null))


问:
How to show last text when maxlines exceeds?
my code is

```<code><TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/typing"
android:maxEms="10"
android:text="efdfjhehjejfeivfdcfdjbjbdsbdjwu"
android:maxLines="2"
android:ellipsize="start"
android:padding="8dp"
android:background="@drawable/rounded_orange_bubble"
android:textColor="@color/white"
android:textSize="15dp" />
</code>```

I want that if lines exceeds so it with show last lines of text on first lines of text

please help
Have spent 2-3 hours

答: You can use a ScrollView, add the texts and always scroll the ScrollView to the bottom.</p>

ContentLicense: CC BY-SA 4.0

Body:
my code is

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/typing"
android:maxEms="10"
android:text="efdfjhehjejfeivfdcfdjbjbdsbdjwu"
android:maxLines="2"
android:ellipsize="start"
android:padding="8dp"
android:background="@drawable/rounded_orange_bubble"
android:textColor="@color/white"
android:textSize="15dp" />

I want that if lines exceeds so it with show last lines of text on first lines of text

please help
Have spent 2-3 hours


问:
Create array from mixed floats and arrays Python
Let's say that I have an array x = np.random.normal(size=(300, 300)) and that I wish to create a diagonal matrix of size (2, 2, 300, 300) using x. My first approach was to just do

```<code>import numpy as np

x = np.random.normal(size=(300, 300))

array = np.array([
    [x, 0.],
    [0., x]
])
</code>```

However, when doing so I get an array of size (2, 2). Is there a numpy function for recasting the elements to the same size? Given that all the arrays of the list are the same shape, and that all other elements are floats.

Edit
I might add that just defining an empty array and setting the diagonal to x is not a solution.

Edit 2
Here's a sample

```<code>import numpy as np

x = np.random.normal(size=(3, 3))

array = np.zeros((2, 2, *x.shape))

array[0, 0] = array[1, 1] = x

print(array)
</code>```

Yielding

```<code>[[[[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]

  [[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]]

 [[[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]

  [[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]]]
</code>```

答:
You can follow your first idea by:</p>

```<code>x = np.random.normal(size=(300, 300))
O = np.zeros_like(x)
r = np.array([[x,O],[O,x]])

In [153]: r.shape
Out[153]: (2, 2, 300, 300)
</code>```

Body:
Let's say that I have an array x = np.random.normal(size=(300, 300)) and that I wish to create a diagonal matrix of size (2, 2, 300, 300) using x. My first approach was to just do

import numpy as np

x = np.random.normal(size=(300, 300))

array = np.array([
    [x, 0.],
    [0., x]
])

However, when doing so I get an array of size (2, 2). Is there a numpy function for recasting the elements to the same size? Given that all the arrays of the list are the same shape, and that all other elements are floats.

Edit
I might add that just defining an empty array and setting the diagonal to x is not a solution.

Edit 2
Here's a sample

import numpy as np

x = np.random.normal(size=(3, 3))

array = np.zeros((2, 2, *x.shape))

array[0, 0] = array[1, 1] = x

print(array)

Yielding

[[[[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]

  [[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]]

 [[[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]

  [[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]]]

Body:
You can follow your first idea by:

x = np.random.normal(size=(300, 300))
O = np.zeros_like(x)
r = np.array([[x,O],[O,x]])

In [153]: r.shape
Out[153]: (2, 2, 300, 300)


问:
Parse RFC3339 timestamp in spark
Spark's CSV timestampFormat:

timestampFormat – sets the string that indicates a timestamp format. Custom date formats follow the formats at java.text.SimpleDateFormat. This applies to timestamp type. If None is set, it uses the default value, yyyy-MM-dd'T'HH:mm:ss.SSSXXX.

SimpleDateFormat seems doesn't support RFC3339 well, which would look like 2017-11-27T07:10:07Z.

How should I configure spark to parse this time format when reading a CSV file?

Title: Parse RFC3339 timestamp in spark

Body:
Spark will do it for you automatically:

>>> df=spark.read.option("header","true").option("inferSchema","true").option("delimiter",",").csv("file:///temp/1.csv")
>>> df.printSchema()
root
 |-- ts: timestamp (nullable = true)
 |-- val: integer (nullable = true)

>>> df.show()
+-------------------+---+
|                 ts|val|
+-------------------+---+
|2017-11-27 08:10:07|  1|
|2017-11-28 09:08:08|  1|
|2017-11-30 00:59:59|  1|
+-------------------+---+


问:
Game mesh goes crazy
I have experienced a strange issue where my gameobject meshes go crazy upon picking them up. It's only for specific meshes for which some of them only do it randomly. By crazy I mean they resize in a certain axis.

I am using the HTC Vive, SteamVR, and VRTK.

The only thing that I changed was update a graphics driver, but everything else seems to be fine.
Here is a link to my game on GitHub;

https://github.com/Tishbyte/CS-Tour

To reproduce follow these steps;

Turn on the game from the main scene using the HTC Vive.

Travel to a room with a whiteboard, these can identified by the markers which having glowing tips.

Pick up the marker and you shall see that the mesh goes crazy. This can also be done randomly with the blue and black chairs if you throw the object.

Any help would be appreciated.

答: I found that the child objects had a certain scale that was modified when it was interacted with by other objects. Not sure why this happens, but it has something to do with the parent object having less than a scale of 1. I fixed the bug by placing all the buggy child objects into a separate gameobject with a scale of one on x, y, and z.</p>

Title: Game mesh goes crazy


问:
Getting general location of user with google maps
I'm trying to get a general location of the user, reasons irrelevant, but I can't use the API to get their location. I've tried to parse the data associated with the IP, but if I have the $.getJson() outside of the initMap() function, the variables aren't changed and if inside initMap(), initMap() isn't recognised as a function.

tl:dr - how do I call the $.getJSON from inside the initMap() function?

Here's What I've tried:

```<code><div id="map" style="width: 100%; height: 100%;; "></div>
        <!-- G-Maps box-sizing: border-box; -->

        <script>
            var usrLat = 0;
            var usrLon = 0;

            function initMap() {
                var map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 6,

                    $.getJSON("https://freegeoip.net/json/", function (data) {
                                        usrLat = parseFloat(data.latitude);
                                        usrLon = parseFloat(data.longitude);
                                        console.log(usrLon + ", " + usrLat);
                                        });

                    center: {lat: usrLat, lng: usrLon},
                    mapTypeControl: true,
                    scrollwheel: false,
                    navigationControl: false,
                    mapTypeControl: false,
                    scaleControl: false,
                    draggable: false,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: true,
                    mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                    mapTypeIds: ['roadmap', 'terrain']
                    }
                });
            }
        </script>
</code>```

答:
Sorted it out. Thanks to Phil and GeoCodeZip for the help</p>

```<code><script>
            var usrLat = 0;
            var usrLon = 0;

            $.getJSON("https://freegeoip.net/json/", function (data) {
                var map = new google.maps.Map(document.getElementById('map'), {
                        zoom: 8,
                        center: {lat: parseFloat(data.latitude), lng: parseFloat(data.longitude)},
                        mapTypeControl: true,
                        scrollwheel: false,
                        navigationControl: false,
                        mapTypeControl: false,
                        scaleControl: false,
                        draggable: false,
                        mapTypeId: google.maps.MapTypeId.ROADMAP,
                        disableDefaultUI: true,
                        mapTypeControlOptions: {
                            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                            mapTypeIds: ['roadmap', 'terrain']
                        }
                });
            });
        </script>
</code>```

Body:
Sorted it out. Thanks to Phil and GeoCodeZip for the help

<script>
            var usrLat = 0;
            var usrLon = 0;

            $.getJSON("https://freegeoip.net/json/", function (data) {
                var map = new google.maps.Map(document.getElementById('map'), {
                        zoom: 8,
                        center: {lat: parseFloat(data.latitude), lng: parseFloat(data.longitude)},
                        mapTypeControl: true,
                        scrollwheel: false,
                        navigationControl: false,
                        mapTypeControl: false,
                        scaleControl: false,
                        draggable: false,
                        mapTypeId: google.maps.MapTypeId.ROADMAP,
                        disableDefaultUI: true,
                        mapTypeControlOptions: {
                            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                            mapTypeIds: ['roadmap', 'terrain']
                        }
                });
            });
        </script>


问:
How to prevent package from reloading?
Consider the following

```<code>Needs["Combinatorica`"];
$ContextPath = DeleteCases[$ContextPath, "Combinatorica`"];
</code>```

When I execute it the second time, it's 10 times faster and it doesn't print the compatibility warning.

How does Mathematica know this package has been loaded already?

What's a good way to avoid reloading the package when it's been loaded and removed from $ContextPath?

I'm relying on Combinatorica for some graph algorithms, but I need to redefine Element every time it is loaded, so I'm trying to keep reloading to minimum

答:
You probably want to look at $Packages variable. The first time you load, your context gets appended to it. The second time, it is not loaded at all, since it is already in $Packages, so nothing is happening thesecond time (apart from bringing the context back on the $ContextPath, but you delete it anyway). You can verify that Get is not invoked the second time by using On[Get].

Since there is no actual reloading happening the second time, you don't have to do anything. But this also means that if you want to really reload the package, you have to first delete its context from $Packages, otherwise the call to Needs will do nothing except returning your context back on the $ContextPath.

Title: How to prevent package from reloading?

Body:
Consider the following

Needs["Combinatorica`"];
$ContextPath = DeleteCases[$ContextPath, "Combinatorica`"];

When I execute it the second time, it's 10 times faster and it doesn't print the compatibility warning.

How does Mathematica know this package has been loaded already?

What's a good way to avoid reloading the package when it's been loaded and removed from $ContextPath?

I'm relying on Combinatorica for some graph algorithms, but I need to redefine Element every time it is loaded, so I'm trying to keep reloading to minimum


问:
In Python 3.6, how can I convert an unknown string to a set?

I want the program to read an input. Unless the input is "HELP", it consists of several integers separated by spaces. I don't know the number of integers provided.

I want the integers to be placed in a set.

This is the code I am currently using, but it takes a long time and I am looking for a faster method.

```<code>nextInput = input()
while nextInput != "HELP":
    testString = set()
    testString1 = nextInput.split()
    for j in range(0, len(testString1)):
        k = int(testString1[j])
        testString.add(k)
    nextInput = input()
</code>```

答:
Try this:</p>

```<code># Create empty set
testString = set()

while True:

    # Ask for input
    nextInput = input()

    # Break if user writes help
    if nextInput.upper() == 'HELP':
        break

    # Try to update the set with ints else print Error!
    try:
        testString.update(map(int,nextInput.split()))
    except ValueError:
        print("Error with input!")
</code>```

Body:
I want the program to read an input. Unless the input is "HELP", it consists of several integers separated by spaces. I don't know the number of integers provided.

I want the integers to be placed in a set.

This is the code I am currently using, but it takes a long time and I am looking for a faster method.

nextInput = input()
while nextInput != "HELP":
    testString = set()
    testString1 = nextInput.split()
    for j in range(0, len(testString1)):
        k = int(testString1[j])
        testString.add(k)
    nextInput = input()

Body:
Try this:

# Create empty set
testString = set()

while True:

    # Ask for input
    nextInput = input()

    # Break if user writes help
    if nextInput.upper() == 'HELP':
        break

    # Try to update the set with ints else print Error!
    try:
        testString.update(map(int,nextInput.split()))
    except ValueError:
        print("Error with input!")


问:
What causes WPF App to close
I've ran into a weird bug where a WPF app is closing after the first window closes.  This has made me curious what is triggering it to close

For example this is what I was the unworking version.  After the EULAWindow would close it would shut down the application.

```<code>EULAWindow eula = new EULAWindow();
eula.ShowDialog();
MainMenuWindow mainWindow = new MainMenuWindow();
mainWindow.ShowDialog();
</code>```

I thought it would open the EULA and then open the Menu window.   I've found that if I rearranged the code it will operate like expected.

For example this will fix it:

```<code>EULAWindow eula = new EULAWindow();
MainMenuWindow mainWindow = new MainMenuWindow();
eula.ShowDialog();
mainWindow.ShowDialog();
</code>```

This brings me to the question of what actually is causing the application to shut down in the first situation?

答:
Since I was using Application Startup to create my windows, it was defaulting setting the EULAWindow to the Current.MainWindow  Then keeping the Current.ShutDownMode as ShutdownMode.OnMainWindowClose.

When you create two windows, before calling Show or ShowDialog, it changes the shutdown mode automatically to ShutdownMode.OnLastWindowClose

I'm not certain how or where this happening, but I can tell this is the behavior that is happening upon further investigation.

Title: What causes WPF App to close

Body:
I've ran into a weird bug where a WPF app is closing after the first window closes.  This has made me curious what is triggering it to close

For example this is what I was the unworking version.  After the EULAWindow would close it would shut down the application.

EULAWindow eula = new EULAWindow();
eula.ShowDialog();
MainMenuWindow mainWindow = new MainMenuWindow();
mainWindow.ShowDialog();

I thought it would open the EULA and then open the Menu window.   I've found that if I rearranged the code it will operate like expected.

For example this will fix it:

EULAWindow eula = new EULAWindow();
MainMenuWindow mainWindow = new MainMenuWindow();
eula.ShowDialog();
mainWindow.ShowDialog();

This brings me to the question of what actually is causing the application to shut down in the first situation?


问:
AudioKit MIDI Events - basic questions, sending to external synth, not sure about handling
I had some more time to play around with AudioKit, yet I have a few questions about MIDI. I tried googling and I also checked the AKMIDI class reference, but this just further confused me.

Let's keep it simple: I have a UIButton that should give out a "C" to an external synth.

```<code>import AudioKit
midiOut.openOutput()
midiOut.sendEvent(AKMIDIEvent(noteOn: 72, velocity: 80, channel: 1))
sleep(1)
midiOut.sendEvent(AKMIDIEvent(noteOff: 72, velocity: 0, channel: 1))
</code>```

Obviously this code is spread over the entire ViewController.swift and the sendEvents are inside an @IBAction, but for the sake of keeping it simple, I merged the LOCs.

So my questions are:

Will this send out MIDI signals to external machines? (I ordered the Lightning Camera Connection Kit, but it will take a few more days to arrive, so I cannot test it yet.) I cannot get anything from the iPhone Simulator, so I take it, this is not working.

Will this send out MIDI signals over wireless MIDI as well? According to what I read on some Google group, you can have Wireless MIDI on macOS. Unfortunately I didn't find anything on if and how you can use this in AudioKit.

What about MIDI over Bluetooth? Will this all be handled by AudioKit automatically or will I have to change anything? I read something about midi.createVirtualPorts(), but I am not sure what this actually does. But the word "virtual" makes me believe this is for testing?

Sorry if these questions are ridiculously noobish, but I really am confused by the exact inner workings of this.

Thanks a lot in advance!

答:
Yes it should. You've opened all outputs, so everything should get the output.

I'm not sure about wireless MIDI as there's nothing specifically done with that in mind in AudioKit. If it doesn't "just work" I can try to replicate.

You might have to explicitly open the bluetooth connection with openOutput("Bluetooth")

Body:
I had some more time to play around with AudioKit, yet I have a few questions about MIDI. I tried googling and I also checked the AKMIDI class reference, but this just further confused me.

Let's keep it simple: I have a UIButton that should give out a "C" to an external synth.

import AudioKit
midiOut.openOutput()
midiOut.sendEvent(AKMIDIEvent(noteOn: 72, velocity: 80, channel: 1))
sleep(1)
midiOut.sendEvent(AKMIDIEvent(noteOff: 72, velocity: 0, channel: 1))

Obviously this code is spread over the entire ViewController.swift and the sendEvents are inside an @IBAction, but for the sake of keeping it simple, I merged the LOCs.

So my questions are:

Will this send out MIDI signals to external machines? (I ordered the Lightning Camera Connection Kit, but it will take a few more days to arrive, so I cannot test it yet.) I cannot get anything from the iPhone Simulator, so I take it, this is not working.

Will this send out MIDI signals over wireless MIDI as well? According to what I read on some Google group, you can have Wireless MIDI on macOS. Unfortunately I didn't find anything on if and how you can use this in AudioKit.

What about MIDI over Bluetooth? Will this all be handled by AudioKit automatically or will I have to change anything? I read something about midi.createVirtualPorts(), but I am not sure what this actually does. But the word "virtual" makes me believe this is for testing?

Sorry if these questions are ridiculously noobish, but I really am confused by the exact inner workings of this.

Thanks a lot in advance!


问:
Find list of pixels between two points
I'm currently programming my first game in JavaScript, and I've never technically learned JavaScript, I'm more fluent with Python.

Anyway, I need to find a way to make a list of all the pixels between two points on a straight horizontal line. I would then use the list to reference whether the user's character is touching any of the pixels to trigger a screen change.

It would be something like

```<code>pixels = []
(Function here to add the pixels to the list)
    For pixel in pixels
         If (dist(object.x, object.y, pixel.x, 0) < 1) {
            object.x = start point on new screen
            Object.y =
</code>```

Does this make any sense? I'm sorry I'm bad at explaining things but I could use the help.

答:
You almost certainly don't want to test intersection this way. This is going to require many more steps than just doing standard line-rectangle collision detection.

I recommend googling something like "line rectangle intersection" or "line rectangle collision detection" for a ton of results, including:

line-rectangle collision detection

How to check if line segment intersects a rectangle?

How to find the intersection point between a line and a rectangle?

Line intersection with AABB Rectangle?

How to test if a line segment intersects an axis-aligned rectange in 2D?

https://gamedev.stackexchange.com/questions/111100/intersection-of-a-line-and-a-rectangle

Title: Find list of pixels between two points

Body:
I'm currently programming my first game in JavaScript, and I've never technically learned JavaScript, I'm more fluent with Python.

Anyway, I need to find a way to make a list of all the pixels between two points on a straight horizontal line. I would then use the list to reference whether the user's character is touching any of the pixels to trigger a screen change.

It would be something like

pixels = []
(Function here to add the pixels to the list)
    For pixel in pixels
         If (dist(object.x, object.y, pixel.x, 0) < 1) {
            object.x = start point on new screen
            Object.y =

Does this make any sense? I'm sorry I'm bad at explaining things but I could use the help.


问:
object with array to .xml
Main.java

```<code>File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
</code>```

Appointment.java

```<code>public class Appointment{
    private Integer day;
    private Integer numbOfVisitors;
    private String comment;
    //setters with @XmlAttribute and getters
}
</code>```

Customer.java

```<code>    public class Customer{
private String name;
private String surname;
private int expirience;
private Appointment[] appointments;
//setters with @XmlAttribute and getters
}
</code>```

How i can Marshall 2 objects in .xml like this? Becouse this code Marshall only customer name and surname

```<code><?xml version="1.0" encoding="UTF-8"?>
<Customer Name="Anton" Surname="Vasiliev" Expirience="3252" >
    <Appointment Day="1" NumbOfVisitors="4" Comment="gdshfgfh" />
    <Appointment Day="2" NumbOfVisitors="2" Comment="dgsh242fd" />
    <Appointment Day="3" NumbOfVisitors="6" Comment="bdgsrjdfgsryw" />
    <Appointment Day="4" NumbOfVisitors="3" Comment="1dgfhhhsqqe" />
</Customer>
</code>```

答:
JAXB does not work with arrays by nature because Java does not have dynamic arrays. Instead declare your Appointment as ArrayList.

it must be initialized either with class or in getter

```<code>private List<Appointment> appointments = new ArrayList();
</code>```

or in getter

```<code>public List<Appointment> getAppointments() {
    if (appointments == null) {
        appointments = new ArrayList<Appointment>();
    }
    return this.appointments;
}
</code>```

Title: object with array to .xml

Body:
Main.java

File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);

Appointment.java

public class Appointment{
    private Integer day;
    private Integer numbOfVisitors;
    private String comment;
    //setters with @XmlAttribute and getters
}

Customer.java

    public class Customer{
private String name;
private String surname;
private int expirience;
private Appointment[] appointments;
//setters with @XmlAttribute and getters
}

How i can Marshall 2 objects in .xml like this? Becouse this code Marshall only customer name and surname

<?xml version="1.0" encoding="UTF-8"?>
<Customer Name="Anton" Surname="Vasiliev" Expirience="3252" >
    <Appointment Day="1" NumbOfVisitors="4" Comment="gdshfgfh" />
    <Appointment Day="2" NumbOfVisitors="2" Comment="dgsh242fd" />
    <Appointment Day="3" NumbOfVisitors="6" Comment="bdgsrjdfgsryw" />
    <Appointment Day="4" NumbOfVisitors="3" Comment="1dgfhhhsqqe" />
</Customer>

Body:
JAXB does not work with arrays by nature because Java does not have dynamic arrays. Instead declare your Appointment as ArrayList.

it must be initialized either with class or in getter

private List<Appointment> appointments = new ArrayList();

or in getter

public List<Appointment> getAppointments() {
    if (appointments == null) {
        appointments = new ArrayList<Appointment>();
    }
    return this.appointments;
}


问:
How to specify which version of perl to use on CentOS
I am running CentOS 5.4 which only has version 5.8 of perl available by default, and I have a program which requires perl 5.10, so I compiled perl 5.10 on CentOS.  How do I specify which perl I want to run the program with because the perl command uses 5.8 by default.</p>

答:
set your PATH environment variable to point to your new perl executable. For instance</p>

```<code> export PATH=/newpath/perl:$PATH
</code>```

Body:
set your PATH environment variable to point to your new perl executable. For instance

 export PATH=/newpath/perl:$PATH


问:
SQL string before and after certain characters
```<code>SELECT NAME
FROM SERVERS
</code>```

returns:

```<code>SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER
</code>```

I need the SELECT query for below result:

```<code>SDACR
SDACR
SDACR\AIR
SDACR\WATER
</code>```

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

```<code> SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS
</code>```

答:
In tsql, you can concatenate values with CONCAT(), or you can simply add strings together with +.

```<code>SELECT LEFT(Name, CHARINDEX('.',Name)-1) + RIGHT(Name,LEN(Name)-CHARINDEX('\',Name)) from SERVERS
</code>```

Also, be careful with doing arithmetic with CHARINDEX(). A value without a '.' or a '\' will return a NULL and you will get an error.

Body:
SELECT NAME
FROM SERVERS

returns:

SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER

I need the SELECT query for below result:

SDACR
SDACR
SDACR\AIR
SDACR\WATER

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

 SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS

Body:
In tsql, you can concatenate values with CONCAT(), or you can simply add strings together with +.

SELECT LEFT(Name, CHARINDEX('.',Name)-1) + RIGHT(Name,LEN(Name)-CHARINDEX('\',Name)) from SERVERS

Also, be careful with doing arithmetic with CHARINDEX(). A value without a '.' or a '\' will return a NULL and you will get an error.


问:
How to get status of auto renew subscription, mainly canceled during sandbox mode?
I found multiple suggestion but still stucked. Do not know what I am suppose to get when subscription is canceled. Or what URL I am supposed to give in iTunes to notification. Here is one reponse I got:

```<code>  "expires_date" = "2017-11-30 14:24:13 Etc/GMT";
        "expires_date_ms" = 1512051853000;
        "expires_date_pst" = "2017-11-30 06:24:13 America/Los_Angeles";
        "is_trial_period" = false;
        "original_purchase_date" = "2017-11-30 14:14:13 Etc/GMT";
        "original_purchase_date_ms" = 1512051253000;
        "original_purchase_date_pst" = "2017-11-30 06:14:13 America/Los_Angeles";
        "original_transaction_id" = 1000000356232086;
        "product_id" = "com.demo.demoapp.weeklysubscriptionsssss";
        "purchase_date" = "2017-11-30 14:19:13 Etc/GMT";
        "purchase_date_ms" = 1512051553000;
        "purchase_date_pst" = "2017-11-30 06:19:13 America/Los_Angeles";
        quantity = 1;
        "transaction_id" = 100000fsdfdsf0356233554;
        "web_order_line_item_id" = 1000000037061260;
    },
</code>```

What am I supposed to get exactly when an subscription is canceled?

答:
There is a common misconception about how Apple's subscription status notifications work. Apple will only notify your backend when a subscription has been canceled by customer service, i.e. when a customer contacts Apple and receives refund. When a user cancels normally you will not receive a notification.

In order to detect when someone has cancelled you need to periodically check the receipt against Apple's /verifyReceipt endpoint to see if the user intends to renew or not, via the expiration_intent field, will tell you why a users subscription expired.

If you are still lost, I recommend reading all of Apple's guide on subscriptions. If you are looking for a shortcut you could try something like RevenueCat (disclaimer: it is my pet project).

Body:
I found multiple suggestion but still stucked. Do not know what I am suppose to get when subscription is canceled. Or what URL I am supposed to give in iTunes to notification. Here is one reponse I got:

  "expires_date" = "2017-11-30 14:24:13 Etc/GMT";
        "expires_date_ms" = 1512051853000;
        "expires_date_pst" = "2017-11-30 06:24:13 America/Los_Angeles";
        "is_trial_period" = false;
        "original_purchase_date" = "2017-11-30 14:14:13 Etc/GMT";
        "original_purchase_date_ms" = 1512051253000;
        "original_purchase_date_pst" = "2017-11-30 06:14:13 America/Los_Angeles";
        "original_transaction_id" = 1000000356232086;
        "product_id" = "com.demo.demoapp.weeklysubscriptionsssss";
        "purchase_date" = "2017-11-30 14:19:13 Etc/GMT";
        "purchase_date_ms" = 1512051553000;
        "purchase_date_pst" = "2017-11-30 06:19:13 America/Los_Angeles";
        quantity = 1;
        "transaction_id" = 100000fsdfdsf0356233554;
        "web_order_line_item_id" = 1000000037061260;
    },

What am I supposed to get exactly when an subscription is canceled?


问:
ngrx one request in flight at a time

Context: Angular 4.x, RxJs 5.4.x, NgRx 4.1.1.

Goal: I want to avoid repeating the same api call when multiple components request the same data. I don't want to cancel in-flight requests, just not make future ones till the in-flight one is complete.

Method: In the store there is a flag named isFetching. In my effect I check the flag to see if there is an in-flight request for already. If so then I don't make the request. The same action that triggers the effect sets the isFetching flag to true.

Problem: The state is updated before effects are run. So isFetching is true before the first request is sent. So no request is ever sent.

Example: Here is a simplified version of the problem:

state.ts

export interface State {
    isFetching: boolean;
}
```

<p><em>reducer.ts</em></p>

<pre class="lang-ts prettyprint-override"><code>export function reducer(state: State, action: Action): State {
    switch (action.type) {
        case 'FETCH':
            return <State>{ isFetching: action.payload };
    }

    return state;
}
</code>```

effect.ts

@Effect()
public fetch: Observable<Action> = this.actions.ofType('FETCH')
    .withLatestFrom(this.store.select(x => x.isFetching), (_, x) => x)
    .filter(x => !x)
    .switchMap(action =>
        this.api.getData()
        .map(data => new FetchSuccess(data))
        .catch(() => Observable.of(new FetchFailure()))
    );
```

<p><strong>Idea #1:</strong></p>

<p>I can duplicate the state by keeping a variable in the class that contains the effect. I would set it when the api request was made and use it to filter out future requests.</p>

<p><em>effect.ts</em></p>

<pre class="lang-ts prettyprint-override"><code>public isFetching = false;

@Effect()
public fetch: Observable<Action> = this.actions.ofType('FETCH')
    .filter(() => !this.isFetching)
    .switchMap(action => {
        this.isFetching = true;
        return this.api.getData()
            .map(data => new FetchSuccess(data))
            .catch(() => Observable.of(new FetchFailure()))
            .do(() => this.isFetching = false);
    });
</code>```

Idea #2:

Don't have the 'FETCH' action set isFetching. Have the effect emit two actions. The first (IsFetching) sets the state and the second (FetchSuccess | FetchFailure) is the result. I don't like that I need two actions to do what I feel I should be able to do with one. The advantage is that if there are multiple 'FETCH' requests there will only be one state update from the IsFetching action.

It seems that the results of the effect are applied to state asynchronously. So sequential synchronous 'FETCH' actions will trigger an equivalent number of requests before the flag is set in state. So don't use this solution.

effect.ts

@Effect()
public fetch: Observable<Action> = this.actions.ofType('FETCH')
    .withLatestFrom(this.store.select(x => x.isFetching), (_, x) => x)
    .filter(x => !x)
    .switchMap(action =>
        this.api.getData()
            .map(data => new FetchSuccess(data))
            .catch(() => Observable.of(new FetchFailure()))
            .startWith(new IsFetching(true))
    );
```

Question
Is there a more elegant/standard way to accomplish my goal? Ideally I would like to avoid keeping the same state information in two places.

答:
One option would be to use an operator that maintains its own state.

For example, you could use distinct, which accepts a second parameter that clears the operator's internal state upon emission:

@Effect()
public fetch: Observable<Action> = this.actions
    .ofType('FETCH')
    .distinct(() => 'FETCH', this.actions.ofType(
        'FETCH_SUCCESS',
        'FETCH_FAILURE'
    ))
    .switchMap(action => this.api.getData()
        .map(data => new FetchSuccess(data))
        .catch(() => Observable.of(new FetchFailure()));
    );
```

If the key selector always returns the same value, any FETCH actions received whilst one is being handled will be ignored.

Title: ngrx one request in flight at a time

Body:
Context: Angular 4.x, RxJs 5.4.x, NgRx 4.1.1.

Goal: I want to avoid repeating the same api call when multiple components request the same data. I don't want to cancel in-flight requests, just not make future ones till the in-flight one is complete.

Method: In the store there is a flag named isFetching. In my effect I check the flag to see if there is an in-flight request for already. If so then I don't make the request. The same action that triggers the effect sets the isFetching flag to true.

Problem: The state is updated before effects are run. So isFetching is true before the first request is sent. So no request is ever sent.

Example: Here is a simplified version of the problem:

state.ts

export interface State {
    isFetching: boolean;
}

reducer.ts

export function reducer(state: State, action: Action): State {
    switch (action.type) {
        case 'FETCH':
            return <State>{ isFetching: action.payload };
    }

    return state;
}

effect.ts

@Effect()
public fetch: Observable<Action> = this.actions.ofType('FETCH')
    .withLatestFrom(this.store.select(x => x.isFetching), (_, x) => x)
    .filter(x => !x)
    .switchMap(action =>
        this.api.getData()
        .map(data => new FetchSuccess(data))
        .catch(() => Observable.of(new FetchFailure()))
    );

Idea #1:

I can duplicate the state by keeping a variable in the class that contains the effect. I would set it when the api request was made and use it to filter out future requests.

effect.ts

public isFetching = false;

@Effect()
public fetch: Observable<Action> = this.actions.ofType('FETCH')
    .filter(() => !this.isFetching)
    .switchMap(action => {
        this.isFetching = true;
        return this.api.getData()
            .map(data => new FetchSuccess(data))
            .catch(() => Observable.of(new FetchFailure()))
            .do(() => this.isFetching = false);
    });

Idea #2:

Don't have the 'FETCH' action set isFetching. Have the effect emit two actions. The first (IsFetching) sets the state and the second (FetchSuccess | FetchFailure) is the result. I don't like that I need two actions to do what I feel I should be able to do with one. The advantage is that if there are multiple 'FETCH' requests there will only be one state update from the IsFetching action.

It seems that the results of the effect are applied to state asynchronously. So sequential synchronous 'FETCH' actions will trigger an equivalent number of requests before the flag is set in state. So don't use this solution.

effect.ts

@Effect()
public fetch: Observable<Action> = this.actions.ofType('FETCH')
    .withLatestFrom(this.store.select(x => x.isFetching), (_, x) => x)
    .filter(x => !x)
    .switchMap(action =>
        this.api.getData()
            .map(data => new FetchSuccess(data))
            .catch(() => Observable.of(new FetchFailure()))
            .startWith(new IsFetching(true))
    );

Question
Is there a more elegant/standard way to accomplish my goal? Ideally I would like to avoid keeping the same state information in two places.

Body:
One option would be to use an operator that maintains its own state.

For example, you could use distinct, which accepts a second parameter that clears the operator's internal state upon emission:

@Effect()
public fetch: Observable<Action> = this.actions
    .ofType('FETCH')
    .distinct(() => 'FETCH', this.actions.ofType(
        'FETCH_SUCCESS',
        'FETCH_FAILURE'
    ))
    .switchMap(action => this.api.getData()
        .map(data => new FetchSuccess(data))
        .catch(() => Observable.of(new FetchFailure()));
    );

If the key selector always returns the same value, any FETCH actions received whilst one is being handled will be ignored.


问:
Config Error in Swift 4
I am receiving the following error, "Value of type 'Configuration' has no member 'config'". Basically, I am trying to establish a connection to the API listed. For reference, I am running Siesta and SwiftyJSON, both of which are new to me. Any help would be great. </p>

```<code>import Foundation
import Siesta
import SwiftyJSON

let Pokeapi = _Pokeapi()

class _Pokeapi: Service {
public init() {
    super.init(baseURL: "https://pokeapi.co/api/v2")
    self.configure {
        $0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
        $0.config.expirationTime = 3600
    }

}
}

public let SwiftyJSONTransformer =
ResponseContentTransformer
    { JSON($0.content as AnyObject) }
</code>```

答:
So the error you get is because $0 in your closure refers to a variable of type Configuration which does not have a member called config. Instead maybe you wanted to write :

```<code>self.configure { config in
    config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
    config.expirationTime = 3600
}
</code>```

Note you that you could also do

```<code>self.configure {
    $0.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
    $0.expirationTime = 3600
}
</code>```

but it makes a better readable code if you name the closure vars

Title: Config Error in Swift 4

Body:
I am receiving the following error, "Value of type 'Configuration' has no member 'config'". Basically, I am trying to establish a connection to the API listed. For reference, I am running Siesta and SwiftyJSON, both of which are new to me. Any help would be great.

import Foundation
import Siesta
import SwiftyJSON

let Pokeapi = _Pokeapi()

class _Pokeapi: Service {
public init() {
    super.init(baseURL: "https://pokeapi.co/api/v2")
    self.configure {
        $0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
        $0.config.expirationTime = 3600
    }

}
}

public let SwiftyJSONTransformer =
ResponseContentTransformer
    { JSON($0.content as AnyObject) }

Body:
So the error you get is because $0 in your closure refers to a variable of type Configuration which does not have a member called config. Instead maybe you wanted to write :

self.configure { config in
    config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
    config.expirationTime = 3600
}

Note you that you could also do

self.configure {
    $0.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
    $0.expirationTime = 3600
}

but it makes a better readable code if you name the closure vars


问:
How to get different strings from a sting character
I have a string "abc". Want to get all the different string from string character.

```<code>#include<bits/stdc++.h>
using namespace std;

// Function to print all sub strings
void subString(string s, int n)
{
     // Pick starting point in outer loop
    // and lengths of different strings for
    // a given starting point
    for (int i = 0; i < n; i++)
       for (int len = 1; len <= n - i; len++)
           cout << s.substr(i, len) << endl;
}

 // Driver program to test above function
 int main()
 {
    string s = "abc";
    subString(s,s.length());
    return 0;
 }
</code>```

Expecting :

a b c ab ac bc abc

Actual output :

a b c ab bc abc

答:
Please see the solution below:</p>

```<code>#include <iostream>

using namespace std;

int main()
{
    string input = "abc";
    for (int length = 0; length < input.length(); length++) {
        for (int offset = 0; offset <= input.length() - length; offset++) {
            cout << input.substr(offset, length) + "\n";
        }
    }
    cout << input;

    return 0;
}
</code>```

Body:
I have a string "abc". Want to get all the different string from string character.

#include<bits/stdc++.h>
using namespace std;

// Function to print all sub strings
void subString(string s, int n)
{
     // Pick starting point in outer loop
    // and lengths of different strings for
    // a given starting point
    for (int i = 0; i < n; i++)
       for (int len = 1; len <= n - i; len++)
           cout << s.substr(i, len) << endl;
}

 // Driver program to test above function
 int main()
 {
    string s = "abc";
    subString(s,s.length());
    return 0;
 }

Expecting :

a b c ab ac bc abc

Actual output :

a b c ab bc abc

Body:
Please see the solution below:

#include <iostream>

using namespace std;

int main()
{
    string input = "abc";
    for (int length = 0; length < input.length(); length++) {
        for (int offset = 0; offset <= input.length() - length; offset++) {
            cout << input.substr(offset, length) + "\n";
        }
    }
    cout << input;

    return 0;
}