问:
Spring with Hibernate - Pre-bound JDBC Connection found
Faced weird problem with "Pre-bound JDBC Connection found" in Spring (5.1.7.RELEASE) and Hibernate (5.4.10.Final). I've read related questions and need to say that I have only 1 datasource and only 1 transaction manager in my code. App is running on Wildfly 18.0.1.

So here's my hibernate config:

```<code>@Bean
public LocalSessionFactoryBean sessionFactory() throws NamingException {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.mycompany"});
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() throws NamingException {
    return (DataSource) new JndiTemplate().lookup(env.getProperty("jndi.jdbc.AGSQL"));
}

@Bean(name = "transactionManager")
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory);
    return txManager;
}

private Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
            setProperty("show_sql", env.getProperty("show_sql"));
            setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_UNCOMMITTED));
        }
    };
}
</code>```

Datasource is configured via jndi. And when I try to open any page it throws error:

```<code>18:39:28,457 ERROR [io.undertow.request] (default task-30) UT005023: Exception handling request to /AGService/map: org.springframework.transaction.IllegalTransactionStateException: Pre-bound JDBC Connection found! HibernateTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself. It is recommended to use a single HibernateTransactionManager for all transactions on a single DataSource, no matter whether Hibernate or JDBC access.
    at deployment.artifacts.war//org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:449)
    at deployment.artifacts.war//org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:378)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:475)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:289)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at deployment.artifacts.war//org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at deployment.artifacts.war//com.mycompany.hibernate.dao.www.UserDao$$EnhancerBySpringCGLIB$$2ab37f7a.getByLogin(<generated>)
    at deployment.artifacts.war//com.mycompany.hibernate.service.www.UserService.getByLogin(UserService.java:23)
    at deployment.artifacts.war//com.mycompany.hibernate.service.www.UserDetailsService.loadUserByUsername(UserDetailsService.java:20)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at deployment.artifacts.war//org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at deployment.artifacts.war//org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at deployment.artifacts.war//com.sun.proxy.$Proxy355.loadUserByUsername(Unknown Source)
    at deployment.artifacts.war//org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:451)
    at deployment.artifacts.war//org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.processAutoLoginCookie(TokenBasedRememberMeServices.java:123)
    at deployment.artifacts.war//org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.autoLogin(AbstractRememberMeServices.java:136)
    at deployment.artifacts.war//org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:98)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
    at deployment.artifacts.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at deployment.artifacts.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at deployment.artifacts.war//org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at deployment.artifacts.war//org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.MetricsHandler.handleRequest(MetricsHandler.java:64)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.MetricsChainHandler.handleRequest(MetricsChainHandler.java:59)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
    at io.undertow.core@2.0.27.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at io.undertow.core@2.0.27.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

It's UserDao class:

```<code>@Repository
public class UserDao extends AbstractDao<Long, UserEntity> {

    public UserDao() {
        super(UserEntity.class);
    }

    /**
     * Get user by login
     * @param login String
     * @return User object
     */
    @Transactional("transactionManager")
    public User getByLogin(String login) {
        Session session = getSession();
        User user = null;
        try {
            UserEntity userEntity = (UserEntity)session
                    .createQuery("FROM UserEntity WHERE login = :login")
                    .setParameter("login", login).uniqueResult();
            user = new User(userEntity);

            RoleEntity roleEntity = (RoleEntity)session
                                        .createQuery("FROM RoleEntity WHERE id = :id")
                                        .setParameter("id", user.getRoleId())
                                        .uniqueResult();
            user.setRole(roleEntity);

        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return user;
    }
}
</code>```

So...I have only one datasource, but have this exception...
And that's not all. If I change data source to this, my app works properly without any exceptions:

```<code>@Bean
public DataSource dataSource() throws NamingException {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("hibernate.connection.driver_class"));
    dataSource.setUrl(env.getProperty("hibernate.connection.url"));
    dataSource.setUsername(env.getProperty("hibernate.connection.username"));
    dataSource.setPassword(env.getProperty("hibernate.connection.password"));
    return dataSource;
}
</code>```

I think that Wildfly can manage it's own transactions with it's own datasources, but I didn't find any settings for transactions on Wildfly config.
And anyway I need to have a transactionmanager bean to link from @Transactional.

I'm stuck on it, any help appreciated.

答:
Changed transaction manager to this and now it works as expected:

```<code>@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(SessionFactory sessionFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(sessionFactory);
    return transactionManager;
}
</code>```

But what's the inner differences between these two implementations?

Body:
Faced weird problem with "Pre-bound JDBC Connection found" in Spring (5.1.7.RELEASE) and Hibernate (5.4.10.Final). I've read related questions and need to say that I have only 1 datasource and only 1 transaction manager in my code. App is running on Wildfly 18.0.1.

So here's my hibernate config:

@Bean
public LocalSessionFactoryBean sessionFactory() throws NamingException {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.mycompany"});
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() throws NamingException {
    return (DataSource) new JndiTemplate().lookup(env.getProperty("jndi.jdbc.AGSQL"));
}

@Bean(name = "transactionManager")
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory);
    return txManager;
}

private Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
            setProperty("show_sql", env.getProperty("show_sql"));
            setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_UNCOMMITTED));
        }
    };
}

Datasource is configured via jndi. And when I try to open any page it throws error:

18:39:28,457 ERROR [io.undertow.request] (default task-30) UT005023: Exception handling request to /AGService/map: org.springframework.transaction.IllegalTransactionStateException: Pre-bound JDBC Connection found! HibernateTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself. It is recommended to use a single HibernateTransactionManager for all transactions on a single DataSource, no matter whether Hibernate or JDBC access.
    at deployment.artifacts.war//org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:449)
    at deployment.artifacts.war//org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:378)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:475)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:289)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at deployment.artifacts.war//org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at deployment.artifacts.war//com.mycompany.hibernate.dao.www.UserDao$$EnhancerBySpringCGLIB$$2ab37f7a.getByLogin(<generated>)
    at deployment.artifacts.war//com.mycompany.hibernate.service.www.UserService.getByLogin(UserService.java:23)
    at deployment.artifacts.war//com.mycompany.hibernate.service.www.UserDetailsService.loadUserByUsername(UserDetailsService.java:20)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at deployment.artifacts.war//org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
    at deployment.artifacts.war//org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at deployment.artifacts.war//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at deployment.artifacts.war//org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at deployment.artifacts.war//com.sun.proxy.$Proxy355.loadUserByUsername(Unknown Source)
    at deployment.artifacts.war//org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:451)
    at deployment.artifacts.war//org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.processAutoLoginCookie(TokenBasedRememberMeServices.java:123)
    at deployment.artifacts.war//org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.autoLogin(AbstractRememberMeServices.java:136)
    at deployment.artifacts.war//org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:98)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
    at deployment.artifacts.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at deployment.artifacts.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at deployment.artifacts.war//org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at deployment.artifacts.war//org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at deployment.artifacts.war//org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.core@2.0.27.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.core@2.0.27.Final//io.undertow.server.handlers.MetricsHandler.handleRequest(MetricsHandler.java:64)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.MetricsChainHandler.handleRequest(MetricsChainHandler.java:59)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow@18.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
    at io.undertow.servlet@2.0.27.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
    at io.undertow.core@2.0.27.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at io.undertow.core@2.0.27.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)

It's UserDao class:

@Repository
public class UserDao extends AbstractDao<Long, UserEntity> {

    public UserDao() {
        super(UserEntity.class);
    }

    /**
     * Get user by login
     * @param login String
     * @return User object
     */
    @Transactional("transactionManager")
    public User getByLogin(String login) {
        Session session = getSession();
        User user = null;
        try {
            UserEntity userEntity = (UserEntity)session
                    .createQuery("FROM UserEntity WHERE login = :login")
                    .setParameter("login", login).uniqueResult();
            user = new User(userEntity);

            RoleEntity roleEntity = (RoleEntity)session
                                        .createQuery("FROM RoleEntity WHERE id = :id")
                                        .setParameter("id", user.getRoleId())
                                        .uniqueResult();
            user.setRole(roleEntity);

        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return user;
    }
}

So...I have only one datasource, but have this exception...
And that's not all. If I change data source to this, my app works properly without any exceptions:

@Bean
public DataSource dataSource() throws NamingException {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("hibernate.connection.driver_class"));
    dataSource.setUrl(env.getProperty("hibernate.connection.url"));
    dataSource.setUsername(env.getProperty("hibernate.connection.username"));
    dataSource.setPassword(env.getProperty("hibernate.connection.password"));
    return dataSource;
}

I think that Wildfly can manage it's own transactions with it's own datasources, but I didn't find any settings for transactions on Wildfly config.
And anyway I need to have a transactionmanager bean to link from @Transactional.

I'm stuck on it, any help appreciated.

Body:
Changed transaction manager to this and now it works as expected:

@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(SessionFactory sessionFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(sessionFactory);
    return transactionManager;
}

But what's the inner differences between these two implementations?


来源: stackexchange

问:
Why should i put service name after create in the providers array in app.module.ts?
I am using as always ng g s [nameOfTheService] to generate a service.That makes the following service

```<code>
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TestService {

  constructor() { }
}

</code>```

this service can be accessed now through all components,but i saw one video where it is saying that we should specify the name of the service in the providers array in the app.module.ts file.
Why we should do that? I never did that and i never had problems with singleton dependency injection in angular.

答:
The injector is responsible for creating service instances and injecting them into classes.

Should, for example, the service live once inside the app or module? Or should every component that depends on the service have its own instance?

Depending on the context, you might have to set metadata inside the @NgModule() decorator.

From the docs:

You can configure injectors with providers at different levels of your app, by setting a metadata value in one of three places:

In the @Injectable() decorator for the service itself.

In the @NgModule() decorator for an NgModule.

In the @Component() decorator for a component.

The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule.

The @NgModule() and @Component() decorators have the providers metadata option, where you can configure providers for NgModule-level or component-level injectors.

ContentLicense: CC BY-SA 4.0

Body:
I am using as always ng g s [nameOfTheService] to generate a service.That makes the following service

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TestService {

  constructor() { }
}

this service can be accessed now through all components,but i saw one video where it is saying that we should specify the name of the service in the providers array in the app.module.ts file.
Why we should do that? I never did that and i never had problems with singleton dependency injection in angular.

Body:
The injector is responsible for creating service instances and injecting them into classes.

Should, for example, the service live once inside the app or module? Or should every component that depends on the service have its own instance?

Depending on the context, you might have to set metadata inside the @NgModule() decorator.

From the <a href="http://You%20can%20configure%20injectors%20with%20providers%20at%20different%20levels%20of%20your%20app,%20by%20setting%20a%20metadata%20value%20in%20one%20of%20three%20places:%20%20In%20the%20@Injectable()%20decorator%20for%20the%20service%20itself.%20%20In%20the%20@NgModule()%20decorator%20for%20an%20NgModule.%20%20In%20the%20@Component()%20decorator%20for%20a%20component.%20%20The%20@Injectable()%20decorator%20has%20the%20providedIn%20metadata%20option,%20where%20you%20can%20specify%20the%20provider%20of%20the%20decorated%20service%20class%20with%20the%20root%20injector,%20or%20with%20the%20injector%20for%20a%20specific%20NgModule.%20%20The%20@NgModule()%20and%20@Component()%20decorators%20have%20the%20providers%20metadata%20option,%20where%20you%20can%20configure%20providers%20for%20NgModule-level%20or%20component-level%20injectors." rel="nofollow noreferrer">docs:

You can configure injectors with providers at different levels of your app, by setting a metadata value in one of three places:

In the @Injectable() decorator for the service itself.

In the @NgModule() decorator for an NgModule.

In the @Component() decorator for a component.

The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule.

The @NgModule() and @Component() decorators have the providers metadata option, where you can configure providers for NgModule-level or component-level injectors.


问:
Add ... if string is too long PHP
I have a description field in my MySQL database, and I access the database on two different pages, one page I display the whole field, but on the other, I just want to display the first 50 characters.  If the string in the description field is less than 50 characters, then it won't show ... , but if it isn't, I will show ... after the first 50 characters.

Example (Full string):

```<code>Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...
</code>```

Exmaple 2 (first 50 characters):

```<code>Hello, this is the first example, where I am going ...
</code>```

答:
For some of you who uses Yii2 there is a method under the hood yii\helpers\StringHelper::truncate().

Example of usage:

```<code>$sting = "stringToTruncate";
$truncatedString = \yii\helpers\StringHelper::truncate($string, 6, '...');
echo $truncatedString; // result: "string..."
</code>```

Here is the doc: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#truncate()-detail

ContentLicense: CC BY-SA 3.0

Title: Add ... if string is too long PHP

Body:
I have a description field in my MySQL database, and I access the database on two different pages, one page I display the whole field, but on the other, I just want to display the first 50 characters.  If the string in the description field is less than 50 characters, then it won't show ... , but if it isn't, I will show ... after the first 50 characters.

Example (Full string):

Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...

Exmaple 2 (first 50 characters):

Hello, this is the first example, where I am going ...

Body:
For some of you who uses Yii2 there is a method under the hood yii\helpers\StringHelper::truncate().

Example of usage:

$sting = "stringToTruncate";
$truncatedString = \yii\helpers\StringHelper::truncate($string, 6, '...');
echo $truncatedString; // result: "string..."

Here is the doc: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#truncate()-detail


问:
Django, How do I access the LANGUAGE_CODE
When you start translating your app things become very interesting and it really challenges the way you build you applications.

in your settings.py file you add all of the different languages

```<code>LANGUAGES = (
    ('en', gettext('English')),
    ('sv', gettext('Swedish')),
    ('no', gettext('Norwegian')),
)
</code>```

no I know you can use get_current_language as LANGUAGE_CODE to access the first bit ie, en

is there a way in my template that I can access the display text ie, English ?

答:
If you have LANGUAGE_CODE you can use language_name filter:

```<code>{{ LANGUAGE_CODE|language_name }}
</code>```

(and many other possibilities: django template translation-specific variables)

In django < v1.3:

You can access available languages list via:

```<code>{% get_available_languages as LANGUAGES %}
</code>```

To show this ist:

```<code>{% for lang in LANGUAGES %}
 CODE:{{ lang.0 }}, NAME:{{ lang.1 }}
{% endfor %}
</code>```

As you can see language name is lang.1 (second member of the inner tuple)

If you want the name of a language that you have it's code, either put that in the context before passing it to the template or in the loop above add a comparaison condition to get the name.

Body:
When you start translating your app things become very interesting and it really challenges the way you build you applications.

in your settings.py file you add all of the different languages

LANGUAGES = (
    ('en', gettext('English')),
    ('sv', gettext('Swedish')),
    ('no', gettext('Norwegian')),
)

no I know you can use get_current_language as LANGUAGE_CODE to access the first bit ie, en

is there a way in my template that I can access the display text ie, English ?

Body:
If you have LANGUAGE_CODE you can use language_name filter:

{{ LANGUAGE_CODE|language_name }}

(and many other possibilities: django template translation-specific variables)

In django < v1.3:

You can access available languages list via:

{% get_available_languages as LANGUAGES %}

To show this ist:

{% for lang in LANGUAGES %}
 CODE:{{ lang.0 }}, NAME:{{ lang.1 }}
{% endfor %}

As you can see language name is lang.1 (second member of the inner tuple)

If you want the name of a language that you have it's code, either put that in the context before passing it to the template or in the loop above add a comparaison condition to get the name.


问:
Window.Print Doesn't Work in Android WebView (API 23) but Works in default Browser and Chrome
The following example code from here works fine in both the default browser "Internet" and "Chrome" browser on Galaxy Tab S2.

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button to print the current page.</p>

<button onclick="myFunction()">Print this page</button>

<script>
function myFunction() {
    window.print();
}
</script>

</body>
</html>
</code>```

However when hosted inside a WebView, nothing happens when clicking "Print this page"

My view XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.MainActivity"
    tools:showIn="@layout/activity_main">

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

MainActivity.Java has the following:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    WebViewClient mWebClient = new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    };
    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(mWebClient);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setGeolocationEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    myWebView.loadUrl("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_print");
}
</code>```

The WebView developer documentation here explicitly calls out:

You cannot use JavaScript in a HTML document to trigger printing.

How can I host a webpage and allow JavaScript printing to work.

Alternatives I've thought of but haven't found a way to implement:

Intercept button clicks, if Print button is been clicked trigger my own printing code

Replace the "Print" button HTML on the fly with some other code that would allow me to handle it in my application

So far to workaround this limitation I've added "Print" button to my application and run my own printing code. It works fine, but is confusing user experience as "Print" button in web page does nothing.

答:
Maybe this will answer to your question:
https://bugs.chromium.org/p/chromium/issues/detail?id=322303

This is the answer from Android WebView team:

Hi,

We (Android WebView team) are planning to port this API to Android Q
  (lower versions are possible too via support lib, but TBD). We want to
  understand the possible use cases of it.

The API will be a blocking callback as we want to freeze the
  DOM/layout tree for printing rendering, this is the same behavior with
  Chrome.

Once we have the callback, we can imagine to get a
  |PrintDocumentAdapter| from WebView#getPrintDocumentAdapter() in the
  callback, and apps can either 1) use the |PrintDocumentAdapter| with
  |PrintManager| to let user choose printing settings or 2) use it to
  generate a PDF file directly. We probably want to unblock when
  PrintDocumentAdapter#onFinish() get called.

This callback will only benefit the case that when loading contents
  you have no control to WebView, the app still needs to support
  printing feature. Otherwise the app can use |PrintDocumentAdapter|
  directly.

We also want to know if you think window.print() from an iframe (to
  print only content in that iframe) is important for you or not.
  Supporting of this is tentative as there is no obvious way for
  getPrintDocumentAdapter() to know the current window.print() is from
  main frame or an iframe.

Questions, thoughts? Please give your feedback, thanks!

Body:
The following example code from here works fine in both the default browser "Internet" and "Chrome" browser on Galaxy Tab S2.

<!DOCTYPE html>

Click the button to print the current page.

<button onclick="myFunction()">Print this page</button>

However when hosted inside a WebView, nothing happens when clicking "Print this page"

My view XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.MainActivity"
    tools:showIn="@layout/activity_main">

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.Java has the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    WebViewClient mWebClient = new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    };
    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(mWebClient);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setGeolocationEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    myWebView.loadUrl("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_print");
}

The WebView developer documentation here explicitly calls out:

You cannot use JavaScript in a HTML document to trigger printing.

How can I host a webpage and allow JavaScript printing to work.

Alternatives I've thought of but haven't found a way to implement:

Intercept button clicks, if Print button is been clicked trigger my own printing code

Replace the "Print" button HTML on the fly with some other code that would allow me to handle it in my application

So far to workaround this limitation I've added "Print" button to my application and run my own printing code. It works fine, but is confusing user experience as "Print" button in web page does nothing.


问:
Extracting numerical data from string
I have text data in a csv file in this format:

76.76% @ 26.2° C D: 20.7° C G/KG: 15.5

Date,Value,Formatted Value

2019-10-11 14:50:00,71.19,71.19% @ 24.4° C D: 17.7° C G/KG: 12.8

2019-10-11 15:00:00,72.2,72.2% @ 24.4° C D: 17.9° C G/KG: 13

2019-10-11 15:10:00,71.35,71.35% @ 24.4° C D: 17.8° C G/KG: 12.9

I would like to extract the each numerical data and store it in a different column. The numbers don't always contain a decimal place though.

Edit: The data is from a csv file and I would like to store each numerical data in a different column.

答:
You can use regex here.

```<code>import re
a='76.76% @ 26.2° C D: 20.7° C G/KG: 15.5 75' #I added 75 just to show it caputres ints and floats.
nums=re.findall(r'\d+\.\d+|\d+',a)
print(nums)
#['76.76', '26.2', '20.7', '15.5', '75']
</code>```

Title: Extracting numerical data from string

Body:
You can use regex here.

import re
a='76.76% @ 26.2° C D: 20.7° C G/KG: 15.5 75' #I added 75 just to show it caputres ints and floats.
nums=re.findall(r'\d+\.\d+|\d+',a)
print(nums)
#['76.76', '26.2', '20.7', '15.5', '75']


问:
Need help writing test case for below .subscribe in Angular
```<code>            ngOnInit{
            .subscribe( (name: Name) => {
            if(!name){
                this.close
            } else {
                this.name = Name
            }
            })
            }
</code>```

I need help writing test cases so that it covers this.name=Name in code coverage. Thanks.

答:
If you just want to test the function handling new events you could extract it:

```<code>const onNewName = (name: Name) => {
  if(!name) {
    this.close();
  } else {
    this.name = name;
  }
};

<observable>.subscribe(onNewName);
</code>```

Then you should be able to test it fairly isolated without mocking the observable.
You still reference this in your function so you have to setup the component properly for testing.

Body:
            ngOnInit{
            .subscribe( (name: Name) => {
            if(!name){
                this.close
            } else {
                this.name = Name
            }
            })
            }

I need help writing test cases so that it covers this.name=Name in code coverage. Thanks.

Body:
If you just want to test the function handling new events you could extract it:

const onNewName = (name: Name) => {
  if(!name) {
    this.close();
  } else {
    this.name = name;
  }
};

<observable>.subscribe(onNewName);

Then you should be able to test it fairly isolated without mocking the observable.
You still reference this in your function so you have to setup the component properly for testing.


问:
Laravel - Number with 4 decimals
I want to store 1 number with 4 decimals, in my database.

If i use float i can add only 2 decimals

```<code>$table->float('sell');
</code>```

If I try with decimal i get an error

```<code>$table->decimal('sell', 1, 4);
</code>```

The first number must be greater than or equal to the second number.

```<code>SQLSTATE[42000]: Syntax error or access violation: 1427 For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column '
</code>```

sell'). (SQL: create table customers (id int unsigned not null auto_increment primary key, sell decimal(1, 4) not null,

   created_at timestamp null, updated_at timestamp null) default character set utf8 collate utf8_unicode_ci)

Any help?

Thanks

答:
In your schema file.

```<code> $table->decimal('your_field_name', 13, 4);
</code>```

your_field_name = Database field name.

13 = Total number of digit. Example- $99,999,999,999.99

4 = value after decimal. Example - $999,999,999.9999

Title: Laravel - Number with 4 decimals

Body:
I want to store 1 number with 4 decimals, in my database.

If i use float i can add only 2 decimals

$table->float('sell');

If I try with decimal i get an error

$table->decimal('sell', 1, 4);

The first number must be greater than or equal to the second number.

SQLSTATE[42000]: Syntax error or access violation: 1427 For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column '

sell'). (SQL: create table customers (id int unsigned not null auto_increment primary key, sell decimal(1, 4) not null,

   created_at timestamp null, updated_at timestamp null) default character set utf8 collate utf8_unicode_ci)

Any help?

Thanks

Body:
In your schema file.

 $table->decimal('your_field_name', 13, 4);

your_field_name = Database field name.

13 = Total number of digit. Example- $99,999,999,999.99

4 = value after decimal. Example - $999,999,999.9999


问:
How to create HTML element for JavaScript and not for HTML
I have this simplified code:

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = (document.createElement("input").value =
            chancesData[index]);
          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);
  ```
</div>
</div>
</p>

<p>as you can see if you opened this coed in your console, the returned array looks like this:</p>

```['facebook', 'twiiter', 'google']
```

<p>I want it to look like this:</p>

```['<input value="facebook">','<input value="twitter">','<input value="google">']
```

答:
Please refer below code.

(function createHTMlString() {
  const chancesData = ["facebook", "twitter", "google"];
  var outputObj = []
  for (var i = 0; i < chancesData.length; i++) {
  var inputTag = document.createElement("INPUT");
    inputTag.setAttribute("value", chancesData[i]);
    outputObj.push(inputTag);
  }
  console.log(outputObj)
})();```

Body:
I have this simplified code:

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = (document.createElement("input").value =
            chancesData[index]);
          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);

as you can see if you opened this coed in your console, the returned array looks like this:

['facebook', 'twiiter', 'google']

I want it to look like this:

['<input value="facebook">','<input value="twitter">','<input value="google">']


问:
Rust OR between two options
I want to know if its possible to perform an OR operation between two Options. Something like :

```<code>let a = Some(3);
let b = None;
let result = a || b;
</code>```

Here I want the result variable to have either the value of a if it's a Some or the value of b.

I didn't find any documentation of this on Internet.

答:
In Rust operands of  Logical OR (||) must be bool. So it is not possible to use it with Option or any other type.

But please see the or method from the documentation of Option.

Returns the option if it contains a value, otherwise returns optb.

Your problem can be solved like this:

let a = Some(3);
let b = None;
let result = a.or(b); // result: Some(3)
```

<p>If you want result as a <code>bool</code> you can use <code>is_some</code> or <code>is_none</code></p>

<pre class="lang-rust prettyprint-override"><code>let result = a.or(b).is_some(); // true
let result = None.or(None).is_some(); // false
</code>```

OR_ELSE

Arguments passed to or are eagerly evaluated; if you are passing the
  result of a function call, it is recommended to use or_else, which is
  lazily evaluated.

You can also use or_else in a situation like this :

let a = Some(3);
let result = a.or(produce_option());
```

<p>As you can see from the code whether your <code>a</code> is <code>Some</code> or <code>None</code> it will run <code>produce_option</code>, this may not be efficient in some(or many) circumstances. </p>

<pre class="lang-rust prettyprint-override"><code>let result = a.or_else(produce_option);
</code>```

In here produce_option will only be called when a is None

AND

For Logical AND (&&) you can use and method of Option.

let a = None;
let b = Some(4);
let result = a.and(b); // result: None
```

<p>For a lazy evaluation you can use <strong>AND_THEN</strong> like <code>OR_ELSE</code>. </p>

<hr>

<p><strong>UNWRAP_OR</strong> </p>

<p><code>unwrap_or</code> or <code>unwrap_or_else</code> is also usable if you want to take the value inside the options while comparing. But this depends on the case, i am writing this as an example: </p>

<pre class="lang-rust prettyprint-override"><code>let a = None;
let b = None;
let x:i32 = a.unwrap_or(b.unwrap_or_default()); //Since `i32`'s default value is 0 `x` will be equal to 0

let a = None;
let b = Some(3);
let x:i32 = a.unwrap_or_else(||b.unwrap_or_default()); // `x` will be eqaul to 3
//using `unwrap_or_else` might be a better idea, because of the lazy evaluation.
</code>```

Note : This answer focused on Option but these are all applicable for Result objects which have same error type.

Title: Rust OR between two options

Body:
I want to know if its possible to perform an OR operation between two Options. Something like :

let a = Some(3);
let b = None;
let result = a || b;

Here I want the result variable to have either the value of a if it's a Some or the value of b.

I didn't find any documentation of this on Internet.

Body:
In Rust operands of  Logical OR (||) must be bool. So it is not possible to use it with Option or any other type.

But please see the or method from the documentation of Option.

Returns the option if it contains a value, otherwise returns optb.

Your problem can be solved like this:

let a = Some(3);
let b = None;
let result = a.or(b); // result: Some(3)

If you want result as a bool you can use is_some or is_none

let result = a.or(b).is_some(); // true
let result = None.or(None).is_some(); // false

OR_ELSE

Arguments passed to or are eagerly evaluated; if you are passing the
  result of a function call, it is recommended to use or_else, which is
  lazily evaluated.

You can also use or_else in a situation like this :

let a = Some(3);
let result = a.or(produce_option());

As you can see from the code whether your a is Some or None it will run produce_option, this may not be efficient in some(or many) circumstances.

let result = a.or_else(produce_option);

In here produce_option will only be called when a is None

AND

For Logical AND (&&) you can use and method of Option.

let a = None;
let b = Some(4);
let result = a.and(b); // result: None

For a lazy evaluation you can use AND_THEN like OR_ELSE.

UNWRAP_OR

unwrap_or or unwrap_or_else is also usable if you want to take the value inside the options while comparing. But this depends on the case, i am writing this as an example:

let a = None;
let b = None;
let x:i32 = a.unwrap_or(b.unwrap_or_default()); //Since `i32`'s default value is 0 `x` will be equal to 0

let a = None;
let b = Some(3);
let x:i32 = a.unwrap_or_else(||b.unwrap_or_default()); // `x` will be eqaul to 3
//using `unwrap_or_else` might be a better idea, because of the lazy evaluation.

Note : This answer focused on Option but these are all applicable for Result objects which have same error type.


问:
gRPC - Unary Call C#
I am trying to learn gRPC by making a simple project server/client which the client send 2 Int Variable and the server will responed with a string and the 2 variable that the client sent
The Protocol Buffer code is :

```<code>syntax = "proto3";
option  csharp_namespace = "MapPB";

service MapRoute {

    rpc Gps(Location) returns (LocationName) {}
}

message Location {

    int32 la = 1;
    int32 lo = 2;
}

message LocationName {

    string Name = 1;
}
</code>```

Server

```<code>using Grpc.Core;
using static MapPB.MapRoute;
using MapPB;

namespace gServer
{
    public class gS : MapRouteBase
    {
        public override async Task<LocationName> Gps(Location request, ServerCallContext context)
        {

            return await base.Gps(new LocationName { Name = "Your Location is " + request.La + ":" + request.Lo } );

        }

    }
    class Program
    {
        const int Port = 50051;
        static void Main(string[] args)
        {

            Server server = new Server
            {
                Services = { MapRoute.BindService(new gS()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine("Map server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();

        }
    }
}
</code>```

Client

```<code>using Grpc.Core;
using Map;
using static MapPB.MapRoute;

namespace Map
{
    class Program : MapRouteClient
    {

        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:50021", ChannelCredentials.Insecure);

            var client = new MapRouteClient(channel);

            int la = 1;
            int lo = 2;

            var reply = client.Gps(new MapPB.Location { La = la , Lo = lo });

            Console.WriteLine(reply.Name);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

        }
    }
}
</code>```

Am getting an red squiggle  at the server code under .Gps

There is no argument given that corresponds to the required formal parameter 'context' of 'MapRoute.MapRouteBase.Gps(Location, ServerCallContext)'

I tried to add context to the parameter  but I got another error

cannot convert from 'MapPB.LocationName' to 'MapPB.Location'

can someone explain what wrong am doing Please ?

答:
As an update on Matthias247's answer, I would prefer to see it like this (even tho his answer is also correct):

```<code>public override Task<LocationName> Gps(Location request, ServerCallContext context)
    {
        return Task.FromResult(new LocationName
        {
            Name = "Your Location is " + request.La + ":" + request.Lo
        });
    }
</code>```

And change your client to async:

```<code>static async Task Main(string[] args)
    {
        Channel channel = new Channel("127.0.0.1:50021", ChannelCredentials.Insecure);

        var client = new MapRouteClient(channel);

        int la = 1;
        int lo = 2;

        var reply = await client.GpsAsync(new MapPB.Location { La = la , Lo = lo });

        Console.WriteLine(reply.Name);

        channel.ShutdownAsync().Wait();
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

    }
</code>```

Title: gRPC - Unary Call C#

Body:
I am trying to learn gRPC by making a simple project server/client which the client send 2 Int Variable and the server will responed with a string and the 2 variable that the client sent
The Protocol Buffer code is :

syntax = "proto3";
option  csharp_namespace = "MapPB";

service MapRoute {

    rpc Gps(Location) returns (LocationName) {}
}

message Location {

    int32 la = 1;
    int32 lo = 2;
}

message LocationName {

    string Name = 1;
}

Server

using Grpc.Core;
using static MapPB.MapRoute;
using MapPB;

namespace gServer
{
    public class gS : MapRouteBase
    {
        public override async Task<LocationName> Gps(Location request, ServerCallContext context)
        {

            return await base.Gps(new LocationName { Name = "Your Location is " + request.La + ":" + request.Lo } );

        }

    }
    class Program
    {
        const int Port = 50051;
        static void Main(string[] args)
        {

            Server server = new Server
            {
                Services = { MapRoute.BindService(new gS()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine("Map server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();

        }
    }
}

Client

using Grpc.Core;
using Map;
using static MapPB.MapRoute;

namespace Map
{
    class Program : MapRouteClient
    {

        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:50021", ChannelCredentials.Insecure);

            var client = new MapRouteClient(channel);

            int la = 1;
            int lo = 2;

            var reply = client.Gps(new MapPB.Location { La = la , Lo = lo });

            Console.WriteLine(reply.Name);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

        }
    }
}

Am getting an red squiggle  at the server code under .Gps

There is no argument given that corresponds to the required formal parameter 'context' of 'MapRoute.MapRouteBase.Gps(Location, ServerCallContext)'

I tried to add context to the parameter  but I got another error

cannot convert from 'MapPB.LocationName' to 'MapPB.Location'

can someone explain what wrong am doing Please ?

Body:
As an update on Matthias247's answer, I would prefer to see it like this (even tho his answer is also correct):

public override Task<LocationName> Gps(Location request, ServerCallContext context)
    {
        return Task.FromResult(new LocationName
        {
            Name = "Your Location is " + request.La + ":" + request.Lo
        });
    }

And change your client to async:

static async Task Main(string[] args)
    {
        Channel channel = new Channel("127.0.0.1:50021", ChannelCredentials.Insecure);

        var client = new MapRouteClient(channel);

        int la = 1;
        int lo = 2;

        var reply = await client.GpsAsync(new MapPB.Location { La = la , Lo = lo });

        Console.WriteLine(reply.Name);

        channel.ShutdownAsync().Wait();
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

    }


问:
Select value from different row based on value of certain column
For example I have data like this like this

```<code>    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   null    |   a
 20022   |   2    |   a     |   null    |   a
 20023   |   3    |   a     |   null    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b
</code>```

what I need is when value in Col_3 is null and Col_1 is not 4,
then select value in Col_3 where Col_1 = 4, that have the same

I tried using this case statement:

```<code>select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 1
     then (select col_3 from table s where s.date = 4
           and s.col_1= seg.col_1 and s.col_4= seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3
  end as col_3
from table seg
</code>```

but for some reason it's not doing what I need it to do
I need it to change the results of the table above to become like this:

```<code>    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   4.5    |   a
 20022   |   2    |   a     |   4.5    |   a
 20023   |   3    |   a     |   4.5    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b
</code>```

答:
Just use window functions and coalesce():

```<code>select date, col1, col2,
       coalesce(max(case when col1 = 4 then col3 end) over (partition by col4) as col3,
       col4
from t;
</code>```

Body:
For example I have data like this like this

    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   null    |   a
 20022   |   2    |   a     |   null    |   a
 20023   |   3    |   a     |   null    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b

what I need is when value in Col_3 is null and Col_1 is not 4,
then select value in Col_3 where Col_1 = 4, that have the same

I tried using this case statement:

select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 1
     then (select col_3 from table s where s.date = 4
           and s.col_1= seg.col_1 and s.col_4= seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3
  end as col_3
from table seg

but for some reason it's not doing what I need it to do
I need it to change the results of the table above to become like this:

    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   4.5    |   a
 20022   |   2    |   a     |   4.5    |   a
 20023   |   3    |   a     |   4.5    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b

Body:
Just use window functions and coalesce():

select date, col1, col2,
       coalesce(max(case when col1 = 4 then col3 end) over (partition by col4) as col3,
       col4
from t;


问:
Is this Quick Sort Logic Correct?
I have tried to implement Quick-Sort in Javascript without any reference to psuedo Code. Is this correct implementation? if not how can i improve on it.

const quickSort = (arr = []) => {
  const length = arr.length;
  if (length === 0 || length === 1) {
    return arr;
  }

  const pivot = arr[0];
  const leftArray = [];
  const rightArray = [];
  for (let i = 1; i < length; i++) {
    if (arr[i] < pivot) {
      leftArray.push(arr[i]);
    } else {
      rightArray.push(arr[i]);
    }
  }
  return [...quickSort(leftArray), pivot, ...quickSort(rightArray)];
};

console.log(quickSort([2, 45, 6, 7, 8, 1]));```
</div>
</div>
</p>

<p>I have added code of test case and executed it over 250000 times.</p>

```// Function to generate random array.
const generateRandomArray = n =>
  Array.from({
    length: n
  }, () => Math.floor(Math.random() * n));

// Function to check whether array is sorted.
const checkSorted = (arr = []) => {
  let sorted = true;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < arr[i - 1]) {
      sorted = false;
      break;
    }
  }
  return sorted;
};

// Testing Quick-Sort
const testQuickSort = () => {
  for (let i = 1; true; i++) {
    const sortedArray = quickSort(generateRandomArray(Date.now() % 100000));
    const isSorted = checkSorted(sortedArray);
    if (!isSorted) {
      console.log("error");
      break;
    }
    console.log("pass", i);
  }
};

testQuickSort();
```

答:
You can try the following Solution

function pivot(arr, start = 0, end = arr.length - 1) {
  const swap = (arr, idx1, idx2) => {
    [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
  };

  // We are assuming the pivot is always the first element
  let pivot = arr[start];
  let swapIdx = start;

  for (let i = start + 1; i <= end; i++) {
    if (pivot > arr[i]) {
      swapIdx++;
      swap(arr, swapIdx, i);
    }
  }

  // Swap the pivot from the start the swapPoint
  swap(arr, start, swapIdx);
  return swapIdx;
}

function quickSort(arr, left = 0, right = arr.length -1){
    if(left < right){
        let pivotIndex = pivot(arr, left, right) //3
        //left
        quickSort(arr,left,pivotIndex-1);
        //right
        quickSort(arr,pivotIndex+1,right);
      }
     return arr;
}

console.log(quickSort([100,-3,2,4,6,9,1,2,5,3,23]));```

Title: Is this Quick Sort Logic Correct?

Body:
I have tried to implement Quick-Sort in Javascript without any reference to psuedo Code. Is this correct implementation? if not how can i improve on it.

const quickSort = (arr = []) => {
  const length = arr.length;
  if (length === 0 || length === 1) {
    return arr;
  }

  const pivot = arr[0];
  const leftArray = [];
  const rightArray = [];
  for (let i = 1; i < length; i++) {
    if (arr[i] < pivot) {
      leftArray.push(arr[i]);
    } else {
      rightArray.push(arr[i]);
    }
  }
  return [...quickSort(leftArray), pivot, ...quickSort(rightArray)];
};

console.log(quickSort([2, 45, 6, 7, 8, 1]));

I have added code of test case and executed it over 250000 times.

// Function to generate random array.
const generateRandomArray = n =>
  Array.from({
    length: n
  }, () => Math.floor(Math.random() * n));

// Function to check whether array is sorted.
const checkSorted = (arr = []) => {
  let sorted = true;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < arr[i - 1]) {
      sorted = false;
      break;
    }
  }
  return sorted;
};

// Testing Quick-Sort
const testQuickSort = () => {
  for (let i = 1; true; i++) {
    const sortedArray = quickSort(generateRandomArray(Date.now() % 100000));
    const isSorted = checkSorted(sortedArray);
    if (!isSorted) {
      console.log("error");
      break;
    }
    console.log("pass", i);
  }
};

testQuickSort();


问:
No references were found in the windows sdk (Windows 1903)
I want to create simple toast notification to action center in windows 10 from a WPF app using this article.

But I got problem on Step 2:

Right click on the project => Add => Reference... => Windows => Core

What I checked:

Windows 10 SDK Installation:

Same issue with a WPF project

And this is my csproj file:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{A5A389ED-4BBB-4EF4-A8A4-45DD3D0AF9AE}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <RootNamespace>WpfApp3</RootNamespace>
    <AssemblyName>WpfApp3</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <TargetPlatformVersion>10.0.10240.0</TargetPlatformVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <Deterministic>true</Deterministic>
    <TargetFrameworkProfile />
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
  </ItemGroup>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
```

This error occurs after the update to Windows 1903, because Visual studio can not access C:\Windows\System32\WinMetadata

答:
Windows 1903:

Copy WinMetadata folder from (hidden folder) C:\WINDOWS\sysnative\WinMetadata to C:\WINDOWS\SysWOW64\WinMetadata.

Re-open reference manager.

Body:
I want to create simple toast notification to action center in windows 10 from a WPF app using this article.

But I got problem on Step 2:

Right click on the project => Add => Reference... => Windows => Core

What I checked:

Windows 10 SDK Installation:

Same issue with a WPF project

And this is my csproj file:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{A5A389ED-4BBB-4EF4-A8A4-45DD3D0AF9AE}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <RootNamespace>WpfApp3</RootNamespace>
    <AssemblyName>WpfApp3</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <TargetPlatformVersion>10.0.10240.0</TargetPlatformVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <Deterministic>true</Deterministic>
    <TargetFrameworkProfile />
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
  </ItemGroup>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

This error occurs after the update to Windows 1903, because Visual studio can not access C:\Windows\System32\WinMetadata


问:
Custom Convolution in tensorflow
Lets assume i want to change the core of the Convolution, so that the kernel weigths change, based on the on the the incoming value in the middle of my kernel. How can i write such a layer in tensorflow ?

```<code> Kernel -> Image

|a b c|    |2 3 2|
|d e f| -> |5 4 5|
|g h i|    |5 3 1|

----> because e would be 4, if both were overlapping, the other wheigths should change like f(x):

f(x)=x*wheigt

|4a 4b 4c|
|4d e  4f|
|4g 4h 4i|
</code>```

So atleast, change all wheigths out of the middle one like f(x).

答:
If I understand correctly, I think this does what you want (TF 2.x, but would be the same in 1.x):

import tensorflow as tf

# Input data
kernel = tf.constant([[1., 2., 3.],
                      [4., 5., 6.],
                      [7., 8., 9.]], dtype=tf.float32)
img = tf.reshape(tf.range(90, dtype=tf.float32), [1, 5, 6, 3])
# Do separable convolution
kernel_t = tf.tile(kernel[:, :, tf.newaxis, tf.newaxis], [1, 1, 3, 1])
eye = tf.eye(3, 3, batch_shape=[1, 1])  # Pointwise filter does nothing
conv = tf.nn.separable_conv2d(img, kernel_t, eye, strides=[1, 1, 1, 1], padding='SAME')
# Scale convolution result and subtract the scaling for the central value
result = conv * img - kernel[1, 1] * img * (img - 1)

# Check result
kernel_np = kernel.numpy()
img_np = img.numpy()
result_np = result.numpy()
# Coordinates of checked result
i, j, c = 3, 4, 1
# Image value
v = img_np[0, i, j, c]
# Image window aroud value
img_w = img_np[0, i - 1:i + 2, j - 1:j + 2, c]
# Kernel scaled by image value except at center
kernel_scaled = kernel_np * v
kernel_scaled[1, 1] = kernel_np[1, 1]
# Compute output value
val_test = (img_w * kernel_scaled).sum()
# Check against TF calculation
val_result = result_np[0, i, j, c]
print(val_test == val_result)
# True
```

Title: Custom Convolution in tensorflow

Body:
Lets assume i want to change the core of the Convolution, so that the kernel weigths change, based on the on the the incoming value in the middle of my kernel. How can i write such a layer in tensorflow ?

 Kernel -> Image

|a b c|    |2 3 2|
|d e f| -> |5 4 5|
|g h i|    |5 3 1|

----> because e would be 4, if both were overlapping, the other wheigths should change like f(x):

f(x)=x*wheigt

|4a 4b 4c|
|4d e  4f|
|4g 4h 4i|

So atleast, change all wheigths out of the middle one like f(x).


问:
How to select specific columns from lots of dataframes in r
I am handling 303 data frames and each data frame has different name as well as contains different columns. What I want is that select specific columns of which name contain "_CD" and "_NM" from those lots of data frames. Is there any good way to deal with it?

Note, those data frames were not listed.

Here is an example (I cannot bring up the real data but show you the fake with similar format)

table 1 name: AD_ITEM_CNT;

columns : CKND_CLSF_CD, SUBJ_CD, ITEM_CNT, UPDT_DT

table 2 name : BLAD_PE_XEXM

columns : PT_SBST_NO, CEXM_NM, CEXM_CD, CEXM_RST, CEX_RSLT_CMNT, LDNG_DT

table 3 name : BLAD_MR_HLTH

columns : PT_SBST_NO, RGST_DT, EDU_DGRE_CD, DRNK_YN, JOB_KIND_CD ...

The goal of this process is to create a table like the below

```<code>Table          |       column |  CD
-----------------------------------
AD_ITEM_CNT    | CKND_CLSF_CD |  01
AD_ITEM_CNT    | CKND_CLSF_CD |  02
AD_ITEM_CNT    | CKND_CLSF_CD |  03
AD_ITEM_CNT    | CKND_CLSF_CD |  04
BLAD_PE_XEXM   | CEXM_CD      |  AVS
BLAD_PE_XEXM   | CEXM_CD      |  ABE
BLAD_PE_XEXM   | CEXM_CD      |  CVS
BLAD_PE_XEXM   | CEXM_CD      |  UVS
</code>```

答:
As @r2evans said, I more than encourage you to start with loading all your data.frames into one list. However, if you don't have any other option, you can do this:

First, lets create 5 data.frames:

```<code>for (i in 1:5) {

  set.seed(123)
  assign(paste0("y",i), data.frame(A_CD = rnorm(1),
                                   A_NM = rnorm(1),
                                   A_GK = rnorm(1)))

}
</code>```

Next, we can create a list of all of our variables (using ls()) and filter (Filter) for only the data.frames:

```<code>dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
</code>```

Lastly, we can filter the data.frames inside the list for the needed columns (have CD and NM in them):

```<code>dfs <- lapply(dfs, function(x) x[, grepl("CD|NM", names(x)), drop=FALSE])
</code>```

Output:

```<code>dfs

$y1
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y2
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y3
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y4
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y5
        A_CD       A_NM
1 -0.5604756 -0.2301775
</code>```

Body:
I am handling 303 data frames and each data frame has different name as well as contains different columns. What I want is that select specific columns of which name contain "_CD" and "_NM" from those lots of data frames. Is there any good way to deal with it?

Note, those data frames were not listed.

Here is an example (I cannot bring up the real data but show you the fake with similar format)

table 1 name: AD_ITEM_CNT;

columns : CKND_CLSF_CD, SUBJ_CD, ITEM_CNT, UPDT_DT

table 2 name : BLAD_PE_XEXM

columns : PT_SBST_NO, CEXM_NM, CEXM_CD, CEXM_RST, CEX_RSLT_CMNT, LDNG_DT

table 3 name : BLAD_MR_HLTH

columns : PT_SBST_NO, RGST_DT, EDU_DGRE_CD, DRNK_YN, JOB_KIND_CD ...

The goal of this process is to create a table like the below

Table          |       column |  CD
-----------------------------------
AD_ITEM_CNT    | CKND_CLSF_CD |  01
AD_ITEM_CNT    | CKND_CLSF_CD |  02
AD_ITEM_CNT    | CKND_CLSF_CD |  03
AD_ITEM_CNT    | CKND_CLSF_CD |  04
BLAD_PE_XEXM   | CEXM_CD      |  AVS
BLAD_PE_XEXM   | CEXM_CD      |  ABE
BLAD_PE_XEXM   | CEXM_CD      |  CVS
BLAD_PE_XEXM   | CEXM_CD      |  UVS

Body:
As @r2evans said, I more than encourage you to start with loading all your data.frames into one list. However, if you don't have any other option, you can do this:

First, lets create 5 data.frames:

for (i in 1:5) {

  set.seed(123)
  assign(paste0("y",i), data.frame(A_CD = rnorm(1),
                                   A_NM = rnorm(1),
                                   A_GK = rnorm(1)))

}

Next, we can create a list of all of our variables (using ls()) and filter (Filter) for only the data.frames:

dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))

Lastly, we can filter the data.frames inside the list for the needed columns (have CD and NM in them):

dfs <- lapply(dfs, function(x) x[, grepl("CD|NM", names(x)), drop=FALSE])

Output:

dfs

$y1
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y2
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y3
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y4
        A_CD       A_NM
1 -0.5604756 -0.2301775

$y5
        A_CD       A_NM
1 -0.5604756 -0.2301775


问:
Can someone help me with this linked list? C++
I have an object oriented exam tomorrow and I'm still stuck with linked lists. For some reason I cant quite understand how they work or how to implement them properly. I've watched a lot of videos and tutorials but it still is quite complex. I always get an error which prints nothing to the console, just a blank black page. Can someone tell em what am I doing wrong?
Thank you.</p>

```<code>#include <iostream>
#include <string>

using namespace std;

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;

class Employees
{
private:
    node* head, * tail;
public:
    Employees()
    {
        head = NULL;
        tail = NULL;
    }
    void addToList(string Name, int Num)
    {
        node* n = new node;
        n->name = Name;
        n->number = Num;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }
    void PrintAll()
    {
        while (head != NULL)
        {
            node* current;
            while (current != NULL)
            {
                cout << current->name << "\t";
                cout << current->number;
            }
        }
    }
};

int main()
{
    Employees a;
    a.addToList("Robert", 54);
    a.addToList("Manny", 77);

    a.PrintAll();

}
</code>```

答:
You have issue with

PrintAll where Head is unaltered and makes it infinite loop.

current is uninitialised and accessing it as a pointer is UB

Below snippet shoud fix your problem,

```<code>void PrintAll()
{
    node* temp = head;
    while (temp != nullptr)
    {
       std::cout << temp ->name << "\t";
       std::cout << temp ->number;
       temp = temp->next
    }
}
</code>```

Body:
I have an object oriented exam tomorrow and I'm still stuck with linked lists. For some reason I cant quite understand how they work or how to implement them properly. I've watched a lot of videos and tutorials but it still is quite complex. I always get an error which prints nothing to the console, just a blank black page. Can someone tell em what am I doing wrong?
Thank you.

#include <iostream>
#include <string>

using namespace std;

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;

class Employees
{
private:
    node* head, * tail;
public:
    Employees()
    {
        head = NULL;
        tail = NULL;
    }
    void addToList(string Name, int Num)
    {
        node* n = new node;
        n->name = Name;
        n->number = Num;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }
    void PrintAll()
    {
        while (head != NULL)
        {
            node* current;
            while (current != NULL)
            {
                cout << current->name << "\t";
                cout << current->number;
            }
        }
    }
};

int main()
{
    Employees a;
    a.addToList("Robert", 54);
    a.addToList("Manny", 77);

    a.PrintAll();

}

Body:
You have issue with

PrintAll where Head is unaltered and makes it infinite loop.

current is uninitialised and accessing it as a pointer is UB

Below snippet shoud fix your problem,

void PrintAll()
{
    node* temp = head;
    while (temp != nullptr)
    {
       std::cout << temp ->name << "\t";
       std::cout << temp ->number;
       temp = temp->next
    }
}