问:
internalTransactionalEventListenerFactory could not find error with jpa
I am using Spring 4.3 and JPA to my project. I used java configuration to configure Hibernate instead of XMl configuration. But when I am compiling below error message is received. Please direct me to resolve this problem.

Following is the stack trace

```<code>java.lang.IllegalStateException: could not find the type for bean named org.springframework.transaction.config.internalTransactionalEventListenerFactory
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.getBeanClass(SpringBeanProcessor.java:456)
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.processBean(SpringBeanProcessor.java:280)
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.postProcessBeanFactory(SpringBeanProcessor.java:258)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:131)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.jboss.resteasy.plugins.spring.SpringContextLoaderListener.contextInitialized(SpringContextLoaderListener.java:48)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1284)
    at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:666)
    at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:217)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:136)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1533)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

JPA configuration class

```<code>`@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:application/core-application.properties" })
public class JPAConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan(new String[] { "com.dak.school.model" });
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        factoryBean.setJpaProperties(jpaProperties());
        return factoryBean;
    }

    /*
    * Provider specific adapter.
    */
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        return hibernateJpaVendorAdapter;
    }

    /*
     * Here you can specify any provider specific properties.
     */
    private Properties jpaProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        // properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(emf);
        return txManager;
    }
} `
</code>```

Application properties file

```<code>> jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url =
> jdbc:mysql://localhost:3306/school_suit jdbc.username = root
> jdbc.password = admin123fg hibernate.dialect =
> org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=create-drop
> hibernate.show_sql = true hibernate.format_sql = true
</code>```

Service implementation class

```<code>@Service
//@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired(required = false)
    private  UserDao userDao;

    @Override
    public void saveUser(final User user) {

        userDao.create(user);

    }
}
</code>```

Dao implementation class

```<code>@Repository
public class UserDaoImpl extends DaoImpl<User,Long> implements UserDao {

}
</code>```

Abstract Daoimpl class

```<code>public abstract class DaoImpl<T, PK extends Serializable> implements IDao<T, PK> {

  /* Persistence Entity class type. */
  protected Class<T> entityClass;

  /* Entity manager to perform DAO operations. */
  @PersistenceContext
  protected EntityManager entityManager;

  /**
   * Constructor
   */
  @SuppressWarnings("unchecked")
  public DaoImpl() {

    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#create(java.lang.Object)
   */
  public T create(T t) {

    this.entityManager.persist(t);
    return t;
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#read(java.io.Serializable)
   */
  public T read(PK id) {

    return this.entityManager.find(entityClass, id);
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#update(java.lang.Object)
   */
  public T update(T t) {

    return this.entityManager.merge(t);
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#delete(java.lang.Object)
   */
  public void delete(T t) {

    t = this.entityManager.merge(t);
    this.entityManager.remove(t);
  }

  /*
   * (non-Javadoc)
   *
   * @see com.yummy.platform.spring.dao.BaseDao#findAll()
   */
  @SuppressWarnings("unchecked")
  public List<T> findAll() {

    Query query = entityManager.createQuery("FROM " + entityClass.getName() + " c");
    return (List<T>) query.getResultList();
  }

}
</code>```

Dependency details

```<code> <spring.version>4.3.0.RELEASE</spring.version>
        <spring.security.version>4.2.2.RELEASE</spring.security.version>
        <jstl.version>1.2</jstl.version>
        <taglib.standard.version>1.1.2</taglib.standard.version>
        <!--<servlet.api.version>3.0.1</servlet.api.version>-->
        <servlet.api.version>3.1.0</servlet.api.version>
        <servlet.api.jsp.version>2.3.1</servlet.api.jsp.version>
        <resteasy.version>3.0.11.Final</resteasy.version>

        <apache.commnos.beanutil.version>1.9.0</apache.commnos.beanutil.version>
        <apache.commnos.codec.version>1.9</apache.commnos.codec.version>
        <commons.collections.version>3.2.1</commons.collections.version>
        <commons-digester.version>3.2</commons-digester.version>
        <commons-logging.version>1.1.3</commons-logging.version>
        <commons-dbcp.version>2.1.1</commons-dbcp.version>
        <commons-lang.version>2.4</commons-lang.version>

        <mysql.connector.version>6.0.5</mysql.connector.version>
        <hibernate.core.version>5.2.9.Final</hibernate.core.version>
        <javax.validation.version>1.1.0.Final</javax.validation.version>
        <hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
</code>```

答: It seems to be an similar issue as https://issues.jboss.org/browse/RESTEASY-1241.  I resolve my issue by upgrading RESTEasy from 3.0.10.Final to 3.0.19.Final.</p>

Body:
I am using Spring 4.3 and JPA to my project. I used java configuration to configure Hibernate instead of XMl configuration. But when I am compiling below error message is received. Please direct me to resolve this problem.

Following is the stack trace

java.lang.IllegalStateException: could not find the type for bean named org.springframework.transaction.config.internalTransactionalEventListenerFactory
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.getBeanClass(SpringBeanProcessor.java:456)
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.processBean(SpringBeanProcessor.java:280)
    at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.postProcessBeanFactory(SpringBeanProcessor.java:258)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:131)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.jboss.resteasy.plugins.spring.SpringContextLoaderListener.contextInitialized(SpringContextLoaderListener.java:48)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1284)
    at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:666)
    at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:217)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:136)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1533)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

JPA configuration class

`@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:application/core-application.properties" })
public class JPAConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan(new String[] { "com.dak.school.model" });
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        factoryBean.setJpaProperties(jpaProperties());
        return factoryBean;
    }

    /*
    * Provider specific adapter.
    */
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        return hibernateJpaVendorAdapter;
    }

    /*
     * Here you can specify any provider specific properties.
     */
    private Properties jpaProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        // properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(emf);
        return txManager;
    }
} `

Application properties file

> jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url =
> jdbc:mysql://localhost:3306/school_suit jdbc.username = root
> jdbc.password = admin123fg hibernate.dialect =
> org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=create-drop
> hibernate.show_sql = true hibernate.format_sql = true

Service implementation class

@Service
//@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired(required = false)
    private  UserDao userDao;

    @Override
    public void saveUser(final User user) {

        userDao.create(user);

    }
}

Dao implementation class

@Repository
public class UserDaoImpl extends DaoImpl<User,Long> implements UserDao {

}

Abstract Daoimpl class

public abstract class DaoImpl<T, PK extends Serializable> implements IDao<T, PK> {

  /* Persistence Entity class type. */
  protected Class<T> entityClass;

  /* Entity manager to perform DAO operations. */
  @PersistenceContext
  protected EntityManager entityManager;

  /**
   * Constructor
   */
  @SuppressWarnings("unchecked")
  public DaoImpl() {

    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#create(java.lang.Object)
   */
  public T create(T t) {

    this.entityManager.persist(t);
    return t;
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#read(java.io.Serializable)
   */
  public T read(PK id) {

    return this.entityManager.find(entityClass, id);
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#update(java.lang.Object)
   */
  public T update(T t) {

    return this.entityManager.merge(t);
  }

  /*
   * (non-Javadoc)
   *
   * @see com.fg.baking.core.dao.IDao#delete(java.lang.Object)
   */
  public void delete(T t) {

    t = this.entityManager.merge(t);
    this.entityManager.remove(t);
  }

  /*
   * (non-Javadoc)
   *
   * @see com.yummy.platform.spring.dao.BaseDao#findAll()
   */
  @SuppressWarnings("unchecked")
  public List<T> findAll() {

    Query query = entityManager.createQuery("FROM " + entityClass.getName() + " c");
    return (List<T>) query.getResultList();
  }

}

Dependency details

 <spring.version>4.3.0.RELEASE</spring.version>
        <spring.security.version>4.2.2.RELEASE</spring.security.version>
        <jstl.version>1.2</jstl.version>
        <taglib.standard.version>1.1.2</taglib.standard.version>

        <servlet.api.version>3.1.0</servlet.api.version>
        <servlet.api.jsp.version>2.3.1</servlet.api.jsp.version>
        <resteasy.version>3.0.11.Final</resteasy.version>

        <apache.commnos.beanutil.version>1.9.0</apache.commnos.beanutil.version>
        <apache.commnos.codec.version>1.9</apache.commnos.codec.version>
        <commons.collections.version>3.2.1</commons.collections.version>
        <commons-digester.version>3.2</commons-digester.version>
        <commons-logging.version>1.1.3</commons-logging.version>
        <commons-dbcp.version>2.1.1</commons-dbcp.version>
        <commons-lang.version>2.4</commons-lang.version>

        <mysql.connector.version>6.0.5</mysql.connector.version>
        <hibernate.core.version>5.2.9.Final</hibernate.core.version>
        <javax.validation.version>1.1.0.Final</javax.validation.version>
        <hibernate-validator.version>5.1.3.Final</hibernate-validator.version>


来源: stackexchange

问:
Check no of occurance of all digits in array using single for Loop or use Any Collection
```<code>Integer a[]={10,20,30,10,10,20,50,60,50,50};

for(int i=0;i<a.length;i++)
{

             int count=0;
            for(int j=0;j<a.length;j++)
            {

                if(a[i]==a[j])
                {
                    count++;

                }
            }
            System.out.println(a[i]+" occurs times ="+count);
            count=0;
}
</code>```

答:
I think you want the output with no duplicate message with one loop

consider using Set to remove duplicate number

Look at this code:

```<code>Integer a[] = { 10, 20, 30, 10, 10, 20, 50, 60, 50, 50 };
Set<Integer> noDuplicateInt = new HashSet<>();
for (Integer integer : a) {
    if (noDuplicateInt.add(integer)) {
        System.out.println("Number of Occurence of " + integer + ": " +
                   Collections.frequency(Arrays.asList(a), integer));
    }
}
</code>```

Update With Regards To Comment

This is the same code without using Collections class:

```<code>Integer a[] = { 10, 20, 30, 10, 10, 20, 50, 60, 50, 50 };
Set<Integer> noDuplicateInt = new HashSet<>();
Map<Integer, Integer> numOccurenceMap = new HashMap<>();
for (Integer integer : a) {
    if (noDuplicateInt.add(integer)) {
        numOccurenceMap.put(integer, 1);
    } else {
        numOccurenceMap.replace(integer, numOccurenceMap.get(integer) + 1);
    }
}
System.out.println(numOccurenceMap);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you want the output with no duplicate message with one loop

consider using Set to remove duplicate number

Look at this code:

Integer a[] = { 10, 20, 30, 10, 10, 20, 50, 60, 50, 50 };
Set<Integer> noDuplicateInt = new HashSet<>();
for (Integer integer : a) {
    if (noDuplicateInt.add(integer)) {
        System.out.println("Number of Occurence of " + integer + ": " +
                   Collections.frequency(Arrays.asList(a), integer));
    }
}

Update With Regards To Comment

This is the same code without using Collections class:

Integer a[] = { 10, 20, 30, 10, 10, 20, 50, 60, 50, 50 };
Set<Integer> noDuplicateInt = new HashSet<>();
Map<Integer, Integer> numOccurenceMap = new HashMap<>();
for (Integer integer : a) {
    if (noDuplicateInt.add(integer)) {
        numOccurenceMap.put(integer, 1);
    } else {
        numOccurenceMap.replace(integer, numOccurenceMap.get(integer) + 1);
    }
}
System.out.println(numOccurenceMap);


问:
Mysql - php query fetch array results using multiple parameters
I have a mysql table as below,

```<code>+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+
</code>```

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

答:
use WHERE clause with OR operator

```<code>SELECT * FROM table WHERE Status='Active' OR  Status='Inactive'
</code>```

its simple add to the query

```<code>AND Status !='Trashed'
</code>```

Body:
I have a mysql table as below,

+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

Body:
use WHERE clause with OR operator

SELECT * FROM table WHERE Status='Active' OR  Status='Inactive'

its simple add to the query

AND Status !='Trashed'

ContentLicense: CC BY-SA 2.5


问:
Set table view cell height by identifier - Swift
I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}
</code>```

The error is at this line:

```<code>let cell = tableV.cellForRow(at: indexPath)
</code>```

Thank you.

答:
First duque cell

```<code>    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
</code>```

after that set cell height as you like.

Body:
I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}

The error is at this line:

let cell = tableV.cellForRow(at: indexPath)

Thank you.

Body:
First duque cell

    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell

after that set cell height as you like.


问:
powershell script to delete old backup files more than 6 months old
I'm deleting files manually on my system which are more than 6 months old, want to automate the process, is it possible via powershell? Pretty new to it!

I want to delete files more than 6 months old.
Any help would be much invited!

答:
```<code>$ToDeleteLimit = (Get-Date).AddMonths(-6)
Get-ChildItem -Path \\PathToYourBackup -Recurse -Force | Where-Object { $_.LastWriteTime -lt $ToDeleteLimit } | Remove-Item -Force
</code>```

Use the Recurse parameter to iterate through the sub-directories and Force parameter to delete hidden or read-only files.

Body:
$ToDeleteLimit = (Get-Date).AddMonths(-6)
Get-ChildItem -Path \\PathToYourBackup -Recurse -Force | Where-Object { $_.LastWriteTime -lt $ToDeleteLimit } | Remove-Item -Force

Use the Recurse parameter to iterate through the sub-directories and Force parameter to delete hidden or read-only files.


问:
how to get element of list without string
I have a list like:

```<code>my_list = ['[:,y+1,x+1]', '[:,y+1,x-1]']
my_list[0]
</code>```

gives:

```<code>'[:,y+1,x+1]'
</code>```

How to get only

```<code>[:,y+1,x+1]
</code>```

Why I need this: I am trying to read netcdf file with the with the coordinates from the list, something like:

```<code>from netCDF4 import Dataset
fd = Dataset(ncfile,'r')
fd.variables['t2m']my_list[0]
</code>```

where x and y are predefined.

答:
Maybe not the right answer, but an attempt. To be able to execute something like:

```<code>fd.variables['t2m'][:,y+1,x+1]
</code>```

Then you should only store tuples here:

```<code>my_list = [(5,5),(3,3)]
</code>```

And define y and x before the command like this:

```<code>y,x = my_list[0]
</code>```

Body:
I have a list like:

my_list = ['[:,y+1,x+1]', '[:,y+1,x-1]']
my_list[0]

gives:

'[:,y+1,x+1]'

How to get only

[:,y+1,x+1]

Why I need this: I am trying to read netcdf file with the with the coordinates from the list, something like:

from netCDF4 import Dataset
fd = Dataset(ncfile,'r')
fd.variables['t2m']my_list[0]

where x and y are predefined.

Body:
Maybe not the right answer, but an attempt. To be able to execute something like:

fd.variables['t2m'][:,y+1,x+1]

Then you should only store tuples here:

my_list = [(5,5),(3,3)]

And define y and x before the command like this:

y,x = my_list[0]


问:
Webpack/Babel not detecting javascript errors before transpiling
I have configured webpack-dev-server for a new React project. I am using babel-loader to transpile ES6 code. In previous projects we were able to detect obvious errors in our javascript code prior to transpilation, eg missing import statements or undefined variables.

Why is webpack / babel-loader not detecting obvious errors? And how can I configure babel-loader to not transpile these errors and instead log to the command prompt?

Here is my package.json

```<code>{
  "name": "advent-calendar",
  "version": "1.0.0",
  "description": "",
  "main": "src/entry.js",
  "scripts": {
    "dev": "webpack-dev-server --config config/webpack.config.dev.js",
    "build:webpack": "cross-env NODE_ENV=production && webpack --config config/webpack.config.prod.js",
    "build": "npm run build:webpack --verbose --color",
    "test": "cross-env NODE_ENV=development ./node_modules/.bin/mocha --opts mocha.opts",
    "test:watch": "npm run test -- --watch",
    "lint": "npm run -s lint:css:raw ; npm run -s lint:js:raw",
    "lint:css": "npm run -s lint:css:raw",
    "lint:css:raw": "stylelint \"src/**/*.{css,less,scss}\"",
    "lint:js": "npm run -s lint:js:raw",
    "lint:js:raw": "eslint  \"src/**/*.js\"",
    "lint:js:raw:fix": "./node_modules/.bin/eslint --fix \"src/**/*.js\"",
    "lint:js:watch": "esw \"src/**/*.js\" --watchyar",
    "lint:watch": "npm run lint:js:watch"
  },
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.0.2",
    "babel-loader": "^7.1.2",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "chai": "^4.1.2",
    "chai-enzyme": "^0.8.0",
    "cross-env": "^5.1.1",
    "css-loader": "^0.28.7",
    "enzyme": "^3.1.1",
    "enzyme-adapter-react-16": "^1.0.4",
    "eslint": "^4.10.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-chai-friendly": "^0.4.0",
    "eslint-plugin-eslint-comments": "^2.0.1",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-jsx-a11y": "^6.0.2",
    "eslint-plugin-react": "^7.4.0",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.30.1",
    "jsdom": "^9.9.1",
    "less": "^2.7.3",
    "less-loader": "^4.0.5",
    "mocha": "^4.0.1",
    "node-sass": "^4.6.0",
    "nyc": "~9.0.1",
    "path": "^0.12.7",
    "prop-types": "^15.6.0",
    "sass-loader": "^6.0.6",
    "simple-jsdom": "^3.0.0",
    "sinon": "^4.1.2",
    "sinon-chai": "^2.14.0",
    "style-loader": "^0.19.0",
    "stylelint": "^8.2.0",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4"
  },
  "dependencies": {
    "classnames": "^2.2.5",
    "crypto-js": "^3.1.9-1",
    "css-reset": "^0.0.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-redux": "^5.0.6",
    "react-transition-group": "^2.2.1",
    "redux": "^3.7.2",
    "redux-devtools-extension": "^2.13.2",
    "redux-saga": "^0.16.0"
  }
}
</code>```

This is my .babelrc

```<code>{
   "presets": [
      "es2015",
      "react",
      "stage-1"
   ]
}
</code>```

My loader for javascript files is

```<code>{
   test: /\.$|\.js$|\.jsx$/,
   exclude: /node_modules\/[^@]/,
   use: [{
     loader: 'babel-loader',
   }],
}
</code>```

答:
And how can I configure babel-loader to not transpile these errors and instead log to the command prompt?

Webpack-dev-server has enough configuration for error logging, which can be provided in declarative mode.

Just use following script (name it run-dev.js and patch package.json respectively) for launching client part:

```<code>import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';

import config from './webpack.dev.config';

const outputConfig = {
    colors: true,
    hash: false,
    version: false,
    timings: false,
    assets: false,
    chunks: false,
    modules: false,
    reasons: false,
    children: false,
    source: false,
    errors: true,
    errorDetails: true,
    warnings: true,
    publicPath: false
};

const clientCompiler = webpack(config);

const clientDevServer = new WebpackDevServer(clientCompiler, {
    stats: outputConfig
});

clientDevServer.listen(3000, '127.0.0.1');
</code>```

Then you can customize outputConfig object depend on requirements and verbose degree of output. Don't forget to turn on errors and errorDetails options, which will indicate chunks and source code lines with compile errors.

Read mode here https://webpack.js.org/configuration/stats/ about outputConfig configuration, including filter patter for error output, which can be used for excluding redundant logging in console.

Body:
I have configured webpack-dev-server for a new React project. I am using babel-loader to transpile ES6 code. In previous projects we were able to detect obvious errors in our javascript code prior to transpilation, eg missing import statements or undefined variables.

Why is webpack / babel-loader not detecting obvious errors? And how can I configure babel-loader to not transpile these errors and instead log to the command prompt?

Here is my package.json

{
  "name": "advent-calendar",
  "version": "1.0.0",
  "description": "",
  "main": "src/entry.js",
  "scripts": {
    "dev": "webpack-dev-server --config config/webpack.config.dev.js",
    "build:webpack": "cross-env NODE_ENV=production && webpack --config config/webpack.config.prod.js",
    "build": "npm run build:webpack --verbose --color",
    "test": "cross-env NODE_ENV=development ./node_modules/.bin/mocha --opts mocha.opts",
    "test:watch": "npm run test -- --watch",
    "lint": "npm run -s lint:css:raw ; npm run -s lint:js:raw",
    "lint:css": "npm run -s lint:css:raw",
    "lint:css:raw": "stylelint \"src/**/*.{css,less,scss}\"",
    "lint:js": "npm run -s lint:js:raw",
    "lint:js:raw": "eslint  \"src/**/*.js\"",
    "lint:js:raw:fix": "./node_modules/.bin/eslint --fix \"src/**/*.js\"",
    "lint:js:watch": "esw \"src/**/*.js\" --watchyar",
    "lint:watch": "npm run lint:js:watch"
  },
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.0.2",
    "babel-loader": "^7.1.2",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "chai": "^4.1.2",
    "chai-enzyme": "^0.8.0",
    "cross-env": "^5.1.1",
    "css-loader": "^0.28.7",
    "enzyme": "^3.1.1",
    "enzyme-adapter-react-16": "^1.0.4",
    "eslint": "^4.10.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-chai-friendly": "^0.4.0",
    "eslint-plugin-eslint-comments": "^2.0.1",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-jsx-a11y": "^6.0.2",
    "eslint-plugin-react": "^7.4.0",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.30.1",
    "jsdom": "^9.9.1",
    "less": "^2.7.3",
    "less-loader": "^4.0.5",
    "mocha": "^4.0.1",
    "node-sass": "^4.6.0",
    "nyc": "~9.0.1",
    "path": "^0.12.7",
    "prop-types": "^15.6.0",
    "sass-loader": "^6.0.6",
    "simple-jsdom": "^3.0.0",
    "sinon": "^4.1.2",
    "sinon-chai": "^2.14.0",
    "style-loader": "^0.19.0",
    "stylelint": "^8.2.0",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4"
  },
  "dependencies": {
    "classnames": "^2.2.5",
    "crypto-js": "^3.1.9-1",
    "css-reset": "^0.0.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-redux": "^5.0.6",
    "react-transition-group": "^2.2.1",
    "redux": "^3.7.2",
    "redux-devtools-extension": "^2.13.2",
    "redux-saga": "^0.16.0"
  }
}

This is my .babelrc

{
   "presets": [
      "es2015",
      "react",
      "stage-1"
   ]
}

My loader for javascript files is

{
   test: /\.$|\.js$|\.jsx$/,
   exclude: /node_modules\/[^@]/,
   use: [{
     loader: 'babel-loader',
   }],
}

Body:
And how can I configure babel-loader to not transpile these errors and instead log to the command prompt?

Webpack-dev-server has enough configuration for error logging, which can be provided in declarative mode.

Just use following script (name it run-dev.js and patch package.json respectively) for launching client part:

import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';

import config from './webpack.dev.config';

const outputConfig = {
    colors: true,
    hash: false,
    version: false,
    timings: false,
    assets: false,
    chunks: false,
    modules: false,
    reasons: false,
    children: false,
    source: false,
    errors: true,
    errorDetails: true,
    warnings: true,
    publicPath: false
};

const clientCompiler = webpack(config);

const clientDevServer = new WebpackDevServer(clientCompiler, {
    stats: outputConfig
});

clientDevServer.listen(3000, '127.0.0.1');

Then you can customize outputConfig object depend on requirements and verbose degree of output. Don't forget to turn on errors and errorDetails options, which will indicate chunks and source code lines with compile errors.

Read mode here https://webpack.js.org/configuration/stats/ about outputConfig configuration, including filter patter for error output, which can be used for excluding redundant logging in console.


问:
Lodash groupBy fat arrow function with React
Following on from Lodash groupBy with moment that groups an array by dates such as today, this week, month etc by using a fat arrow function and moment I am now trying to enable if then else (or ternary) that only enables this if the sort parameter (passed in from state) is actually a date.

This is what I have at the moment...

```<code>     let groupby = datum => {
        if (this.state.sortGroup ='updatedAt') {
          return determineGroup(moment(groupProp(datum)));
        } else {
          this.state.sortGroup
        }
      }

      //console log point 1 -  shows state change

      groupedData = _
      .chain(this.props.records)
      .groupBy(groupby)
      .map(function(val, key) {
          return {
              group: key,
              records: val
          };
      })
      .value()

      //console log point 2 -  no state change
</code>```

It sorts by the grouped createdAt perfectly, but when I put the if then else functionality in it does not sort by any other prop. Also interestingly at log point 2 it does not show the state changing.

Is this something I am doing wrong that is affecting state or poor code in the if then else function?

答:
I'm assuming sortGroup refers to the name of a property on the data, in which case, I think you need something more like this:

const data = [{
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test77.com",
  createdAt: "2017-11-06T20:45:56.931Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-09-06T20:45:56.931Z",
  _id: "6gsb42PSSJt7PgsDG"
}, {
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test66,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-10-06T20:46:27.744Z",
  _id: "Md4wCnEsrQrWApnLS"
}, {
  campaign: "Gary",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-07-06T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-15T03:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-03T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-13T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-09T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}];

const groupProp = _.property('updatedAt');

let determineGroup = value => {
  // remove '2017-11-15' to actually use current date
  const now = moment('2017-11-15T10:00:03Z').startOf('day');

  if (value.isSame(now, 'day')) {
    return 'today';
  }
  if (value.isAfter(now.clone().subtract(7, 'days').startOf('day'))) {
    return 'this week';
  }
  if (value.isSame(now, 'month')) {
    return 'this month';
  }
  return value.format('MM');
};

this.state = {
  sortGroup: 'updatedAt'
};

let groupby = datum => {
  const groupValue = datum[this.state.sortGroup];

  if (this.state.sortGroup === 'updatedAt') {
    return determineGroup(moment(groupValue));
  } else {
    return groupValue;
  }
}

let groupedData = _
  .chain(data)
  .groupBy(groupby)
  .value()

console.log(groupedData);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
Following on from Lodash groupBy with moment that groups an array by dates such as today, this week, month etc by using a fat arrow function and moment I am now trying to enable if then else (or ternary) that only enables this if the sort parameter (passed in from state) is actually a date.

This is what I have at the moment...

     let groupby = datum => {
        if (this.state.sortGroup ='updatedAt') {
          return determineGroup(moment(groupProp(datum)));
        } else {
          this.state.sortGroup
        }
      }

      //console log point 1 -  shows state change

      groupedData = _
      .chain(this.props.records)
      .groupBy(groupby)
      .map(function(val, key) {
          return {
              group: key,
              records: val
          };
      })
      .value()

      //console log point 2 -  no state change

It sorts by the grouped createdAt perfectly, but when I put the if then else functionality in it does not sort by any other prop. Also interestingly at log point 2 it does not show the state changing.

Is this something I am doing wrong that is affecting state or poor code in the if then else function?

Body:
I'm assuming sortGroup refers to the name of a property on the data, in which case, I think you need something more like this:

const data = [{
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test77.com",
  createdAt: "2017-11-06T20:45:56.931Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-09-06T20:45:56.931Z",
  _id: "6gsb42PSSJt7PgsDG"
}, {
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test66,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-10-06T20:46:27.744Z",
  _id: "Md4wCnEsrQrWApnLS"
}, {
  campaign: "Gary",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-07-06T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-15T03:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-03T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-13T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-09T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}];

const groupProp = _.property('updatedAt');

let determineGroup = value => {
  // remove '2017-11-15' to actually use current date
  const now = moment('2017-11-15T10:00:03Z').startOf('day');

  if (value.isSame(now, 'day')) {
    return 'today';
  }
  if (value.isAfter(now.clone().subtract(7, 'days').startOf('day'))) {
    return 'this week';
  }
  if (value.isSame(now, 'month')) {
    return 'this month';
  }
  return value.format('MM');
};

this.state = {
  sortGroup: 'updatedAt'
};

let groupby = datum => {
  const groupValue = datum[this.state.sortGroup];

  if (this.state.sortGroup === 'updatedAt') {
    return determineGroup(moment(groupValue));
  } else {
    return groupValue;
  }
}

let groupedData = _
  .chain(data)
  .groupBy(groupby)
  .value()

console.log(groupedData);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
handle exceptions in stream java 8
I have a string:

```<code>"1, 2, 3 , -4"
</code>```

it is split by ", ".
I have a function to convert a number to a enum type which works fine. I want to use java 8 to convert this string to a list of enum objects.

```<code>Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
  .map(s -> {
    try {
      return this.getEnumObject(Integer.valueOf(s), f.class);
    }
    catch (NoEleException e) {
      e.printStackTrace();
    }
  })
  .collect(Collectors.toList());
</code>```

This gives me an error:

```<code>missing return type.
</code>```

How could I fix it?

答:
Basically to ways of managing this:

catching the exception and return some value or encapsulate values in Optionals and filter accordingly

Throwing a RuntimeException which chains the original one

In the first case we use Optional to put something into the stream on error, and then manage these empty values further in the stream:

```<code>pattern.splitAsStream(str)
.map(s -> {
  try {
    return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
  }
  catch (NoEleException e) {
    e.printStackTrace();
    return Optional.empty();
  }
 })
.filter(Optional::isPresent) // remove empty optionals
.map(Optional::get) // unwrap them
.collect(Collectors.toList());
</code>```

In the second case the stream is stopped and you can then try to catch the RuntimeException and unchain the original one:

```<code>pattern.splitAsStream(str)
.map(s -> {
  try {
    return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
  }
  catch (NoEleException e) {
    e.printStackTrace();
    throw new RuntimeException(e); // stop the stream
  }
 })
.collect(Collectors.toList());
</code>```

Title: handle exceptions in stream java 8

Body:
I have a string:

"1, 2, 3 , -4"

it is split by ", ".
I have a function to convert a number to a enum type which works fine. I want to use java 8 to convert this string to a list of enum objects.

Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
  .map(s -> {
    try {
      return this.getEnumObject(Integer.valueOf(s), f.class);
    }
    catch (NoEleException e) {
      e.printStackTrace();
    }
  })
  .collect(Collectors.toList());

This gives me an error:

missing return type.

How could I fix it?

Body:
Basically to ways of managing this:

catching the exception and return some value or encapsulate values in Optionals and filter accordingly

Throwing a RuntimeException which chains the original one

In the first case we use Optional to put something into the stream on error, and then manage these empty values further in the stream:

pattern.splitAsStream(str)
.map(s -> {
  try {
    return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
  }
  catch (NoEleException e) {
    e.printStackTrace();
    return Optional.empty();
  }
 })
.filter(Optional::isPresent) // remove empty optionals
.map(Optional::get) // unwrap them
.collect(Collectors.toList());

In the second case the stream is stopped and you can then try to catch the RuntimeException and unchain the original one:

pattern.splitAsStream(str)
.map(s -> {
  try {
    return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
  }
  catch (NoEleException e) {
    e.printStackTrace();
    throw new RuntimeException(e); // stop the stream
  }
 })
.collect(Collectors.toList());


问:
How to find the total number of pages in pdf file loaded in objective c?
Is there any way to determine the total number of pages once the pdf file is loaded in the ipad? I am using CATiledLayer Method for loading the pdf file.

Thanking you.

答:
Call the function size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document);

See the CGPDFDocument documentation for other useful stuff you will probably need.

```<code>         CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (__bridge CFStringRef)[NSString stringWithFormat:@"%s",filePath], kCFURLPOSIXPathStyle, 0);
        CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(url);
        CGPDFPageRef myPageRef = CGPDFDocumentGetPage(pdf, 1);
        int  totalPages= CGPDFDocumentGetNumberOfPages(pdf);
</code>```

Body:
Call the function size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document);

See the CGPDFDocument documentation for other useful stuff you will probably need.

         CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (__bridge CFStringRef)[NSString stringWithFormat:@"%s",filePath], kCFURLPOSIXPathStyle, 0);
        CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(url);
        CGPDFPageRef myPageRef = CGPDFDocumentGetPage(pdf, 1);
        int  totalPages= CGPDFDocumentGetNumberOfPages(pdf);


问:
Add protobuf file as dependency to py_proto_library in Bazel
I would like to import a.proto into b.proto and compile with Bazel.

BUILD:

```<code>py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)
</code>```

b.proto

```<code>import public "a.proto";
</code>```

When I run it with Bazel I get does not have mandatory providers: 'py'. error, even though according to the example here that's how it should work.

I tried using filegroup to add a.proto as a dependency, and same error, because apparently deps expects python files.
Is py_proto_library operating differently than java_proto_library? If so, how can I add a.proto as dependency so that it gets imported correctly?

EDIT:
I am loading protobuf from https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz

This rule accepts .proto files if you pass them as proto_deps, but then I get an error Import "a.proto" was not found or had errors.

Maybe I should specify imports somehow?

答: The py_proto_library macro provided by upstream protobuf doesn't work like the rules described in the Bazel blog post. The deps of a py_proto_library rule may only contains other py_proto_library rules. The .proto themselves files must go in srcs.

Body:
I would like to import a.proto into b.proto and compile with Bazel.

BUILD:

py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)

b.proto

import public "a.proto";

When I run it with Bazel I get does not have mandatory providers: 'py'. error, even though according to the example here that's how it should work.

I tried using filegroup to add a.proto as a dependency, and same error, because apparently deps expects python files.
Is py_proto_library operating differently than java_proto_library? If so, how can I add a.proto as dependency so that it gets imported correctly?

EDIT:
I am loading protobuf from https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz

This rule accepts .proto files if you pass them as proto_deps, but then I get an error Import "a.proto" was not found or had errors.

Maybe I should specify imports somehow?


问:
Switch statement for multiple cases

Can anyone please tell me what is the purpose of the marked portions? (source)

I know that we can use multiple case statement like below

```<code>case black:
printf ("black\n");
break;
case blue:
case cyan:
case red:
printf("blue");
break;
</code>```

答:
They're actually regular labels that could be used as the target for a goto.  That is, you could write goto cyan; somewhere in the function and it would jump to the label cyan: inside the switch.

It is likely they're a thinko error — they're probably intended to be case labels case cyan: case green: case magenta: ….  Note that one of the classic errors in a switch is to introduce a label defualt: instead of the default: label.

Looking a bit harder at the code in the image, it is appallingly badly laid out.  After the foreground = blue; assignment, there is a case white: label which is not in the scope of a switch statement, so that's a syntax error.  And the switch (background) is followed by {   } all on one line, so there is no code in the switch and the case black: label is also outside of any switch and hence also a syntax error.

It is conceivable that there's a page fold down the middle of the lower portion of the text, in which case it's curious that the enum colors is spread over the fold line.  The code then makes some sort of sense, though.

If the code is all on one page and 'formatted' like that, then it is grotesque.

If that's not an isolated example of abysmal code, then you should throw the book away, now.  I mean that most sincerely — a book containing that mess isn't worth diddly-squat.  You won't know when it is teaching you anything useful and when it is teaching you complete garbage.  Don't risk it; throw it away. (And if your teacher wrote the book, change classes now.)

Title: Switch statement for multiple cases

Body:
Can anyone please tell me what is the purpose of the marked portions? (source)

I know that we can use multiple case statement like below

case black:
printf ("black\n");
break;
case blue:
case cyan:
case red:
printf("blue");
break;


问:
Why mpirun freeze in loop
Here is my script and python code.

$ cat go

```<code>while true
do
echo "------->"
python3 -m mpi4py ./go.py
echo "<------"
done
</code>```

This code run python go.py in loop.

$ cat go.py

```<code>import mpi4py.MPI as MPI

print( "######", MPI.Is_initialized())

comm = MPI.COMM_WORLD
comm_rank = comm.Get_rank()
comm_size = comm.Get_size()

# point to point communication
data_send = [comm_rank]*5
comm.send(data_send,dest=(comm_rank+1)%comm_size)
data_recv =comm.recv(source=(comm_rank-1)%comm_size)
print("my rank is %d, and Ireceived:" % comm_rank)
print( data_recv )

MPI.Finalize()

print( "######", MPI.Is_finalized())
</code>```

This python code just print.

After I run this go script, the go.py execute and exit, when go.py execute again,
it got stuck.

$ mpirun --mca orte_base_help_aggregate 0 -np 2 sh ./go

```<code>------->
------->
--------------------------------------------------------------------------
[[27909,1],1]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
[[27909,1],0]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
###### True
###### True
my rank is 0, and Ireceived:
[1, 1, 1, 1, 1]
my rank is 1, and Ireceived:
[0, 0, 0, 0, 0]
###### True
###### True
<------
------->
<------
------->
--------------------------------------------------------------------------
[[27909,1],0]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
[[27909,1],1]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
</code>```

and freeze for ever.

Why does it stuck, and how can I continue this script?

BTW:
I have two kind of job A/B to run, job A persist, job B finish and quit. So I can't run it as following:

```<code>while true
do
  echo "------->"
  mpirun -np 2 A : -np 2 B
  echo "<------"
done
</code>```

Is there other way to do this?

答:
long story short, you cannot do that.

here is what you should do instead

```<code>while true
do
  echo "------->"
  mpirun --mca orte_base_help_aggregate 0 -np 2 python3 -m mpi4py ./go.py
  echo "<------"
done
</code>```

Title: Why mpirun freeze in loop

Body:
Here is my script and python code.

$ cat go

while true
do
echo "------->"
python3 -m mpi4py ./go.py
echo "<------"
done

This code run python go.py in loop.

$ cat go.py

import mpi4py.MPI as MPI

print( "######", MPI.Is_initialized())

comm = MPI.COMM_WORLD
comm_rank = comm.Get_rank()
comm_size = comm.Get_size()

# point to point communication
data_send = [comm_rank]*5
comm.send(data_send,dest=(comm_rank+1)%comm_size)
data_recv =comm.recv(source=(comm_rank-1)%comm_size)
print("my rank is %d, and Ireceived:" % comm_rank)
print( data_recv )

MPI.Finalize()

print( "######", MPI.Is_finalized())

This python code just print.

After I run this go script, the go.py execute and exit, when go.py execute again,
it got stuck.

$ mpirun --mca orte_base_help_aggregate 0 -np 2 sh ./go

------->
------->
--------------------------------------------------------------------------
[[27909,1],1]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
[[27909,1],0]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
###### True
###### True
my rank is 0, and Ireceived:
[1, 1, 1, 1, 1]
my rank is 1, and Ireceived:
[0, 0, 0, 0, 0]
###### True
###### True
<------
------->
<------
------->
--------------------------------------------------------------------------
[[27909,1],0]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
[[27909,1],1]: A high-performance Open MPI point-to-point messaging module
was unable to find any relevant network interfaces:

Module: OpenFabrics (openib)
  Host: myvm20

Another transport will be used instead, although this may result in
lower performance.
--------------------------------------------------------------------------

and freeze for ever.

Why does it stuck, and how can I continue this script?

BTW:
I have two kind of job A/B to run, job A persist, job B finish and quit. So I can't run it as following:

while true
do
  echo "------->"
  mpirun -np 2 A : -np 2 B
  echo "<------"
done

Is there other way to do this?

Body:
long story short, you cannot do that.

here is what you should do instead

while true
do
  echo "------->"
  mpirun --mca orte_base_help_aggregate 0 -np 2 python3 -m mpi4py ./go.py
  echo "<------"
done


问:
How can I convert a part of Java source file to Kotlin?
In my Kotlin project, I have some parts of Java code that I want to convert to Kotlin. The menu item that converts the Java file to Kotlin is disabled because it's not a whole file I want to convert.

How can I convert Java code to Kotlin?

答: Simple Ctrl+Alt+Shift+ K code will convert into kotlin</p>

ContentLicense: CC BY-SA 4.0


问:
I want to display the post excerpt with date and title
I want to display the excerpt of 2 posts with title and post-date, the code is done but it is showing the date only for one post.

Here Is The Code.

```<code><div class="col-md-4">
 <div class="reel-focus-blog wow slideInRight animated">
  <h1>Reel Focus Blog</h1>
   <?php
    $the_query = new WP_Query( 'posts_per_page=2' );
    while ($the_query -> have_posts()) : $the_query ->
     the_post(); ?>
      <div class="reel-focus-blog-box">
       <h3><?php the_title(); ?></h3>
       <p class="datetime"><i><?php the_date();?></i></p>
       <p><?php the_excerpt(__('(more…)')); ?>
       <a class="read-more" href="">Read More</a></>
  </div>

  <?php
  endwhile;
  wp_reset_postdata();?>
 </div>
</div>
</code>```

答:
Test with

get_the_date()

```<code>// The Args
$args = array(
    'posts_per_page' => 2,
    'order' => 'DESC',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
<div class="reel-focus-blog-box">
       <h3><?php the_title(); ?></h3>
       <p class="datetime"><i><?php echo get_the_date();?></i></p>
       <p><?php the_excerpt(); ?>
       <a class="read-more" href="">Read More</a></>
  </div>
    }
} else {
    // no posts found
}
wp_reset_postdata();
</code>```

Body:
I want to display the excerpt of 2 posts with title and post-date, the code is done but it is showing the date only for one post.

Here Is The Code.

Reel Focus Blog

   <?php
    $the_query = new WP_Query( 'posts_per_page=2' );
    while ($the_query -> have_posts()) : $the_query ->
     the_post(); ?>

<?php the_title(); ?>

<?php the_date();?>

<?php the_excerpt(__('(more…)')); ?>
       Read More</>

  <?php
  endwhile;
  wp_reset_postdata();?>

Body:
Test with

get_the_date()

// The Args
$args = array(
    'posts_per_page' => 2,
    'order' => 'DESC',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
<div class="reel-focus-blog-box">
       <h3><?php the_title(); ?></h3>
       <p class="datetime"><i><?php echo get_the_date();?></i></p>
       <p><?php the_excerpt(); ?>
       <a class="read-more" href="">Read More</a></>
  </div>
    }
} else {
    // no posts found
}
wp_reset_postdata();


问:
Question on my Class implemention in C#
Currently i have a class which has only properties

```<code>class MyEntity
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}
</code>```

In my other class, I use to set the values like

```<code>MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";
</code>```

The reason i have the class MyEntity with only properties is to ensure adherence.

Question here is, if this approach is correct? I can have multiple instances of MyEntity

Can i use Static Class for this? How can i use Generics in this?

BTW the implementation is in C#

Thanks in advance

Cheers,

Karthik

答:
Here is a quick and dirty use of generics for your unspecified DTO I am assuming.</p>

```<code>class MyEntity<T>
{
   public T value { get; set; }
}
</code>```

Title: Question on my Class implemention in C#

Body:
Currently i have a class which has only properties

class MyEntity
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}

In my other class, I use to set the values like

MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";

The reason i have the class MyEntity with only properties is to ensure adherence.

Question here is, if this approach is correct? I can have multiple instances of MyEntity

Can i use Static Class for this? How can i use Generics in this?

BTW the implementation is in C#

Thanks in advance

Cheers,

Karthik

Body:
Here is a quick and dirty use of generics for your unspecified DTO I am assuming.

class MyEntity<T>
{
   public T value { get; set; }
}


问:
i wanted to use this javascript function with asp update panel, Details are bellow

Here is the script that I am using for opening a new tab and it's working without using an update panel:

```<code><script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank';
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</code>```

This is my .aspx page: and i want to use it with update panel please help

```<code><asp:ScriptManager ID="ScriptManager1" runat="server"
</asp:ScriptManager>
<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:Button ID="btnAssign" runat="server" Text="Assign" OnClientClick="SetTarget();" OnClick="btnAssign_Click"/>
     </ContentTemplate>
</asp:UpdatePanel >
</code>```

i want to use it with update panel please help me if there any solution

答:
You can use the below script. It will work for you.

```<code><script language="javascript">
        function SetTarget() {
            document.forms[0].target = "_blank";
            window.open(this.href);
            alert("hello");
            return false;

        }
    </script>
</code>```

do let me know in case you required any more help.

Body:
You can use the below script. It will work for you.

<script language="javascript">
        function SetTarget() {
            document.forms[0].target = "_blank";
            window.open(this.href);
            alert("hello");
            return false;

        }
    </script>

do let me know in case you required any more help.


问:
Read multiple file csv in pandas from a directory and store them in a array of list, each file as one observation
I have a folder, i have 30 CSV files in there , all different name.

I want to loop through all the files and read them using pandas separately, and store them in a list of lists. While reading them separately, I want also to remove some variables from them at the same like remove columns which are correlated.

Currently, I am trying to do this.

```<code>import glob
import pandas as pd
path = os.getcwd()

# Get folder path containing text files
file_list = glob.glob(path + '/*.csv')
data = []
for file_path in file_list:
    data.append(
        pd.read_csv(file_path).drop(['column1', 'column2'], axis =1))
# now you can access it outside the "for loop..."
for d in data:
    print(d)
</code>```

So, I want to store each data frame as 2 D lists in a list and train my model because each[ [CSV][2] ][3]file is an observation. My CSV file is having(5000,12) observations. have label for each CSV or instance, which is the filename.

Don't know If I am moving in right direction.

```<code>len(data)
# 30

label = [1,1,1,1,1,1,1,1,1,1,,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3]
max_length = 25 # shape of data frame after removing two variables
# define the model

model = Sequential()
model.add(Dense(24, input_dim=25, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())
</code>```

答:
I think you can create dictionary of DataFrames with keys from filenames:

```<code>file_list = glob.glob(path + '/*.csv')
dfs = {os.path.basename(fp).split('.')[0]:
       pd.read_csv(fp).drop(['column1', 'column2'], axis=1) for fp in file_list}
</code>```

For select use:

```<code>print (dfs['turbo1'])
</code>```

EDIT:

```<code>dfs=np.array([pd.read_csv(fp).drop(['column1','column2'],axis=1).values for fp in file_list])
</code>```

Body:
I have a folder, i have 30 CSV files in there , all different name.

I want to loop through all the files and read them using pandas separately, and store them in a list of lists. While reading them separately, I want also to remove some variables from them at the same like remove columns which are correlated.

Currently, I am trying to do this.

import glob
import pandas as pd
path = os.getcwd()

# Get folder path containing text files
file_list = glob.glob(path + '/*.csv')
data = []
for file_path in file_list:
    data.append(
        pd.read_csv(file_path).drop(['column1', 'column2'], axis =1))
# now you can access it outside the "for loop..."
for d in data:
    print(d)

So, I want to store each data frame as 2 D lists in a list and train my model because each[ [CSV][2] ][3]file is an observation. My CSV file is having(5000,12) observations. have label for each CSV or instance, which is the filename.

Don't know If I am moving in right direction.

len(data)
# 30

label = [1,1,1,1,1,1,1,1,1,1,,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3]
max_length = 25 # shape of data frame after removing two variables
# define the model

model = Sequential()
model.add(Dense(24, input_dim=25, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())

Body:
I think you can create dictionary of DataFrames with keys from filenames:

file_list = glob.glob(path + '/*.csv')
dfs = {os.path.basename(fp).split('.')[0]:
       pd.read_csv(fp).drop(['column1', 'column2'], axis=1) for fp in file_list}

For select use:

print (dfs['turbo1'])

EDIT:

dfs=np.array([pd.read_csv(fp).drop(['column1','column2'],axis=1).values for fp in file_list])


答:
You code would run fine, if you would have noticed that your Javascript code has a syntax error. You are missing a closing } to define your function. Without it you are receving an unexpected end of input error.
In addition you will not open a new tab until you actually submit your form.

This code will work:

```<code><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <script>
        function SetTarget() {
            document.forms[0].target = "_blank";
            console.log("Foo");
            document.forms[0].submit();

        }
    </script>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Button ID="btnAssign" runat="server" Text="Assign" OnClientClick="SetTarget();" />
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>
</code>```

Title: i wanted to use this javascript function with asp update panel, Details are bellow

Body: Here is the script that I am using for opening a new tab and it's working without using an update panel:

Body:
You code would run fine, if you would have noticed that your Javascript code has a syntax error. You are missing a closing } to define your function. Without it you are receving an unexpected end of input error.
In addition you will not open a new tab until you actually submit your form.

This code will work:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <script>
        function SetTarget() {
            document.forms[0].target = "_blank";
            console.log("Foo");
            document.forms[0].submit();

        }
    </script>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Button ID="btnAssign" runat="server" Text="Assign" OnClientClick="SetTarget();" />
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>


问:
In Go, how to Unmarshal bson byte[] data into an array of structs?
What's the best way to Unmarshal bson byte[] data into an array of structs, when the array of structs is passed into an interface{} parameter?

For demonstration purposes, in the following code, I use bson.Marshal() on the inStructArr to get the byte[] type of data. This is so I can use bson.Unmarshal(...) to pipe into the outStructArr.

```<code>import "gopkg.in/mgo.v2/bson"

type User struct {
    Name string
}

func DecodeArrData(inStructArr, outStructArr interface{}) {
    inStructArrData, _ := bson.Marshal(inStructArr)
    bson.Unmarshal(inStructArrData, outStructArr) // <-- Error happens here
    // What's the right way of accomplishing this?
}

func Main() {
    outUsers := &[]User{}
    inUsers := []User{User{"A"}, User{"B"}}

    DecodeArrData(inUsers, outUsers)
}
</code>```

When I do this, the error-message I get is: Unsupported document type for unmarshalling: []User. What's the right way of doing this?

Thanks in advance!

答:
The Marshal and Unmarshal functions work with BSON documents, not BSON arrays.

Wrap the slices in a struct to provide the document expected by the package:

```<code>func DecodeArrData(inStructArr, outStructArr interface{}) error {
    in := struct{ Data interface{} }{Data: inStructArr}
    inStructArrData, err := bson.Marshal(in)
    if err != nil {
        return err
    }
    var out struct{ Data bson.Raw }
    if err := bson.Unmarshal(inStructArrData, &out); err != nil {
        return err
    }
    return out.Data.Unmarshal(outStructArr)
}
</code>```

If you are willing to take advantage of an undocumented feature of the Marshal function and add some BSON format knowledge to your application, then you can omit the wrapper.

The undocumented feature of Marshal is that it encodes slices as BSON arrays. The BSON array can be decoded using a bson.Raw value with Kind set the the BSON code for arrays (the value 4) and Data set to the array data:

```<code>func DecodeArrData(inStructArr, outStructArr interface{}) error {
    inStructArrData, err := bson.Marshal(inStructArr)
    if err != nil {
        return err
    }
    raw := bson.Raw{Kind: 4, Data: inStructArrData}
    return raw.Unmarshal(outStructArr)
}
</code>```

Body:
What's the best way to Unmarshal bson byte[] data into an array of structs, when the array of structs is passed into an interface{} parameter?

For demonstration purposes, in the following code, I use bson.Marshal() on the inStructArr to get the byte[] type of data. This is so I can use bson.Unmarshal(...) to pipe into the outStructArr.

import "gopkg.in/mgo.v2/bson"

type User struct {
    Name string
}

func DecodeArrData(inStructArr, outStructArr interface{}) {
    inStructArrData, _ := bson.Marshal(inStructArr)
    bson.Unmarshal(inStructArrData, outStructArr) // <-- Error happens here
    // What's the right way of accomplishing this?
}

func Main() {
    outUsers := &[]User{}
    inUsers := []User{User{"A"}, User{"B"}}

    DecodeArrData(inUsers, outUsers)
}

When I do this, the error-message I get is: Unsupported document type for unmarshalling: []User. What's the right way of doing this?

Thanks in advance!

Body:
The Marshal and Unmarshal functions work with BSON documents, not BSON arrays.

Wrap the slices in a struct to provide the document expected by the package:

func DecodeArrData(inStructArr, outStructArr interface{}) error {
    in := struct{ Data interface{} }{Data: inStructArr}
    inStructArrData, err := bson.Marshal(in)
    if err != nil {
        return err
    }
    var out struct{ Data bson.Raw }
    if err := bson.Unmarshal(inStructArrData, &out); err != nil {
        return err
    }
    return out.Data.Unmarshal(outStructArr)
}

If you are willing to take advantage of an undocumented feature of the Marshal function and add some BSON format knowledge to your application, then you can omit the wrapper.

The undocumented feature of Marshal is that it encodes slices as BSON arrays. The BSON array can be decoded using a bson.Raw value with Kind set the the BSON code for arrays (the value 4) and Data set to the array data:

func DecodeArrData(inStructArr, outStructArr interface{}) error {
    inStructArrData, err := bson.Marshal(inStructArr)
    if err != nil {
        return err
    }
    raw := bson.Raw{Kind: 4, Data: inStructArrData}
    return raw.Unmarshal(outStructArr)
}


问:
Remove only Horizontal Border from Table
I only want the horizontal line to be removed.

Meaning rows should not have lines and column should have lines.

In my code, there is no line in row as well as column.

I tried:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Company
Number

Demo (2)

2017-11-16 12:18:15

        Sr.
        Item
        Qty
        Amount

          1

          Shirt  (DC Dry Clean)

          2

          100

          2

          Saree  (RP ROll Polish)

          2

          100

        Two Hundred Rupees Only
        Total:
        200

```

I only want the horizontal line to be removed after the first row, i.e after Sr, Item and all, and before amount row (the last row).

答:
try this</p>

```<code> .table-bordered>tbody>tr>th {
    border: 0px solid #ddd;
}
</code>```

Body:
I only want the horizontal line to be removed.

Meaning rows should not have lines and column should have lines.

In my code, there is no line in row as well as column.

I tried:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Company
Number

Demo (2)

2017-11-16 12:18:15

        Sr.
        Item
        Qty
        Amount

          1

          Shirt  (DC Dry Clean)

          2

          100

          2

          Saree  (RP ROll Polish)

          2

          100

        Two Hundred Rupees Only
        Total:
        200

I only want the horizontal line to be removed after the first row, i.e after Sr, Item and all, and before amount row (the last row).

Body:
try this

 .table-bordered>tbody>tr>th {
    border: 0px solid #ddd;
}


问:
NFC-reader on Win IOT: Pin ' is currently opened in an incompatible sharing mode
I am working on a NFC reader project based on Windows 10 IoT running on a Rasperry PI 3.

I use the library Mfrc522lib.cs found here: RFID RC522 Raspberry PI 2 Windows IOT.
I use an async task to wait for the card. It scans perfect the first time, but when I start the task again (for test puprose with button).
I get this:

Pin ' is currently opened in an incompatible sharing mode. Make sure this pin is not already in use by this application or another Application

Any idea?

```<code>public MainPage()
{
    this.InitializeComponent();
    startNFC();
}

public void startNFC()
{
    var read = ReadNFCAsync();

    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () =>
        {
            // Your UI update code goes here!
            this.serial.Text = "Klar for å lese kortet ditt";
            this.statusline.Fill = new SolidColorBrush(Colors.Green);
        });
    read.ContinueWith(prev => {
        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                // Your UI update code goes here!
                this.serial.Text = prev.Result.ToString();
                this.statusline.Fill = new SolidColorBrush(Colors.Orange);
            });
    });
}

public static async Task<String> ReadNFCAsync()
{
    await Task.Delay(1000);
    var mfrc  = new Mfrc522();

    await mfrc.InitIO();

    while (true)
    {
        if (mfrc.IsTagPresent())
        {

            var uid = mfrc.ReadUid();
            var serial= uid.ToString();

            mfrc.HaltTag();
            return serial;

        }
    }
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    startNFC();
}
</code>```

答:
This issue due to initializing GPIO pin is in use. Because every time you click the button the following line will be executed:

```<code>await mfrc.InitIO();
</code>```

To solve this problem you can edit your code like this:

```<code>    private Mfrc522 mfrc = new Mfrc522();

    public static bool IsGpioInitialized = false;

    public async Task ReadNFCAsync()
    {
        if (!IsGpioInitialized)
        {
            await mfrc.InitIO();
            IsGpioInitialized = true;
        }
    }
</code>```

Body:
I am working on a NFC reader project based on Windows 10 IoT running on a Rasperry PI 3.

I use the library Mfrc522lib.cs found here: RFID RC522 Raspberry PI 2 Windows IOT.
I use an async task to wait for the card. It scans perfect the first time, but when I start the task again (for test puprose with button).
I get this:

Pin ' is currently opened in an incompatible sharing mode. Make sure this pin is not already in use by this application or another Application

Any idea?

public MainPage()
{
    this.InitializeComponent();
    startNFC();
}

public void startNFC()
{
    var read = ReadNFCAsync();

    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () =>
        {
            // Your UI update code goes here!
            this.serial.Text = "Klar for å lese kortet ditt";
            this.statusline.Fill = new SolidColorBrush(Colors.Green);
        });
    read.ContinueWith(prev => {
        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                // Your UI update code goes here!
                this.serial.Text = prev.Result.ToString();
                this.statusline.Fill = new SolidColorBrush(Colors.Orange);
            });
    });
}

public static async Task<String> ReadNFCAsync()
{
    await Task.Delay(1000);
    var mfrc  = new Mfrc522();

    await mfrc.InitIO();

    while (true)
    {
        if (mfrc.IsTagPresent())
        {

            var uid = mfrc.ReadUid();
            var serial= uid.ToString();

            mfrc.HaltTag();
            return serial;

        }
    }
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    startNFC();
}

Body:
This issue due to initializing GPIO pin is in use. Because every time you click the button the following line will be executed:

await mfrc.InitIO();

To solve this problem you can edit your code like this:

    private Mfrc522 mfrc = new Mfrc522();

    public static bool IsGpioInitialized = false;

    public async Task ReadNFCAsync()
    {
        if (!IsGpioInitialized)
        {
            await mfrc.InitIO();
            IsGpioInitialized = true;
        }
    }


问:
How do I open a new window/tab and dynamically fill it with content?
I am building a website that displays recipes. Each recipe appears as part of a blog entry, and will have a link at the bottom to Print this recipe.

What I want to happen is a click on the link opens a new window and fills it with a print-friendly-styled version of the recipe, which is already inside its own
.

Can I do this with JS/jQuery alone, or do I need to process from the server side? Any ideas how to do this?

EDIT: What would be ideal would be to generate a PDF on the fly, but in lieu of that I'd like a new window, containing only the recipe, for the visitor to print out or save, as they see fit. Print-styles are nice, but most people don't know they exist and can't be bothered to check and see by printing out a page that doesn't look print ready.

答:
Yes, you can(Hello Mr. Obama).

Most browsers allow you to pass in a data: format string, like

```<code>window.open('data:text/html;charset=utf-8,text%20to%20show');
</code>```

which would open a new window / tab (that is browser config dependend) with the Content "text to show". You can pass in HTML code in the same manner, probably escaped.

```<code>var print = $('<div>', {
   id:   'foobar',
   html: 'Hello world',
   css:  {
      backgroundColor:   '#ff0000',
      color:    '#ffffff',
      width:    '200px',
      height:   '200px'
   }
}),
opener = $('<div>').append(print);

window.open('data:text/html;charset=utf-8,' + opener.html());
</code>```

Demo: http://www.jsfiddle.net/4yUqL/73/

Body:
Yes, you can(Hello Mr. Obama).

Most browsers allow you to pass in a data: format string, like

window.open('data:text/html;charset=utf-8,text%20to%20show');

which would open a new window / tab (that is browser config dependend) with the Content "text to show". You can pass in HTML code in the same manner, probably escaped.

var print = $('<div>', {
   id:   'foobar',
   html: 'Hello world',
   css:  {
      backgroundColor:   '#ff0000',
      color:    '#ffffff',
      width:    '200px',
      height:   '200px'
   }
}),
opener = $('<div>').append(print);

window.open('data:text/html;charset=utf-8,' + opener.html());

Demo: http://www.jsfiddle.net/4yUqL/73/


问:
how to re-arrange divs
```<code><div class="row">
  <div class="pimage clr">
    <img src="./images/portfolio/1.jpg" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">Onet</div>
    </div>
  </div>
  <div class="pvideo">
    <img src="./images/portfolio/2.jpg" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">two</div>
    </div>
  </div>
  <div class="pimage">
    <img src="./images/portfolio/3.jpg" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">three</div>
    </div>
  </div>
</div>
</div>
</code>```

in larger display  i want this to display in the same order, but for tablet i want to display one and three together and two below them.

答:
You can use bootstrap grid and use pull and push methods. Here is the sample example how it will work. First order your block as per the tablet device and then try to arrange the order for large device.

Initially |A|B|C| then we are going to change the order |A|C| and then below |B|

```<code>  <div class="row">
       <div class="col-sm-4 col-xs-6">
           Content A
       </div>
       <div class="col-sm-4 col-xs-6 col-sm-push-4">
           Content C
       </div>
       <div class="col-sm-4 col-xs-12 col-sm-pull-4">
           Content B
       </div>
  </div>
</code>```

If you seen the above code, I am pushing my Content C block to push right side and then Content B block to pull left side. Initially I have ordered it as per my desired screen then I moved the blocks accordingly for small screens.

DEMO

Read the below SO Question for more clarity.

Bootstrap 3: Push/pull columns only on smaller screen sizes

Title: how to re-arrange divs

Body:
Onet

two

three

in larger display  i want this to display in the same order, but for tablet i want to display one and three together and two below them.

Body:
You can use bootstrap grid and use pull and push methods. Here is the sample example how it will work. First order your block as per the tablet device and then try to arrange the order for large device.

Initially |A|B|C| then we are going to change the order |A|C| and then below |B|

  <div class="row">
       <div class="col-sm-4 col-xs-6">
           Content A
       </div>
       <div class="col-sm-4 col-xs-6 col-sm-push-4">
           Content C
       </div>
       <div class="col-sm-4 col-xs-12 col-sm-pull-4">
           Content B
       </div>
  </div>

If you seen the above code, I am pushing my Content C block to push right side and then Content B block to pull left side. Initially I have ordered it as per my desired screen then I moved the blocks accordingly for small screens.

DEMO

Read the below SO Question for more clarity.

Bootstrap 3: Push/pull columns only on smaller screen sizes


问:
Getting Kanban throughput data from Microsoft VSO
I'm creating a throughput calculator for my team based on our data in the MS VSO tool.  In order to accurately indicate the date we start work on a PBI I need to extract the date a PBI is committed to.

Is it possible to query the MS VSO product in order to extract the dates that a PBI changed state to "Committed"?

I can get "Created Date" via the query editor (column options only I'm afraid), but VSO doesn't seem to allow access to the state change dates.  And start date isn't correct, as the PBI may have been kicking around in the backlog for some time before it's Dev ready.

答:
Cannot achieve that with the query by default.

But you could query the work item history with the TFS API and check the timestamps on when the state transitions occurred.

Refer to this article to do that : TFS SDK: Work Item History Visualizer using TFS API

You can also use the REST API to extract the dates that a Work item changed state.

For example, you can use  below PowerShell sample to get the date changed to "Committed":

```<code>Param(
   [string]$collectionurl = "https://instance.visualstudio.com",  #If on-premise TFS change it to http://server:8080/tfs/DefaultCollection
   [string]$workitemId = "62",
   [string]$user = "username",
   [string]$token = "token"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$baseUrl = "$collectionurl/_apis/wit/workitems/$($workitemId)/revisions?api-version=1.0"
$response = (Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)})
$revisions = $response.value.fields | where({$_.'System.State' -eq 'Committed'}) # Change the sate which you want to get it's changed date here

$witrevisions = @()

foreach($revision in $revisions){

    $customObject = new-object PSObject -property @{
          "WorkItemType" = $revision.'System.WorkItemType'
          "CommittedDate" = $revision.'System.ChangedDate'
          "ChangedBy" = $revision.'System.ChangedBy'
        }

    $witrevisions += $customObject
}

$witrevisions | Select-Object -Last 1 `
                WorkItemType,
                CommittedDate,
                ChangedBy
</code>```

Body:
Cannot achieve that with the query by default.

But you could query the work item history with the TFS API and check the timestamps on when the state transitions occurred.

Refer to this article to do that : TFS SDK: Work Item History Visualizer using TFS API

You can also use the REST API to extract the dates that a Work item changed state.

For example, you can use  below PowerShell sample to get the date changed to "Committed":

Param(
   [string]$collectionurl = "https://instance.visualstudio.com",  #If on-premise TFS change it to http://server:8080/tfs/DefaultCollection
   [string]$workitemId = "62",
   [string]$user = "username",
   [string]$token = "token"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$baseUrl = "$collectionurl/_apis/wit/workitems/$($workitemId)/revisions?api-version=1.0"
$response = (Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)})
$revisions = $response.value.fields | where({$_.'System.State' -eq 'Committed'}) # Change the sate which you want to get it's changed date here

$witrevisions = @()

foreach($revision in $revisions){

    $customObject = new-object PSObject -property @{
          "WorkItemType" = $revision.'System.WorkItemType'
          "CommittedDate" = $revision.'System.ChangedDate'
          "ChangedBy" = $revision.'System.ChangedBy'
        }

    $witrevisions += $customObject
}

$witrevisions | Select-Object -Last 1 `
                WorkItemType,
                CommittedDate,
                ChangedBy


问:
Google map does not fit in SubView properly
I am using Google map but it's not set properly in subView.
I am using swift 3.

```<code>@IBOutlet weak var mapSubView: UIView!
 var mapView:GMSMapView!
var placesClient: GMSPlacesClient!
</code>```

I have used the following code in viewDidLoad:

```<code>let camera = GMSCameraPosition.camera(withLatitude: 28.616536, longitude: 77.379552, zoom: 12.0)
mapView = GMSMapView.map(withFrame: mapSubView.bounds, camera: camera)
mapSubView.addSubview(mapView)
mapView.delegate = self
self.drawPath()
placesClient = GMSPlacesClient.shared()
</code>```

Screenshot from my simulator:

You have see white space in right side near google map

And a screenshot from my storyboard:

答:
In viewDidLoad, your view is not completely rendered so the line

```<code>mapView = GMSMapView.map(withFrame: mapSubView.bounds, camera: camera)
</code>```

will set the size of the mapView based on the bounds at that particular time. There are a couple of work arounds. One is to render your mapView at a later time e.g. in viewWillAppear. The other is to create a UIView in storyboard, set it's constraints, make it's class to be GMSMapView and connect an @IBOutlet. Also, you can fix it by using autoresizingMask

Body:
I am using Google map but it's not set properly in subView.
I am using swift 3.

@IBOutlet weak var mapSubView: UIView!
 var mapView:GMSMapView!
var placesClient: GMSPlacesClient!

I have used the following code in viewDidLoad:

let camera = GMSCameraPosition.camera(withLatitude: 28.616536, longitude: 77.379552, zoom: 12.0)
mapView = GMSMapView.map(withFrame: mapSubView.bounds, camera: camera)
mapSubView.addSubview(mapView)
mapView.delegate = self
self.drawPath()
placesClient = GMSPlacesClient.shared()

Screenshot from my simulator:

You have see white space in right side near google map

And a screenshot from my storyboard:

Body:
In viewDidLoad, your view is not completely rendered so the line

mapView = GMSMapView.map(withFrame: mapSubView.bounds, camera: camera)

will set the size of the mapView based on the bounds at that particular time. There are a couple of work arounds. One is to render your mapView at a later time e.g. in viewWillAppear. The other is to create a UIView in storyboard, set it's constraints, make it's class to be GMSMapView and connect an @IBOutlet. Also, you can fix it by using autoresizingMask


问:
Drupal: PDOException: could not find driver in lock_may_be_available()
I am running Drupal on my local machine using Windows and recently I opened a project solution within Visual Studio.  Upon opening the solution, it asked me to install PHP7 extensions via the Microsoft Web Platform Installer.  After these extensions were installed, when I navigate to my local Drupal site, I get the following error:

PDOException: could not find driver in lock_may_be_available()

I did do some research before I decided to ask this question and it seems that I'm just missing this driver.

If this is the problem, how do I install the right PDO driver for Drupal?

Any help is greatly appreciated!

答:
It's not driver for Drupal, but for PHP. It's name should be "pdo_mysql", "php_pdo_mysql" or similar, depending on platform. Since you are on windows you should look for a way to install it there. I.e. check this SO post:

PHP - How to install PDO driver? (Windows)

BTW, will you site really run on windows server? If not, my advise is to develop on virtual machine, so you'll have the same development environment, as production will be (most likely linux, right?).