问:
Fetch the Data from DB2 and save in MongoDB using Spring Batch without metadata tables
I need to fetch all the data from Db2 table and copy to mongoDB. I am using Spring batch without metadata tables. I am using JpaPagingItemReader for fetching data from Db2. I am able to get the data from Db2 for the first fetch which based on the PageSize attribute and save in mongoDB successfully but for the next set of data, getting error in fetching the data with the pagination.

Below given the Error:

```<code>15:17:36,085 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.084  INFO 7088 --- [ default task-2] c.t.controller.ItemController   : About to copy All Item
15:17:36,135 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.135  INFO 7088 --- [ default task-2] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=readDB2]] launched with the following parameters: [{}]
15:17:36,180 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.180  INFO 7088 --- [ default task-2] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
15:17:36,215 INFO  [stdout] (default task-2) Hibernate: select itm0_.itm_nbr as t1_4_, itm0_.itm_des_txt as itm_des13_4_ from itm itm0_ fetch first 10 rows only
15:17:36,884 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.884 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:38,621 INFO  [stdout] (default task-2) 2017-12-06 15:17:38.621  INFO 7088 --- [ default task-2] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:1998}] to lxmdbpmdmdev001:27017
15:17:38,894 INFO  [stdout] (default task-2) 2017-12-06 15:17:38.894 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,139 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.139 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,386 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.386 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,632 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.632 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,881 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.881 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,123 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.123 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,377 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.377 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,619 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.619 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,865 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.865 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]

15:17:41,109 INFO  [stdout] (default task-2) Hibernate: select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( select itm0_.itm_nbr as t1_4_, itm0_.itm_des_txt as itm_des13_4_ from itm itm0_ fetch first 20 rows only ) as inner2_ ) as inner1_ where rownumber_ > 10 order by rownumber_

15:17:41,346 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: -199, SQLState: 42601
15:17:41,347 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) DB2 SQL Error: SQLCODE=-199, SQLSTATE=42601, SQLERRMC=OF;;??( [ DESC ASC NULLS RANGE CONCAT || / MICROSECONDS MICROSECOND, DRIVER=4.18.60
15:17:41,347 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: -516, SQLState: 26501
15:17:41,347 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) DB2 SQL Error: SQLCODE=-516, SQLSTATE=26501, SQLERRMC=null, DRIVER=4.18.60
15:17:41,347 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: -514, SQLState: 26501
15:17:41,347 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) DB2 SQL Error: SQLCODE=-514, SQLSTATE=26501, SQLERRMC=SQL_CURLN200C1, DRIVER=4.18.60
15:17:41,362 INFO  [stdout] (default task-2) 2017-12-06 15:17:41.362 ERROR 7088 --- [ default task-2] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step1 in job readDB2

15:17:41,362 INFO  [stdout] (default task-2)
15:17:41,362 INFO  [stdout] (default task-2) javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
15:17:41,362 INFO  [stdout] (default task-2)    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
15:17:41,362 INFO  [stdout] (default task-2)    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
15:17:41,362 INFO  [stdout] (default task-2)    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:492) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.item.database.JpaPagingItemReader.doReadPage(JpaPagingItemReader.java:225) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:157) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:110) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]

15:17:41,376 INFO  [stdout] (default task-2)    at com.test.service.impl.ItemServiceImpl.itemCopy(ItemServiceImpl.java:266) [classes:na]
15:17:41,376 INFO  [stdout] (default task-2)    at com.test.controller.ItemController.allItemCopy(ItemController.java:48) [classes:na]

....

15:17:41,410 INFO  [stdout] (default task-2) 2017-12-06 15:17:41.410  INFO 7088 --- [ default task-2] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=readDB2]] completed with the following parameters: [{}] and the following status: [FAILED]
</code>```

Batch Configuration:

```<code>@Configuration
@EnableBatchProcessing
public class ItemBatch {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    EntityManagerFactory entityManagerFactory;

    @Autowired
    MongoTemplate mongoTemplate;

    @Bean
    public Job readDB2() {
        return jobBuilderFactory.get("readDB2").start(step1()).build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Itm, com.test.model.mongodb.Itm> chunk(5)
                .reader(reader())
                .writer(writer())
                .build();
    }

    @Bean
    public ItemStreamReader<Itm> reader() {
        JpaPagingItemReader<Itm> databaseReader = new JpaPagingItemReader<>();
        try {
            databaseReader.setEntityManagerFactory(entityManagerFactory);
            JpaQueryProviderImpl<Itm> jpaQueryProvider = new JpaQueryProviderImpl<>();
            jpaQueryProvider.setQuery("Itm.findAll");
            databaseReader.setQueryProvider(jpaQueryProvider);
            databaseReader.setPageSize(10);
            databaseReader.afterPropertiesSet();
        } catch (Exception e) {
            System.err.println("Error :" + e);
        }
        return databaseReader;
    }

    @Bean
    public MongoItemWriter<com.test.model.mongodb.Itm> writer() {
        MongoItemWriter<com.test.model.mongodb.Itm> writer = new MongoItemWriter<>();
        try {
            writer.setTemplate(mongoTemplate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        writer.setCollection("itm");
        return writer;
    }
}
</code>```

In-Memory Configuration instead of metadata:

```<code>@Configuration
public class SpringBatchTestConfiguration {

    @Bean
    public ResourcelessTransactionManager transactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager txManager)
            throws Exception {
        MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(txManager);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean
    public JobRepository jobRepository(MapJobRepositoryFactoryBean factory) throws Exception {
        return factory.getObject();
    }

    @Bean
    public JobExplorer jobExplorer(MapJobRepositoryFactoryBean factory) {
        return new SimpleJobExplorer(factory.getJobInstanceDao(), factory.getJobExecutionDao(),
                factory.getStepExecutionDao(), factory.getExecutionContextDao());
    }

    @Bean
    public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
        SimpleJobLauncher launcher = new SimpleJobLauncher();
        launcher.setJobRepository(jobRepository);
        return launcher;
    }
}
</code>```

QueryProvider:

```<code>public class JpaQueryProviderImpl<E> extends AbstractJpaQueryProvider {

    private Class<E> entityClass;
    private String query;

    @Override
    public Query createQuery() {
        return getEntityManager().createNamedQuery(query, entityClass);
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public void setEntityClass(Class<E> entityClazz) {
        this.entityClass = entityClazz;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.isTrue(StringUtils.hasText(query), "Query cannot be empty");
        Assert.notNull(entityClass, "Entity class cannot be NULL");
    }
}
</code>```

Entity:

```<code>@Entity
@Table(name="ITM")
@NamedQueries({ @NamedQuery(name = "Itm.findAll", query = "select i from Itm i") })
public class Itm implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="ITEM_NBR")
    private int itemId;

    @Column(name="ITM_DES_TXT")
    private String itmDesTxt;

    //getter and setter

}
</code>```

答:
The root cause is this error:

DB2 SQL Error: SQLCODE=-199, SQLSTATE=42601, SQLERRMC=OF;;??( [ DESC ASC NULLS RANGE CONCAT || / MICROSECONDS MICROSECOND, DRIVER=4.18.60

which points you to the OF keyword being unexpected.

ORDER BY ORDER OF in the OLAP specification is not valid in Db2 for z/OS v11, as can be seen in the manual. You'll need to rewrite your statement to order by some explicit expression -- or skip ORDER BY altogether since you're not ordering the inner2_ subselect anyway.

Body:
I need to fetch all the data from Db2 table and copy to mongoDB. I am using Spring batch without metadata tables. I am using JpaPagingItemReader for fetching data from Db2. I am able to get the data from Db2 for the first fetch which based on the PageSize attribute and save in mongoDB successfully but for the next set of data, getting error in fetching the data with the pagination.

Below given the Error:

15:17:36,085 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.084  INFO 7088 --- [ default task-2] c.t.controller.ItemController   : About to copy All Item
15:17:36,135 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.135  INFO 7088 --- [ default task-2] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=readDB2]] launched with the following parameters: [{}]
15:17:36,180 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.180  INFO 7088 --- [ default task-2] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
15:17:36,215 INFO  [stdout] (default task-2) Hibernate: select itm0_.itm_nbr as t1_4_, itm0_.itm_des_txt as itm_des13_4_ from itm itm0_ fetch first 10 rows only
15:17:36,884 INFO  [stdout] (default task-2) 2017-12-06 15:17:36.884 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:38,621 INFO  [stdout] (default task-2) 2017-12-06 15:17:38.621  INFO 7088 --- [ default task-2] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:1998}] to lxmdbpmdmdev001:27017
15:17:38,894 INFO  [stdout] (default task-2) 2017-12-06 15:17:38.894 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,139 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.139 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,386 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.386 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,632 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.632 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:39,881 INFO  [stdout] (default task-2) 2017-12-06 15:17:39.881 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,123 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.123 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,377 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.377 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,619 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.619 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]
15:17:40,865 INFO  [stdout] (default task-2) 2017-12-06 15:17:40.865 DEBUG 7088 --- [ default task-2] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, itmDesTxt, itemId]

15:17:41,109 INFO  [stdout] (default task-2) Hibernate: select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( select itm0_.itm_nbr as t1_4_, itm0_.itm_des_txt as itm_des13_4_ from itm itm0_ fetch first 20 rows only ) as inner2_ ) as inner1_ where rownumber_ > 10 order by rownumber_

15:17:41,346 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: -199, SQLState: 42601
15:17:41,347 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) DB2 SQL Error: SQLCODE=-199, SQLSTATE=42601, SQLERRMC=OF;;??( [ DESC ASC NULLS RANGE CONCAT || / MICROSECONDS MICROSECOND, DRIVER=4.18.60
15:17:41,347 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: -516, SQLState: 26501
15:17:41,347 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) DB2 SQL Error: SQLCODE=-516, SQLSTATE=26501, SQLERRMC=null, DRIVER=4.18.60
15:17:41,347 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: -514, SQLState: 26501
15:17:41,347 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) DB2 SQL Error: SQLCODE=-514, SQLSTATE=26501, SQLERRMC=SQL_CURLN200C1, DRIVER=4.18.60
15:17:41,362 INFO  [stdout] (default task-2) 2017-12-06 15:17:41.362 ERROR 7088 --- [ default task-2] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step1 in job readDB2

15:17:41,362 INFO  [stdout] (default task-2)
15:17:41,362 INFO  [stdout] (default task-2) javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
15:17:41,362 INFO  [stdout] (default task-2)    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
15:17:41,362 INFO  [stdout] (default task-2)    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
15:17:41,362 INFO  [stdout] (default task-2)    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:492) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.item.database.JpaPagingItemReader.doReadPage(JpaPagingItemReader.java:225) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,362 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:157) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:110) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,363 INFO  [stdout] (default task-2)    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
15:17:41,376 INFO  [stdout] (default task-2)    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.8.RELEASE.jar:3.0.8.RELEASE]

15:17:41,376 INFO  [stdout] (default task-2)    at com.test.service.impl.ItemServiceImpl.itemCopy(ItemServiceImpl.java:266) [classes:na]
15:17:41,376 INFO  [stdout] (default task-2)    at com.test.controller.ItemController.allItemCopy(ItemController.java:48) [classes:na]

....

15:17:41,410 INFO  [stdout] (default task-2) 2017-12-06 15:17:41.410  INFO 7088 --- [ default task-2] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=readDB2]] completed with the following parameters: [{}] and the following status: [FAILED]

Batch Configuration:

@Configuration
@EnableBatchProcessing
public class ItemBatch {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    EntityManagerFactory entityManagerFactory;

    @Autowired
    MongoTemplate mongoTemplate;

    @Bean
    public Job readDB2() {
        return jobBuilderFactory.get("readDB2").start(step1()).build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Itm, com.test.model.mongodb.Itm> chunk(5)
                .reader(reader())
                .writer(writer())
                .build();
    }

    @Bean
    public ItemStreamReader<Itm> reader() {
        JpaPagingItemReader<Itm> databaseReader = new JpaPagingItemReader<>();
        try {
            databaseReader.setEntityManagerFactory(entityManagerFactory);
            JpaQueryProviderImpl<Itm> jpaQueryProvider = new JpaQueryProviderImpl<>();
            jpaQueryProvider.setQuery("Itm.findAll");
            databaseReader.setQueryProvider(jpaQueryProvider);
            databaseReader.setPageSize(10);
            databaseReader.afterPropertiesSet();
        } catch (Exception e) {
            System.err.println("Error :" + e);
        }
        return databaseReader;
    }

    @Bean
    public MongoItemWriter<com.test.model.mongodb.Itm> writer() {
        MongoItemWriter<com.test.model.mongodb.Itm> writer = new MongoItemWriter<>();
        try {
            writer.setTemplate(mongoTemplate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        writer.setCollection("itm");
        return writer;
    }
}

In-Memory Configuration instead of metadata:

@Configuration
public class SpringBatchTestConfiguration {

    @Bean
    public ResourcelessTransactionManager transactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager txManager)
            throws Exception {
        MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(txManager);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean
    public JobRepository jobRepository(MapJobRepositoryFactoryBean factory) throws Exception {
        return factory.getObject();
    }

    @Bean
    public JobExplorer jobExplorer(MapJobRepositoryFactoryBean factory) {
        return new SimpleJobExplorer(factory.getJobInstanceDao(), factory.getJobExecutionDao(),
                factory.getStepExecutionDao(), factory.getExecutionContextDao());
    }

    @Bean
    public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
        SimpleJobLauncher launcher = new SimpleJobLauncher();
        launcher.setJobRepository(jobRepository);
        return launcher;
    }
}

QueryProvider:

public class JpaQueryProviderImpl<E> extends AbstractJpaQueryProvider {

    private Class<E> entityClass;
    private String query;

    @Override
    public Query createQuery() {
        return getEntityManager().createNamedQuery(query, entityClass);
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public void setEntityClass(Class<E> entityClazz) {
        this.entityClass = entityClazz;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.isTrue(StringUtils.hasText(query), "Query cannot be empty");
        Assert.notNull(entityClass, "Entity class cannot be NULL");
    }
}

Entity:

@Entity
@Table(name="ITM")
@NamedQueries({ @NamedQuery(name = "Itm.findAll", query = "select i from Itm i") })
public class Itm implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="ITEM_NBR")
    private int itemId;

    @Column(name="ITM_DES_TXT")
    private String itmDesTxt;

    //getter and setter

}


来源: stackexchange

问:
Force browser to disable horizontal bar even when you ZOOMING in at 150%
How do i force the browser to disable horizontal bar even when you are viewing your web content at 125% - 150%?</p>

答:
This will disable when zoomed.  Add this to your CSS file.</p>

```<code>html{overflow:hidden;}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This will disable when zoomed.  Add this to your CSS file.

html{overflow:hidden;}


问:
Does Flash have equivalent of tag property like for .net winform controls?
In winform you can have a tag property which is a custom property where you can put any stuff you want so that you don't need to create a custom component just for adding a new property.

Is this exist in Flash ?

答:
I'm not sure if I'm exactly understanding you, but it sounds like you want the ability to add a property to a custom class without having to declare that property in the class definition?

If that's the case, you'll want to use the "Dynamic" keyword on your class. "public dynamic class MyClass extends Whatever" - then you can say var myInstance:MyClass = new MyClass() and you can say myInstance.randomPropertyThatIJustMadeUp = whatever.

Does that make sense? Is that what you're looking for? Note that certain AS3 core classes already dynamic, including Object and MovieClip.

Finally, note that there is a good reason why that's not turned on by default. It's often not the best practice to use dynamic classes, it can slow down the player and lead to errors because you are negating the benefits of type checking. There are cases, though, where it's useful.

Good luck!

ContentLicense: CC BY-SA 2.5


问:
Custom JSS theme overwrites material UI theme?
I'm using JSS themes to style my components, but it seems my custom JSS theme overwrites the JSS theme used by the Material UI components. I'm using material-ui 1.0.0-beta.22

It looks something like this:

```<code>import React from 'react
import injectSheet, {ThemeProvider} from 'react-jss
import Dialog from 'material-ui/Dialog'

const theme = {
  background: 'blue'
}

const styles = theme => ({
  container: {
    background: theme.background,
  }
})

const Demo = () => (
  <ThemeProvider theme={theme}>
    <div className={props.classes.demo}>
      <Dialog />
    </div>
  </ThemeProvider>
)

export default injectSheet(styles)(Demo)
</code>```

When rendering this component, it causes the following error:

```<code>Uncaught TypeError: Cannot read property 'unit' of undefined
    at styles (Dialog.js?9662:87)
    at Object.create (getStylesCreator.js?6ed6:29)
    at Style.attach (withStyles.js?deb5:328)
    at Style.componentWillMount (withStyles.js?deb5:258)
    at callComponentWillMount (react-dom.development.js?cada:9777)
    at mountClassInstance (react-dom.development.js?cada:9834)
    at updateClassComponent (react-dom.development.js?cada:10216)
    at beginWork (react-dom.development.js?cada:10605)
    at performUnitOfWork (react-dom.development.js?cada:12573)
    at workLoop (react-dom.development.js?cada:12682)
</code>```

The Material UI Dialog component tries to access props.theme.spacing.unit, but no such property exists, as the whole theme has been overwritten by my custom theme.

Not sure if this is a bug or if I'm doing something wrong? Shouldn't JSS themes at least be merged? Am I missing some Material UI theming config?

答: Yes, they are using the same provider. If you want a different theming for your react-jss components, you can setup https://github.com/cssinjs/react-jss#theming a new namespace for theming, see "createTheming"</p>

Body:
I'm using JSS themes to style my components, but it seems my custom JSS theme overwrites the JSS theme used by the Material UI components. I'm using material-ui 1.0.0-beta.22

It looks something like this:

import React from 'react
import injectSheet, {ThemeProvider} from 'react-jss
import Dialog from 'material-ui/Dialog'

const theme = {
  background: 'blue'
}

const styles = theme => ({
  container: {
    background: theme.background,
  }
})

const Demo = () => (
  <ThemeProvider theme={theme}>

      <Dialog />

  </ThemeProvider>
)

export default injectSheet(styles)(Demo)

When rendering this component, it causes the following error:

Uncaught TypeError: Cannot read property 'unit' of undefined
    at styles (Dialog.js?9662:87)
    at Object.create (getStylesCreator.js?6ed6:29)
    at Style.attach (withStyles.js?deb5:328)
    at Style.componentWillMount (withStyles.js?deb5:258)
    at callComponentWillMount (react-dom.development.js?cada:9777)
    at mountClassInstance (react-dom.development.js?cada:9834)
    at updateClassComponent (react-dom.development.js?cada:10216)
    at beginWork (react-dom.development.js?cada:10605)
    at performUnitOfWork (react-dom.development.js?cada:12573)
    at workLoop (react-dom.development.js?cada:12682)

The Material UI Dialog component tries to access props.theme.spacing.unit, but no such property exists, as the whole theme has been overwritten by my custom theme.

Not sure if this is a bug or if I'm doing something wrong? Shouldn't JSS themes at least be merged? Am I missing some Material UI theming config?


问:
Redirect to default in Web Api Authorize
My problem: When a session expires user still can perform an action (search). Action results are some garbage (controller is not visited). I don't know why; I just want to redirect a user to login page.

My plan is to make custom Authorize and override HandleUnauthorizedRequest(HttpActionContext) and redirect a user to index.
I have no idea how to redirect to my default page.

Sample code:

```<code>public class SessionTimeoutAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        base.HandleUnauthorizedRequest(actionContext);
        //redirect here
    }
}
</code>```

答:
I thought I can redirect to site directly from Web API... Well, I can't. Turned out I don't need custom Authorize, because [Authorize] redirect correctly. I need my client to redirect when Authorize wants. In my case (Angular 1,5) it was an interceptor.

```<code>app.service('httpRedirectInterceptor', ['$window', function ($window) {
this.response = function (redirection) {
    if (typeof redirection.data === 'string') {
        if (redirection.data.indexOf instanceof Function &&
            redirection.data.indexOf('id="app-login-page"') != -1) {
            $window.location.pathname = "/Account/Login";
        }
    }
    return redirection;
};

this.request = function (req) {
    var elem = angular.element(document.body).find('div[ncg-request-verification-token]').attr('ncg-request-verification-token');
    req.headers['RequestVerificationToken'] = elem || "no request verification token";

    return req;
};}]);
</code>```

and in app.config

```<code>$httpProvider.interceptors.
push('httpRedirectInterceptor');
</code>```

Body:
My problem: When a session expires user still can perform an action (search). Action results are some garbage (controller is not visited). I don't know why; I just want to redirect a user to login page.

My plan is to make custom Authorize and override HandleUnauthorizedRequest(HttpActionContext) and redirect a user to index.
I have no idea how to redirect to my default page.

Sample code:

public class SessionTimeoutAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        base.HandleUnauthorizedRequest(actionContext);
        //redirect here
    }
}

Body:
I thought I can redirect to site directly from Web API... Well, I can't. Turned out I don't need custom Authorize, because [Authorize] redirect correctly. I need my client to redirect when Authorize wants. In my case (Angular 1,5) it was an interceptor.

app.service('httpRedirectInterceptor', ['$window', function ($window) {
this.response = function (redirection) {
    if (typeof redirection.data === 'string') {
        if (redirection.data.indexOf instanceof Function &&
            redirection.data.indexOf('id="app-login-page"') != -1) {
            $window.location.pathname = "/Account/Login";
        }
    }
    return redirection;
};

this.request = function (req) {
    var elem = angular.element(document.body).find('div[ncg-request-verification-token]').attr('ncg-request-verification-token');
    req.headers['RequestVerificationToken'] = elem || "no request verification token";

    return req;
};}]);

and in app.config

$httpProvider.interceptors.
push('httpRedirectInterceptor');


问:
Loss of precision when casting Math.pow()
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

```<code>2_147_483_647
</code>```

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

```<code>System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);
</code>```

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

答:
A cast has precedence over subtraction. You should rather do the subtraction first:

```<code> System.out.println((int) (Math.pow(2, 31) - 1));
</code>```

Math.pow(2, 31) is 2_147_483_648 with a type of double (since Math.pow() returns a double) , this number does not fit into an int.

When you cast the double 2_147_483_648 to an int, it gets truncated to the largest value an int can hold (see How does double to int cast work in Java).

The cast truncates the double 2_147_483_648 to the int 2_147_483_647.

Then your code subtracts 1, and ends up with   2_147_483_646.

Body:
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

2_147_483_647

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

Body:
A cast has precedence over subtraction. You should rather do the subtraction first:

 System.out.println((int) (Math.pow(2, 31) - 1));

Math.pow(2, 31) is 2_147_483_648 with a type of double (since Math.pow() returns a double) , this number does not fit into an int.

When you cast the double 2_147_483_648 to an int, it gets truncated to the largest value an int can hold (see How does double to int cast work in Java).

The cast truncates the double 2_147_483_648 to the int 2_147_483_647.

Then your code subtracts 1, and ends up with   2_147_483_646.


问:
wso2 esb enrich text in xml
I'm trying to enrich the text of an XML-Node with WSO2 ESB Version 4.9.0.

Simple XML:

```<code><enrich>
    <source type="inline">
        <query><where><order.id>0</order.id></where></query>
    </source>
    <target type="body" />
</enrich>
</code>```

Enrich:

```<code><enrich>
    <source type="property" property="uri.var.processId" />
    <target action="replace" type="body" xpath="//order.id/text()" />
</enrich>
</code>```

But the output looks like this:

```<code><query xmlns="http://ws.apache.org/ns/synapse"><where><order.id>0</order.id></where>SOHBSS-000002</query>
</code>```

When I was expecting this:

```<code><query xmlns="http://ws.apache.org/ns/synapse"><where><order.id>SOHBSS-000002</order.id></where></query>
</code>```

When I even more simplify the given XML to <order.id>0</order.id> the same enrich mediator from above, gives the correct <order.id xmlns="http://ws.apache.org/ns/synapse">SOHBSS-000002</order.id> output.

Is the xpath wrong? Or am I using the enrich mediator for something that it's not made for?

Because the XML is simple, I'm trying to not us XSLT to do the change.

答:
I had some tough time trying to do an xpath on tags with namespaces, so here it is (thanks Lesrac for yor comments about xmlns)</p>

```<code><enrich>
    <source type="inline">
        <query namespace="http://www.fadata.bg/Insurance_Messages/v3.0/xml/">
          <where><order.id>0</order.id></where></query>
    </source>
    <target type="body" />
</enrich>
<enrich>
    <source type="property" property="uri.var.processId" />
    <target action="replace" type="custom" xpath="//fadata:order.id/text()"
       xmlns:fadata="http://www.fadata.bg/Insurance_Messages/v3.0/xml/"/>
</enrich>
</code>```

Title: wso2 esb enrich text in xml

Body:
I'm trying to enrich the text of an XML-Node with WSO2 ESB Version 4.9.0.

Simple XML:

<enrich>
    <source type="inline">
        <query><where><order.id>0</order.id></where></query>
    </source>
    <target type="body" />
</enrich>

Enrich:

<enrich>
    <source type="property" property="uri.var.processId" />
    <target action="replace" type="body" xpath="//order.id/text()" />
</enrich>

But the output looks like this:

<query xmlns="http://ws.apache.org/ns/synapse"><where><order.id>0</order.id></where>SOHBSS-000002</query>

When I was expecting this:

<query xmlns="http://ws.apache.org/ns/synapse"><where><order.id>SOHBSS-000002</order.id></where></query>

When I even more simplify the given XML to <order.id>0</order.id> the same enrich mediator from above, gives the correct <order.id xmlns="http://ws.apache.org/ns/synapse">SOHBSS-000002</order.id> output.

Is the xpath wrong? Or am I using the enrich mediator for something that it's not made for?

Because the XML is simple, I'm trying to not us XSLT to do the change.

Body:
I had some tough time trying to do an xpath on tags with namespaces, so here it is (thanks Lesrac for yor comments about xmlns)

<enrich>
    <source type="inline">
        <query namespace="http://www.fadata.bg/Insurance_Messages/v3.0/xml/">
          <where><order.id>0</order.id></where></query>
    </source>
    <target type="body" />
</enrich>
<enrich>
    <source type="property" property="uri.var.processId" />
    <target action="replace" type="custom" xpath="//fadata:order.id/text()"
       xmlns:fadata="http://www.fadata.bg/Insurance_Messages/v3.0/xml/"/>
</enrich>


问:
Store items in sessionStorage that has ben pushed in another function
I've a slight problem with my code.

I have an array that stores values and i need to store them into sessionStorage.

```<code>document.getElementById("submit-button").addEventListener("click", book, false);

var array = new Array;

function book()
{

 var seat;

 // value in label that is changed everytime i click on a element.
 seat = document.getElementById("label").innerHTML;

 // Put it in a global array
 array.push(seat);
 window.sessionStorage.setItem("items", JSON.stringify(array));

 booked(seat);

}
</code>```

and in load() function:

```<code>function load()
 {
  var storedArray = JSON.parse(window.sessionStorage.getItem("items"));

  for (var i = 0; i < storedArray.length; i++)
  {
    var str1 = "seat";
    var str2 = storedArray[i];

    var number = document.getElementById(str1.concat(str2));
    var context = number.getContext("2d");
    context.fillStyle = 'red';
    context.fillRect(0,0, seat18.width, seat18.height);
  }

 }
</code>```

But my problem is that every time i call book() function, the array resets itself and pushing the new value. And in load() function, the storedArray in only register the newest value from the Array.

First, i want to store every value that is made in book() in global array and get every value in load() from getItem. How can i make that possible?

答: To clarify. So I want my array (which is converted to a string) inserted into SetItem in sessionStorage to be stored each time I use book (). Then each string will be presented in getItem in load ().</p>

Body:
I've a slight problem with my code.

I have an array that stores values and i need to store them into sessionStorage.

document.getElementById("submit-button").addEventListener("click", book, false);

var array = new Array;

function book()
{

 var seat;

 // value in label that is changed everytime i click on a element.
 seat = document.getElementById("label").innerHTML;

 // Put it in a global array
 array.push(seat);
 window.sessionStorage.setItem("items", JSON.stringify(array));

 booked(seat);

}

and in load() function:

function load()
 {
  var storedArray = JSON.parse(window.sessionStorage.getItem("items"));

  for (var i = 0; i < storedArray.length; i++)
  {
    var str1 = "seat";
    var str2 = storedArray[i];

    var number = document.getElementById(str1.concat(str2));
    var context = number.getContext("2d");
    context.fillStyle = 'red';
    context.fillRect(0,0, seat18.width, seat18.height);
  }

 }

But my problem is that every time i call book() function, the array resets itself and pushing the new value. And in load() function, the storedArray in only register the newest value from the Array.

First, i want to store every value that is made in book() in global array and get every value in load() from getItem. How can i make that possible?


问:
Converting Individual Excel Sheets as Individual PDF Files
I am just trying to use VBA to create create/save individual excel sheets as individual PDF files.

I came across this online:

```<code>Sub SaveWorksheetsAsPDFs()
Dim sFile       As String
Dim sPath       As String
Dim wks         As Worksheet

With ActiveWorkbook
    sPath = .Path & "\"
    For Each wks In .Worksheets
            sFile = wks.Name & ".pdf"
            wks.ExportAsFixedFormat Type:=xlTypePDF, _
                                    Filename:=sPath & sFile, _
                                    Quality:=xlQualityStandard, _
                                    IncludeDocProperties:=False, _
                                    IgnorePrintAreas:=False, _
                                    OpenAfterPublish:=False
    Next wks
End With
End Sub
</code>```

However, I'm getting the following error:

Run-time error '5':
  Invalid procedure call or argument

For someone not 100% familiar with VBA, what's invalid?

Thanks

答:
As I said in my comment, your code runs fine (Win-10, Excel-365).  I first:

Saved the .xlsm file to insure Spath exists
Selected an area on each worksheet to insure it will be PDF'ed correctly

Body:
I am just trying to use VBA to create create/save individual excel sheets as individual PDF files.

I came across this online:

Sub SaveWorksheetsAsPDFs()
Dim sFile       As String
Dim sPath       As String
Dim wks         As Worksheet

With ActiveWorkbook
    sPath = .Path & "\"
    For Each wks In .Worksheets
            sFile = wks.Name & ".pdf"
            wks.ExportAsFixedFormat Type:=xlTypePDF, _
                                    Filename:=sPath & sFile, _
                                    Quality:=xlQualityStandard, _
                                    IncludeDocProperties:=False, _
                                    IgnorePrintAreas:=False, _
                                    OpenAfterPublish:=False
    Next wks
End With
End Sub

However, I'm getting the following error:

Run-time error '5':
  Invalid procedure call or argument

For someone not 100% familiar with VBA, what's invalid?

Thanks


问:
Generic Set of Suppliers of Sets
I am trying to create a Set of Suppliers of Sets. The inner set can be of any type (String, Number, etc...). I want to be able to both add Suppliers to this Set, and retrieve them. When I retrieve them, I understand that I won't know what type of Set the Supplier is returning, and am ok with it being a Supplier<Set<Object>>. How do I declare this Set?

I tried

1.

```<code>Set<Supplier<Set>>
</code>```

Which works, but then I'm not generic-izing the inner Set, which seems wrong

2.

```<code>Set<Supplier<Set<Object>>>
</code>```

But then I can't add a Supplier<Set<String>>

3.

```<code>Set<Supplier<Set<?>>>
</code>```

But I still can't add the above (and won't be able to take anything out of that set, I imagine)

Any ideas?

答:
Declare as Set<Supplier<? extends Set<?>>>.
I think the reason why it works is because Supplier<?> is the supertype of any Supplier, and Supplier<? extends Set<?>> is the supertype of any Set Supplier. WhileSupplier<Set<?>> is not the same type as any concrete typed Set Supplier for example Supplier<Set<String>>.

Title: Generic Set of Suppliers of Sets

Body:
I am trying to create a Set of Suppliers of Sets. The inner set can be of any type (String, Number, etc...). I want to be able to both add Suppliers to this Set, and retrieve them. When I retrieve them, I understand that I won't know what type of Set the Supplier is returning, and am ok with it being a Supplier<Set<Object>>. How do I declare this Set?

I tried

1.

Set<Supplier<Set>>

Which works, but then I'm not generic-izing the inner Set, which seems wrong

2.

Set<Supplier<Set<Object>>>

But then I can't add a Supplier<Set<String>>

3.

Set<Supplier<Set<?>>>

But I still can't add the above (and won't be able to take anything out of that set, I imagine)

Any ideas?


问:
react-native add fragment to view is not showing
I have added a dynamic generated FrameLayout to a react-native view. The Framelayout is showing up. but when I add a fragment to the view, nothing is showing.

here is a part of the code:

```<code>    public FrameLayout createViewInstance(ThemedReactContext context) {

            Fragment fragment = MapFragment.newInstance(mapKey);
            FrameLayout view = new FrameLayout(context);
            view.setWillNotDraw(false);

            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            view.setLayoutParams(lp);

            view.setId(View.generateViewId());

            view.setBackgroundColor(Color.parseColor("#1FFDDB"));

            FragmentActivity activity = MainActivity.getFragmentActivity();

            FragmentManager fragmentManager = activity.getSupportFragmentManager();

            fragmentManager.beginTransaction().remove(fragment).commit();
            fragmentManager.executePendingTransactions();

            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.add(0, fragment);

            fragmentTransaction.show(fragment);
            fragmentTransaction.attach(fragment);
            fragmentTransaction.commit();
            fragmentManager.executePendingTransactions();
            return view;
        }
</code>```

When I add a TextView to the view it is showing:

```<code>// add a textfield to the view
TextView textView1 = new TextView(context);
textView1.setText("Android");
textView1.setTextSize(30);
textView1.setGravity(Gravity.CENTER);

view.setVisibility(View.VISIBLE);

view.addView(textView1);
</code>```

so there is an issue with the Fragment.
any ideas why the fragment is not showing up?

答:
I also encountered this problem and found the solution.

Android side:
First, create a layout_container.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
</code>```

Then inflate it in createViewInstance method and define function to add fragment to the container.

```<code>@Override
public String getName() {
    return "ExampleFragment";
}
@Override
protected View createViewInstance(ThemedReactContext reactContext) {
    mContext = context;
    LinearLayout root = (LinearLayout) LayoutInflater.from(reactContext)
                .inflate(R.layout.layout_container, null);
    return root;
}

@Nullable
@Override
public Map<String, Integer> getCommandsMap() {
    return MapBuilder.of(
            "create", COMMAND_CREATE
    );

}

@Override
public void receiveCommand(View view, int commandId, @Nullable ReadableArray args) {
    Log.d(TAG, "receiveCommand: " + commandId);
    switch (commandId) {
        case COMMAND_CREATE:
            createFragment();
            break;
    }
}

private void createFragment() {
    MapFragment mapFragment = new MapFragment();
    mContext.getCurrentActivity()
            .getFragmentManager()
            .beginTransaction()
            .add(R.id.container, mapFragment)
            .commit();
}
</code>```

RN side:
create Native UI Component Fragment.js

```<code>import {NativeModules, requireNativeComponent, View, UIManager, findNodeHandle} from 'react-native';
const fragmentIFace = {
  name: "Fragment",
  propTypes: {
    ...View.propTypes,
  }
};
const NativeFragment = requireNativeComponent("ExampleFragment", fragmentIFace);
class ExampleFragment extends Component {
  fragment;
  render() {
    return <NativeFragment
      ref={c => this.fragment = c}
      {...this.props} style={{flex: 1}}/>
  }

  create = () => {
    UIManager.dispatchViewManagerCommand(
      findNodeHandle(this.fragment),
      UIManager.MapFragment.Commands.create,
      [] // No args
    )
  }
export default ExampleFragment
</code>```

then you can use it in RN.

```<code>class App extends Component {
    componentDidMount() {
        this.fragment.create();
    }
    render() {
        return (
            <View>
                <ExampleFragment ref={r=>this.fragment = r} />
            </View>
        );
    }
}
</code>```

Here's the explanation:

In your code, you try to add fragment to the view which cannot be a fragment container.

Usually, View.generateViewId() will return id 0x1 which is duplicated  with ReactRootView by coincidence so that your app will not crash. If you set other id to the container view, you will get exception and app will crash because the id of your view can not be found from current app's layout.

You can check it with Layout Inspector in Android Studio.

To prevent from duplication of ids, the best way is defining them in xml.
And that's why I inflate a root view from xml.

But if you set id for the root(LinearLayout in my example), the id will be removed by RN when it is added, so the child is necessary.

After RN get the root view(didComponentMount()), then you need to call create() from RN component, and you can see it.

Body:
I have added a dynamic generated FrameLayout to a react-native view. The Framelayout is showing up. but when I add a fragment to the view, nothing is showing.

here is a part of the code:

    public FrameLayout createViewInstance(ThemedReactContext context) {

            Fragment fragment = MapFragment.newInstance(mapKey);
            FrameLayout view = new FrameLayout(context);
            view.setWillNotDraw(false);

            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            view.setLayoutParams(lp);

            view.setId(View.generateViewId());

            view.setBackgroundColor(Color.parseColor("#1FFDDB"));

            FragmentActivity activity = MainActivity.getFragmentActivity();

            FragmentManager fragmentManager = activity.getSupportFragmentManager();

            fragmentManager.beginTransaction().remove(fragment).commit();
            fragmentManager.executePendingTransactions();

            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.add(0, fragment);

            fragmentTransaction.show(fragment);
            fragmentTransaction.attach(fragment);
            fragmentTransaction.commit();
            fragmentManager.executePendingTransactions();
            return view;
        }

When I add a TextView to the view it is showing:

// add a textfield to the view
TextView textView1 = new TextView(context);
textView1.setText("Android");
textView1.setTextSize(30);
textView1.setGravity(Gravity.CENTER);

view.setVisibility(View.VISIBLE);

view.addView(textView1);

so there is an issue with the Fragment.
any ideas why the fragment is not showing up?

Body:
I also encountered this problem and found the solution.

Android side:
First, create a layout_container.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Then inflate it in createViewInstance method and define function to add fragment to the container.

@Override
public String getName() {
    return "ExampleFragment";
}
@Override
protected View createViewInstance(ThemedReactContext reactContext) {
    mContext = context;
    LinearLayout root = (LinearLayout) LayoutInflater.from(reactContext)
                .inflate(R.layout.layout_container, null);
    return root;
}

@Nullable
@Override
public Map<String, Integer> getCommandsMap() {
    return MapBuilder.of(
            "create", COMMAND_CREATE
    );

}

@Override
public void receiveCommand(View view, int commandId, @Nullable ReadableArray args) {
    Log.d(TAG, "receiveCommand: " + commandId);
    switch (commandId) {
        case COMMAND_CREATE:
            createFragment();
            break;
    }
}

private void createFragment() {
    MapFragment mapFragment = new MapFragment();
    mContext.getCurrentActivity()
            .getFragmentManager()
            .beginTransaction()
            .add(R.id.container, mapFragment)
            .commit();
}

RN side:
create Native UI Component Fragment.js

import {NativeModules, requireNativeComponent, View, UIManager, findNodeHandle} from 'react-native';
const fragmentIFace = {
  name: "Fragment",
  propTypes: {
    ...View.propTypes,
  }
};
const NativeFragment = requireNativeComponent("ExampleFragment", fragmentIFace);
class ExampleFragment extends Component {
  fragment;
  render() {
    return <NativeFragment
      ref={c => this.fragment = c}
      {...this.props} style={{flex: 1}}/>
  }

  create = () => {
    UIManager.dispatchViewManagerCommand(
      findNodeHandle(this.fragment),
      UIManager.MapFragment.Commands.create,
      [] // No args
    )
  }
export default ExampleFragment

then you can use it in RN.

class App extends Component {
    componentDidMount() {
        this.fragment.create();
    }
    render() {
        return (
            <View>
                <ExampleFragment ref={r=>this.fragment = r} />
            </View>
        );
    }
}

Here's the explanation:

In your code, you try to add fragment to the view which cannot be a fragment container.

Usually, View.generateViewId() will return id 0x1 which is duplicated  with ReactRootView by coincidence so that your app will not crash. If you set other id to the container view, you will get exception and app will crash because the id of your view can not be found from current app's layout.

You can check it with Layout Inspector in Android Studio.

To prevent from duplication of ids, the best way is defining them in xml.
And that's why I inflate a root view from xml.

But if you set id for the root(LinearLayout in my example), the id will be removed by RN when it is added, so the child is necessary.

After RN get the root view(didComponentMount()), then you need to call create() from RN component, and you can see it.

ContentLicense: CC BY-SA 4.0


问:
jQuery - building a banner with a timeout
I want to build a banner that says "Loading", and hides when the application is done.

```<code><div id="ajaxBanner"></div>

function ajaxBanner(action, confirmMsg) {

    if (action == 'show') {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
    } else if (action == 'hide') {
        $('#ajaxBanner').fadeOut();
    } else if (confirmMsg == true) {
        $('#ajaxBanner').show();
        ajaxBanner_timeout = setTimeout(ajaxBanner('hide'), 2000);
    }
};
</code>```

The function shows a "Loading" banner message to the user and later hides it. The thing is, I also want to use this space for confirmation messages, like "XXXX Added to XXX".

The problem is, when confirmMsg is true, it is getting killed by a subsequent AJAX call with does Action show.

How can I say only do action==show or action==hide when the ajaxBanner_timeout is complete?

答:
One problem is setTimeout() does not take a function call it takes a string or an anonymous function try setTimeout("ajaxBanner('hide')", 2000);.  Right now the function is immediately called no pause.  Another method is

```<code>setTimeout(function(){
  //do something;
},2000);
</code>```

Note this is the better way.

Body:
I want to build a banner that says "Loading", and hides when the application is done.

function ajaxBanner(action, confirmMsg) {

    if (action == 'show') {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
    } else if (action == 'hide') {
        $('#ajaxBanner').fadeOut();
    } else if (confirmMsg == true) {
        $('#ajaxBanner').show();
        ajaxBanner_timeout = setTimeout(ajaxBanner('hide'), 2000);
    }
};

The function shows a "Loading" banner message to the user and later hides it. The thing is, I also want to use this space for confirmation messages, like "XXXX Added to XXX".

The problem is, when confirmMsg is true, it is getting killed by a subsequent AJAX call with does Action show.

How can I say only do action==show or action==hide when the ajaxBanner_timeout is complete?

Body:
One problem is setTimeout() does not take a function call it takes a string or an anonymous function try setTimeout("ajaxBanner('hide')", 2000);.  Right now the function is immediately called no pause.  Another method is

setTimeout(function(){
  //do something;
},2000);

Note this is the better way.


问:
const already declared in ES6 switch block
Consider the file sample.es6

```<code>switch (1) {
    case 1:
        const foo = 1;
        break;
    case 2:
        const foo = 2;
        break;
}
</code>```

If I run it with Node I got

```<code>$ node --version
v4.2.11
$ node sample.es6
/tmp/sample.es6:6
const foo = 2;
^

SyntaxError: Identifier 'foo' has already been declared
    at Object.<anonymous> (/tmp/sample.es6:1:11)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:134:18)
    at node.js:961:3
</code>```

Why I'm getting this error? Node shouldn't evaluate const foo = 2;.

答:
If you'are expecting to create a scope inside case statement you should use  (IIFE) Immediately Invoked Function Expression. It will allow you to create additional scope that you need inside case statement.

```<code>function (value) {
   switch (value) {
     case 1:
       return (function() {
         const foo = 1
         return foo
       }())
       break;
     case 2:
       return (function() {
         const foo = 2
         return foo
       }())
       break;
   }
}
</code>```

Here is an example https://jsfiddle.net/hermanleus/e4ceq7xt/2/

Hope it helps

Body:
Consider the file sample.es6

switch (1) {
    case 1:
        const foo = 1;
        break;
    case 2:
        const foo = 2;
        break;
}

If I run it with Node I got

$ node --version
v4.2.11
$ node sample.es6
/tmp/sample.es6:6
const foo = 2;
^

SyntaxError: Identifier 'foo' has already been declared
    at Object.<anonymous> (/tmp/sample.es6:1:11)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:134:18)
    at node.js:961:3

Why I'm getting this error? Node shouldn't evaluate const foo = 2;.

Body:
If you'are expecting to create a scope inside case statement you should use  (IIFE) Immediately Invoked Function Expression. It will allow you to create additional scope that you need inside case statement.

function (value) {
   switch (value) {
     case 1:
       return (function() {
         const foo = 1
         return foo
       }())
       break;
     case 2:
       return (function() {
         const foo = 2
         return foo
       }())
       break;
   }
}

Here is an example https://jsfiddle.net/hermanleus/e4ceq7xt/2/

Hope it helps


问:
Python Primitive Pythagorean triple code not working

Currently trying to find all primitve pytagorean triples up to some number n, using the formula a = m^2-n^2, b = 2mn, c = m^2 + n^2. Here is the code:

```<code>    def prim(k):
        primlist=[]
        for m in range(1,k):
            for n in range(m+1,k+1):
                if m**2+n**2>k:
                    break
                if m%2==1 and n%2==1:
                    break
               if n**2-m**2==0 or 2*m*n ==0 or n**2+m**2==0:
                    break

                if gcd(m,n)!=1:
                    break

                primlist.append([n**2-m**2,2*m*n,n**2+m**2])
        return primlist
    print(prim(100))
</code>```

We expect to find all pythagorean triples, however some are missing, for example 20,21,29. Theres 16 with c under 100 however we only get 6. Cheers

答:
Apart from the first condition, where m & n are too large, you don't want to break out of the inner loop, simply continue on to the next iteration.

The following tests are completely superfluous, since with your m and n they can never be true.

```<code>if n**2-m**2==0 or 2*m*n ==0 or n**2+m**2==0:
</code>```

so I've removed them from the code. You didn't supply a gcd function, or import one from the standard library, so I've supplied my own.

```<code>def gcd(a, b):
    '''  Greatest common divisor of a & b '''
    while b:
        a, b = b, a % b
    return a

def prim(k):
    primlist=[]
    for m in range(1,k):
        for n in range(m+1,k+1):
            if m**2 + n**2 > k:
                break
            if m%2==1 and n%2==1:
                continue
            if gcd(m,n)!=1:
                continue

            primlist.append([n**2 - m**2, 2*m*n, n**2 + m**2])
    return primlist

print(prim(100))
</code>```

output

```<code>[[3, 4, 5], [15, 8, 17], [35, 12, 37], [63, 16, 65], [5, 12, 13], [21, 20, 29], [45, 28, 53], [77, 36, 85], [7, 24, 25], [55, 48, 73], [9, 40, 41], [33, 56, 65], [65, 72, 97], [11, 60, 61], [39, 80, 89], [13, 84, 85]]
</code>```

FWIW, here's a more efficient (and slightly more Pythonic) way to write that code. Rather than building a list, we make a generator. That way we can just print or consume the triples, and of course we can easily collect them into a list by doing, eg list(prim(100)).

```<code>def gcd(a, b):
    '''  Greatest common divisor of a & b '''
    while b:
        a, b = b, a % b
    return a

def prim(k):
    for m in range(1, k):
        for n in range(m+1, k+1):
            m2, n2 = m * m, n * n
            if m2 + n2 > k:
                break
            if m % 2 and n % 2:
                continue
            if gcd(m, n) > 1:
                continue

            yield n2 - m2, 2*m*n, n2 + m2

for i, t in enumerate(prim(100), 1):
    print(i, t)
</code>```

output

```<code>1 (3, 4, 5)
2 (15, 8, 17)
3 (35, 12, 37)
4 (63, 16, 65)
5 (5, 12, 13)
6 (21, 20, 29)
7 (45, 28, 53)
8 (77, 36, 85)
9 (7, 24, 25)
10 (55, 48, 73)
11 (9, 40, 41)
12 (33, 56, 65)
13 (65, 72, 97)
14 (11, 60, 61)
15 (39, 80, 89)
16 (13, 84, 85)
</code>```

Body:
Currently trying to find all primitve pytagorean triples up to some number n, using the formula a = m^2-n^2, b = 2mn, c = m^2 + n^2. Here is the code:

    def prim(k):
        primlist=[]
        for m in range(1,k):
            for n in range(m+1,k+1):
                if m**2+n**2>k:
                    break
                if m%2==1 and n%2==1:
                    break
               if n**2-m**2==0 or 2*m*n ==0 or n**2+m**2==0:
                    break

                if gcd(m,n)!=1:
                    break

                primlist.append([n**2-m**2,2*m*n,n**2+m**2])
        return primlist
    print(prim(100))

We expect to find all pythagorean triples, however some are missing, for example 20,21,29. Theres 16 with c under 100 however we only get 6. Cheers

Body:
Apart from the first condition, where m & n are too large, you don't want to break out of the inner loop, simply continue on to the next iteration.

The following tests are completely superfluous, since with your m and n they can never be true.

if n**2-m**2==0 or 2*m*n ==0 or n**2+m**2==0:

so I've removed them from the code. You didn't supply a gcd function, or import one from the standard library, so I've supplied my own.

def gcd(a, b):
    '''  Greatest common divisor of a & b '''
    while b:
        a, b = b, a % b
    return a

def prim(k):
    primlist=[]
    for m in range(1,k):
        for n in range(m+1,k+1):
            if m**2 + n**2 > k:
                break
            if m%2==1 and n%2==1:
                continue
            if gcd(m,n)!=1:
                continue

            primlist.append([n**2 - m**2, 2*m*n, n**2 + m**2])
    return primlist

print(prim(100))

output

[[3, 4, 5], [15, 8, 17], [35, 12, 37], [63, 16, 65], [5, 12, 13], [21, 20, 29], [45, 28, 53], [77, 36, 85], [7, 24, 25], [55, 48, 73], [9, 40, 41], [33, 56, 65], [65, 72, 97], [11, 60, 61], [39, 80, 89], [13, 84, 85]]

FWIW, here's a more efficient (and slightly more Pythonic) way to write that code. Rather than building a list, we make a generator. That way we can just print or consume the triples, and of course we can easily collect them into a list by doing, eg list(prim(100)).

def gcd(a, b):
    '''  Greatest common divisor of a & b '''
    while b:
        a, b = b, a % b
    return a

def prim(k):
    for m in range(1, k):
        for n in range(m+1, k+1):
            m2, n2 = m * m, n * n
            if m2 + n2 > k:
                break
            if m % 2 and n % 2:
                continue
            if gcd(m, n) > 1:
                continue

            yield n2 - m2, 2*m*n, n2 + m2

for i, t in enumerate(prim(100), 1):
    print(i, t)

output

1 (3, 4, 5)
2 (15, 8, 17)
3 (35, 12, 37)
4 (63, 16, 65)
5 (5, 12, 13)
6 (21, 20, 29)
7 (45, 28, 53)
8 (77, 36, 85)
9 (7, 24, 25)
10 (55, 48, 73)
11 (9, 40, 41)
12 (33, 56, 65)
13 (65, 72, 97)
14 (11, 60, 61)
15 (39, 80, 89)
16 (13, 84, 85)


答:
The problem is you are calling ajaxBanner('hide') in your setTimeout instead of passing in the function reference.  Wrapping your ajaxBanner('hide') in an anonymous function will solve the problem:

```<code> setTimeout(function() { ajaxBanner('hide'); }, 2000);
</code>```

Explanation/Test you can do in your JavaScript Console:

One way to see the difference is to paste this in your Firebug console and run it:

Good:

```<code> // alert fires in 5 seconds
 setTimeout(function() { alert('hide'); }, 5000);
</code>```

Bad:

```<code> // alert fires right away, despite the 5 second delay
 setTimeout(alert('hide'), 5000);
</code>```

UPDATE: Note that I am not assigning the setTimeout event to a variable as it's not needed in the above code example in the question.

Title: jQuery - building a banner with a timeout

Body:
The problem is you are calling ajaxBanner('hide') in your setTimeout instead of passing in the function reference.  Wrapping your ajaxBanner('hide') in an anonymous function will solve the problem:

 setTimeout(function() { ajaxBanner('hide'); }, 2000);

Explanation/Test you can do in your JavaScript Console:

One way to see the difference is to paste this in your Firebug console and run it:

Good:

 // alert fires in 5 seconds
 setTimeout(function() { alert('hide'); }, 5000);

Bad:

 // alert fires right away, despite the 5 second delay
 setTimeout(alert('hide'), 5000);

UPDATE: Note that I am not assigning the setTimeout event to a variable as it's not needed in the above code example in the question.


问:
Android Layout Positioing
This is a little bit complicated to explain, so apologies.

The basic requirement is annotator app on Android, which allows the user to draw over the desktop, take a snapshot and one or two other things.

When the app starts it shows a single icon. This can be moved about the desktop.

When this icon is single clicked (touch) 6 icons spread evenly centred around the central icon appear.

So far so good. Now we move the central icon, and re-calculate the positions of the 6 outer icons centred around the new position of the central icon.

What we find is the outer icons are off centre relative to the central icon. The displacement looks to be roughly equal (bot X and Y) by the position of the touch within the central icon.

I will attempt to draw what happens.

First when the touch point on the drag/move is in the centre, everything lines up perfectly:

When the touch point is to the right, the displacement is leftwards as below:

When the touch is at the bottom the displacement is upwards:

The position of the "x" relative to the icon is it seems from

```<code>int shiftX = event.getX();
int shiftY = event.getY();
</code>```

The position of the moved icon is from :

```<code>view.getLocationInWindow(locWXY);
int X = locWXY[0];
int Y = locWXY[1];
</code>```

So, the positions of the satellite icons are calculated as:

```<code>final double angle = 30.000;
final double rad = angle * Math.PI / 180.000;
final int radius = 100;
final int penX = (int) (X + radius * cos(rad) + shiftX);
final int penY = (int) (Y - radius * sin(rad) + shiftY);
final int clearX = X ;
final int clearY = (int) (Y - radius   + shiftY);
final int closeX = (int) (X - radius * cos(rad) + shiftX);
final int closeY = (int) (Y - radius * sin(rad)   + shiftY);
final int iFlipX = (int) (X - radius * cos(rad) + shiftX);
final int iFlipY = (int) (Y + radius * sin(rad)   + shiftY);
final int sshotX = X  + shiftX;
final int sshotY = (int) (Y + radius   + shiftY);
final int iFolderX = (int) (X + radius * cos(rad) + shiftX);
final int iFolderY = (int) (Y + radius * sin(rad)   + shiftY);

penLP= new RelativeLayout.LayoutParams(70, 70);
penLP.leftMargin = penX;
penLP.topMargin = penY;
imbBlackPen.setLayoutParams(penLP);

clearLP = new RelativeLayout.LayoutParams(70, 70);
clearLP .leftMargin = clearX;
clearLP .topMargin = clearY;
imbClearScreen.setLayoutParams(clearLP );

folderLP = new RelativeLayout.LayoutParams(70, 70);
folderLP .leftMargin = iFolderX ;
folderLP .topMargin = iFolderY;
imbFolder.setLayoutParams(folderLP );

sshotLP = new RelativeLayout.LayoutParams(70, 70);
sshotLP .leftMargin = sshotX ;
sshotLP .topMargin = sshotY;
imbScreenCapture.setLayoutParams(sshotLP );

iFlipLP = new RelativeLayout.LayoutParams(70, 70);
iFlipLP .leftMargin = iFlipX ;
iFlipLP .topMargin = iFlipY;
imbIflipChart.setLayoutParams(iFlipLP );

closeLP = new RelativeLayout.LayoutParams(70, 70);
closeLP .leftMargin = closeX ;
closeLP .topMargin = closeY;
imbClose.setLayoutParams(closeLP );
</code>```

I have tried setting shiftX and shiftY to zero, calculating X and X + shiftX/2. All to no avail. The strange thing is that on a small 10 inch tablet with resolution 1920 x 1200 it looks almost perfect, but on a large 65 inch touch screen the displacement is extremely pronounced.

We must be missing something, but I cannot figure out what.

答:
As commented above ...

Fixed. The icon position calculation code above needed to be executed on ACTION_UP as well as ACTION_DOWN. Refactored this as a method and called it on both these events.

Title: Android Layout Positioing

Body:
This is a little bit complicated to explain, so apologies.

The basic requirement is annotator app on Android, which allows the user to draw over the desktop, take a snapshot and one or two other things.

When the app starts it shows a single icon. This can be moved about the desktop.

When this icon is single clicked (touch) 6 icons spread evenly centred around the central icon appear.

So far so good. Now we move the central icon, and re-calculate the positions of the 6 outer icons centred around the new position of the central icon.

What we find is the outer icons are off centre relative to the central icon. The displacement looks to be roughly equal (bot X and Y) by the position of the touch within the central icon.

I will attempt to draw what happens.

First when the touch point on the drag/move is in the centre, everything lines up perfectly:

When the touch point is to the right, the displacement is leftwards as below:

When the touch is at the bottom the displacement is upwards:

The position of the "x" relative to the icon is it seems from

int shiftX = event.getX();
int shiftY = event.getY();

The position of the moved icon is from :

view.getLocationInWindow(locWXY);
int X = locWXY[0];
int Y = locWXY[1];

So, the positions of the satellite icons are calculated as:

final double angle = 30.000;
final double rad = angle * Math.PI / 180.000;
final int radius = 100;
final int penX = (int) (X + radius * cos(rad) + shiftX);
final int penY = (int) (Y - radius * sin(rad) + shiftY);
final int clearX = X ;
final int clearY = (int) (Y - radius   + shiftY);
final int closeX = (int) (X - radius * cos(rad) + shiftX);
final int closeY = (int) (Y - radius * sin(rad)   + shiftY);
final int iFlipX = (int) (X - radius * cos(rad) + shiftX);
final int iFlipY = (int) (Y + radius * sin(rad)   + shiftY);
final int sshotX = X  + shiftX;
final int sshotY = (int) (Y + radius   + shiftY);
final int iFolderX = (int) (X + radius * cos(rad) + shiftX);
final int iFolderY = (int) (Y + radius * sin(rad)   + shiftY);

penLP= new RelativeLayout.LayoutParams(70, 70);
penLP.leftMargin = penX;
penLP.topMargin = penY;
imbBlackPen.setLayoutParams(penLP);

clearLP = new RelativeLayout.LayoutParams(70, 70);
clearLP .leftMargin = clearX;
clearLP .topMargin = clearY;
imbClearScreen.setLayoutParams(clearLP );

folderLP = new RelativeLayout.LayoutParams(70, 70);
folderLP .leftMargin = iFolderX ;
folderLP .topMargin = iFolderY;
imbFolder.setLayoutParams(folderLP );

sshotLP = new RelativeLayout.LayoutParams(70, 70);
sshotLP .leftMargin = sshotX ;
sshotLP .topMargin = sshotY;
imbScreenCapture.setLayoutParams(sshotLP );

iFlipLP = new RelativeLayout.LayoutParams(70, 70);
iFlipLP .leftMargin = iFlipX ;
iFlipLP .topMargin = iFlipY;
imbIflipChart.setLayoutParams(iFlipLP );

closeLP = new RelativeLayout.LayoutParams(70, 70);
closeLP .leftMargin = closeX ;
closeLP .topMargin = closeY;
imbClose.setLayoutParams(closeLP );

I have tried setting shiftX and shiftY to zero, calculating X and X + shiftX/2. All to no avail. The strange thing is that on a small 10 inch tablet with resolution 1920 x 1200 it looks almost perfect, but on a large 65 inch touch screen the displacement is extremely pronounced.

We must be missing something, but I cannot figure out what.


问:
Problems with exporting Java program to a JAR file
So, the software is working properly and everything is fine. I did find some answers to my question online but I can't seem to fix my problem. Everything seems to be okay in my Build Path and in order.
The error I'm getting:

```<code>    Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
Caused by: java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry
        at java.base/java.net.URLClassLoader.findClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 3 more
</code>```

I need to export my project to a JAR file, please help me, I'm desperate. And thanks to anyone that cares to answer in advance.

答:
So, I've figured out what was the problem. The problem was, I was using Java 8 for my project while I had installed (some time ago) Java 9 on my PC. When I tried to run the JAR file, it used Java 9 to run it and it had some dependencies misplaced. I just uninstalled Java 9, exported the project with jre 1.8.0_144 and I'm running jdk 1.8.0_121 on my PC. Everything works great now.

Thank you @Gal and @AJNeufeld for your answers and your help.

Body:
So, the software is working properly and everything is fine. I did find some answers to my question online but I can't seem to fix my problem. Everything seems to be okay in my Build Path and in order.
The error I'm getting:

    Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
Caused by: java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry
        at java.base/java.net.URLClassLoader.findClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 3 more

I need to export my project to a JAR file, please help me, I'm desperate. And thanks to anyone that cares to answer in advance.


问:
How to combine (append) generic Lists in Java without using Javas Collection Framework?
is there an efficient way to combine two generic doube linked lists without using the Collection Framework of Java? The lists are already sorted, so it is only necessary to append the second list to the first one. So far I tried this way, but I am not sure if this is the correct approach:

```<code>public void combineWith(List<T> anotherList) {
    DoubleLinkedList<T> list1 = new DoubleLinkedList<>();

    anotherList = new DoubleLinkedList<>();

    list1= this;

    if(this.next==null) {
        list1.next= (DoubleLinkedList<T>) anotherList;

    }
</code>```

Thanks in advance.

答:
Intended is a merge of sorted lists. For walking with insert/remove, the Iterator or in this case ListIterator is useful. A double linked list could also move by pointers in the lists.

The basic algorithm is:

```<code>/**
 * Merge this list with another, both are sorted.
 * @param other unchanged list.
 */
public void mergeSorted(List<T> other) {
    Iterator<T> iter = iterator();
    Iterator<T> otherIter = other.iterator();
    while (iter.hasNext() && otherIter.hasNext()) {
        T value = iter.next();
        T otherValue = otherIter.next();
        int cmp = value.compareTo(otherValue);
        if (cmp >= 0) {
            if (cmp > 0) {
               iter.insert(otherValue);
            }
            otherIter.next();
        }
        if (cmp <= 0) {
            iter.next();
        }
    }
    while (other.hasNext()) {
       iter.insert(other.next());
    }
}
</code>```

Here I skip on equal elements.

My attempt at ascii art:

Equal (this, other)

```<code>:   :
X = X
|   |
</code>```

Less

```<code>:   :
X   :
: \ :
:   Y
|   :
</code>```

Greater

```<code>:   :
:   X
: / :
Y   +
:   |
</code>```

Body:
is there an efficient way to combine two generic doube linked lists without using the Collection Framework of Java? The lists are already sorted, so it is only necessary to append the second list to the first one. So far I tried this way, but I am not sure if this is the correct approach:

public void combineWith(List<T> anotherList) {
    DoubleLinkedList<T> list1 = new DoubleLinkedList<>();

    anotherList = new DoubleLinkedList<>();

    list1= this;

    if(this.next==null) {
        list1.next= (DoubleLinkedList<T>) anotherList;

    }

Thanks in advance.

Body:
Intended is a merge of sorted lists. For walking with insert/remove, the Iterator or in this case ListIterator is useful. A double linked list could also move by pointers in the lists.

The basic algorithm is:

/**
 * Merge this list with another, both are sorted.
 * @param other unchanged list.
 */
public void mergeSorted(List<T> other) {
    Iterator<T> iter = iterator();
    Iterator<T> otherIter = other.iterator();
    while (iter.hasNext() && otherIter.hasNext()) {
        T value = iter.next();
        T otherValue = otherIter.next();
        int cmp = value.compareTo(otherValue);
        if (cmp >= 0) {
            if (cmp > 0) {
               iter.insert(otherValue);
            }
            otherIter.next();
        }
        if (cmp <= 0) {
            iter.next();
        }
    }
    while (other.hasNext()) {
       iter.insert(other.next());
    }
}

Here I skip on equal elements.

My attempt at ascii art:

Equal (this, other)

:   :
X = X
|   |

Less

:   :
X   :
: \ :
:   Y
|   :

Greater

:   :
:   X
: / :
Y   +
:   |


问:
Passing variables to a subprocess call
I am trying to pass my variables from raw_input to my subprocess command. I am new to Python. Any help would he appreciated.

```<code>#!/usr/bin/python

import subprocess

print "\nWhat user name"
username = str(raw_input('username: '))
print "\nWhat is the user id"
userid = int(raw_input('Enter user id: '))
print "\nWhat is the user\'s primary group?"
primarygroup = int(raw_input('Enter group: '))
print "\nWhat is the user\'s secondary group?"
secondarygroup = int(raw_input('Enter group: '))

subprocess.call(['useradd' '-m' '-g' _primarygroup '-G' _secondarygroup '-u' _userid _username])

print"\nThe user has been added"
</code>```

答:
You can create the arg string first and then just past this variable to the subprocess.call. For example:</p>

```<code>projects_csv_fn = 'projects_csv_2.csv'
prjects_json_fn = 'projects.json'

args ='python json_to_csv.py id ' + prjects_json_fn + ' ' + projects_csv_fn

subprocess.call(args, shell=True)
</code>```

Title: Passing variables to a subprocess call

Body:
I am trying to pass my variables from raw_input to my subprocess command. I am new to Python. Any help would he appreciated.

#!/usr/bin/python

import subprocess

print "\nWhat user name"
username = str(raw_input('username: '))
print "\nWhat is the user id"
userid = int(raw_input('Enter user id: '))
print "\nWhat is the user\'s primary group?"
primarygroup = int(raw_input('Enter group: '))
print "\nWhat is the user\'s secondary group?"
secondarygroup = int(raw_input('Enter group: '))

subprocess.call(['useradd' '-m' '-g' _primarygroup '-G' _secondarygroup '-u' _userid _username])

print"\nThe user has been added"

Body:
You can create the arg string first and then just past this variable to the subprocess.call. For example:

projects_csv_fn = 'projects_csv_2.csv'
prjects_json_fn = 'projects.json'

args ='python json_to_csv.py id ' + prjects_json_fn + ' ' + projects_csv_fn

subprocess.call(args, shell=True)


问:
How to limit content length response of simplified HTTP request in node?
I would like to setup the simplified HTTP request() client package to abort the download of HTTP resources that are too big.

Let's imagine request() is setup to download an url and the resource size is 5 Gigabytes. I would like request() to stop downloading after 10MB. Usually, when request gets an answer it gets all the HTTP headers and everything behind. Once you manipulate the data, you have already all the downloaded data.

In axios, there is a parameter called maxContentLength but I can't find anything similar for request().

I must also mention, that I don't it to catch an error but only download at least the headers and the beginning of the resource.

答:
```<code>const request = require('request');
const URL = 'http://de.releases.ubuntu.com/xenial/ubuntu-16.04.3-desktop-amd64.iso';
const MAX_SIZE = 10 * 1024 * 1024 // 10MB , maximum size to download
let total_bytes_read = 0;
</code>```

1 - If the  response from the server is gzip-compressed , you should
  enable gzip option.
      https://github.com/request/request#examples   For backwards-compatibility, response compression is not supported by
  default.    To accept gzip-compressed responses, set the gzip option
  to true.

```<code>request
    .get({
        uri: URL,
        gzip: true
    })
    .on('error', function (error) {
        //TODO: error handling
        console.error('ERROR::', error);
    })
    .on('data', function (data) {
        // decompressed data
        console.log('Decompressed  chunck Recived:' + data.length, ': Total downloaded:', total_bytes_read)
        total_bytes_read += data.length;
        if (total_bytes_read >= MAX_SIZE) {
            //TODO: handle exceeds max size event
            console.error("Request exceeds max size.");
            throw new Error('Request exceeds max size'); //stop
        }
    })
    .on('response', function (response) {
        response.on('data', function (chunk) {
            //compressed data
            console.log('Compressed  chunck Recived:' + chunk.length, ': Total downloaded:', total_bytes_read)
        });
    })
    .on('end', function () {
        console.log('Request completed! Total size downloaded:', total_bytes_read)
    });
</code>```

NB:  If the server does not compress response but you still use gzip
  option / decompress, then  the decompress chunk & the original chunk will be
  equal.   Hence you can do the Limit check either way(from the
  decompressed / compressed chunk)  However if response is compressed
  you should check the size limit of the decompressed chunk

2 - if the response is not compressed you don't need gzip option to
  decompress

```<code>request
    .get(URL)
    .on('error', function (error) {
        //TODO: error handling
        console.error('ERROR::', error);
    })
    .on('response', function (response) {
        response.on('data', function (chunk) {
            //compressed data
            console.log('Recived chunck:' + chunk.length, ': Total downloaded:', total_bytes_read)
            total_bytes_read += chunk.length;
            if (total_bytes_read >= MAX_SIZE) {
                //TODO: handle exceeds max size event
                console.error("Request as it exceds max size:")
                throw new Error('Request as it exceds max size');
            }
            console.log("...");
        });
    })
    .on('end', function () {
        console.log('Request completed! Total size downloaded:', total_bytes_read)
    });
</code>```

Body:
const request = require('request');
const URL = 'http://de.releases.ubuntu.com/xenial/ubuntu-16.04.3-desktop-amd64.iso';
const MAX_SIZE = 10 * 1024 * 1024 // 10MB , maximum size to download
let total_bytes_read = 0;

1 - If the  response from the server is gzip-compressed , you should
  enable gzip option.
      https://github.com/request/request#examples   For backwards-compatibility, response compression is not supported by
  default.    To accept gzip-compressed responses, set the gzip option
  to true.

request
    .get({
        uri: URL,
        gzip: true
    })
    .on('error', function (error) {
        //TODO: error handling
        console.error('ERROR::', error);
    })
    .on('data', function (data) {
        // decompressed data
        console.log('Decompressed  chunck Recived:' + data.length, ': Total downloaded:', total_bytes_read)
        total_bytes_read += data.length;
        if (total_bytes_read >= MAX_SIZE) {
            //TODO: handle exceeds max size event
            console.error("Request exceeds max size.");
            throw new Error('Request exceeds max size'); //stop
        }
    })
    .on('response', function (response) {
        response.on('data', function (chunk) {
            //compressed data
            console.log('Compressed  chunck Recived:' + chunk.length, ': Total downloaded:', total_bytes_read)
        });
    })
    .on('end', function () {
        console.log('Request completed! Total size downloaded:', total_bytes_read)
    });

NB:  If the server does not compress response but you still use gzip
  option / decompress, then  the decompress chunk & the original chunk will be
  equal.   Hence you can do the Limit check either way(from the
  decompressed / compressed chunk)  However if response is compressed
  you should check the size limit of the decompressed chunk

2 - if the response is not compressed you don't need gzip option to
  decompress

request
    .get(URL)
    .on('error', function (error) {
        //TODO: error handling
        console.error('ERROR::', error);
    })
    .on('response', function (response) {
        response.on('data', function (chunk) {
            //compressed data
            console.log('Recived chunck:' + chunk.length, ': Total downloaded:', total_bytes_read)
            total_bytes_read += chunk.length;
            if (total_bytes_read >= MAX_SIZE) {
                //TODO: handle exceeds max size event
                console.error("Request as it exceds max size:")
                throw new Error('Request as it exceds max size');
            }
            console.log("...");
        });
    })
    .on('end', function () {
        console.log('Request completed! Total size downloaded:', total_bytes_read)
    });


问:
Select and Update Query MSQL
I have a table named BOOK

I need a query that will discount the price of books by 10%, list the Book Code(PK),the Book Title and Discounted Price of each book.

I need to then change the price column to 'Discounted Price' as the name for the computed column.

I currently have

```<code>UPDATE BOOK SET PRICE = PRICE*0.9
SELECT CONCAT(PRICE) AS Discounted_Price,BOOK_CODE, BOOK_TITLE;
</code>```

But I am getting an error message.

答:
Instead of updating the price in the table and avoiding to have two queries, you can have the desired result by a SELECT query like below :

```<code>Select BOOK_CODE, BOOK_TITLE, (PRICE * 0.9) as Discounted_Price from BOOK;
</code>```

Title: Select and Update Query MSQL

Body:
I have a table named BOOK

I need a query that will discount the price of books by 10%, list the Book Code(PK),the Book Title and Discounted Price of each book.

I need to then change the price column to 'Discounted Price' as the name for the computed column.

I currently have

UPDATE BOOK SET PRICE = PRICE*0.9
SELECT CONCAT(PRICE) AS Discounted_Price,BOOK_CODE, BOOK_TITLE;

But I am getting an error message.

Body:
Instead of updating the price in the table and avoiding to have two queries, you can have the desired result by a SELECT query like below :

Select BOOK_CODE, BOOK_TITLE, (PRICE * 0.9) as Discounted_Price from BOOK;