问:
error with userDetailsService org.springframework.beans.factory.UnsatisfiedDependencyException
I wrote a lot of code so I can't find exactly the code that generates this error but I have been trying to fix it for days without success. This is an error concerning the userDetailsService that I have implemented on userService, the user entity class implements UserDetails and serializable. Please I need help.

the User entity class

```<code>@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User implements UserDetails, Serializable{

  @Id
  private String matricule;

  private String password;

  private String username;

  private String codeExploitant;

  private Boolean activated;

  @Column(nullable=true)
  private String createdBy;

   @OneToMany(mappedBy="user", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
   private List<UserCaisse> caisses;

   public void addCaisse(Caisse caisse) {
       //recupereration de la date systeme
       LocalDateTime dateTime = LocalDateTime.now();

          UserCaisse userCaisse = new UserCaisse(this, caisse);
          userCaisse.setDate(dateTime);
          caisses.add(userCaisse);
          caisse.getUsers().add(userCaisse);
      }

   public void removeCaisse(Caisse caisse) {
          for (Iterator<UserCaisse> iterator = caisses.iterator();
               iterator.hasNext(); ) {
              UserCaisse userCaisse = iterator.next();

              if (userCaisse.getUser().equals(this) &&
                      userCaisse.getCaisse().equals(caisse)) {
                  iterator.remove();
                  userCaisse.getCaisse().getUsers().remove(userCaisse);
                  userCaisse.setUser(null);
                  userCaisse.setCaisse(null);
              }
          }
   }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
      return null;
  }

  @Override
  public boolean isAccountNonExpired() {
      return false;
  }

  @Override
  public boolean isAccountNonLocked() {
      return false;
  }

  @Override
  public boolean isCredentialsNonExpired() {
      return false;
  }

  @Override
  public boolean isEnabled() {
      return false;
  }
}
</code>```

the UserService class

```<code>@Service
@Slf4j
public class UserService implements UserDetailsService{

    private final IUser userRepository;

    private final ICaisse caisseRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    private User user;

    @Autowired
    public UserService(IUser userRepository, ICaisse caisseRepository) {
        this.userRepository=userRepository;
        this.caisseRepository=caisseRepository;
    }

    //find methods
    public User findById(String matricule) {
        log.info("Selection d'un enregistrement de user a partir du matricule {} effectué avec succès", matricule);
        return userRepository.findById(matricule).orElse(new User());
    }

    public List<User> find(String username) {
        log.info("Selection d'une liste d'enregistrement de user a partir de username effectué avec succès");
        return userRepository.findByUsername(username);
    }

    public List<User> find(){
        List<User> lstUser=userRepository.findAll();

        try {
            lstUser.forEach(item->{
                item.setPassword(null);
            });

            log.info("Selection de tous les users effectué avec succès");
        } catch (Exception e) {
            log.error("Erreur lors de la selection de tous les users {}",e.getMessage());
            System.err.println("Erreur lors de la selection de tous les users "+e.getMessage());
        }

        return lstUser;
    }

    public User getOne(String matricule) {
        log.info("Selection d'un enregistrement de user a partir de matricule: {} effectué avec succès",matricule);
        return userRepository.getOne(matricule);
    }

    //Delete methods
    public boolean delete(String matricule) {
        boolean success=false;

        try {
            if(!StringUtils.isEmpty(matricule)) {
                user=userRepository.findById(matricule).orElse(new User());
                userRepository.deleteById(user.getMatricule());
                success=true;
            }

            log.info("Suppression de l'utilisateur de matricule {} effectuée avec succès",matricule);
        } catch (Exception e) {
            log.error("Erreur survenu lors de la suppression de l'enregistrement {} erreur:{}",matricule,e.getMessage());
            System.err.println("Erreur survenu lors de la suppression de l'enregistrement "+matricule+" "+e.getMessage());
        }

        return success;
    }

    public List<Caisse> getCaisseByUser(String matricule){
        List<Caisse> caisses=caisseRepository.findAll();
        User user=userRepository.findById(matricule).orElse(new User());
        List<Caisse> lstCaisses=new ArrayList<Caisse>();

        try {
            List<UserCaisse> uc=user.getCaisses();

            caisses.forEach(item->{
                uc.forEach(data->{
                    if(item.getIdCaisse().equals(data.getId().getIdCaisse())) {
                        lstCaisses.add(item);
                    }
                });
            });

            log.info("Recuperation d'une liste de caisse selon l'utlisateur {} effectué avec succès",matricule);
        } catch (Exception e) {
            log.error("Erreur lors de la recuperation de la liste de caisse selon l'utilisateur");
            System.err.println("Erreur lors de la recuperation de la liste de caisse selon l'utilisateur "+e.getMessage());
        }

        return lstCaisses;
    }

    //save
    public User save(User user, String mode) {
        User u=new User();

        try {
            if(mode=="create") {
                //cryptage de password
                String passwordEncrypt=passwordEncoder.encode(user.getPassword());
                user.setPassword(passwordEncrypt);
                u=userRepository.save(user);
            }
            else if(mode=="update"){
                if(user.getPassword()==null) {
                    User getUser=userRepository.findById(user.getMatricule()).orElse(new User());
                    user.setPassword(getUser.getPassword());
                }else {
                    user.setPassword(passwordEncoder.encode(user.getPassword()));
                }

                u=userRepository.save(user);
            }else{
                u=userRepository.save(user);
            }

            log.info("Enregistrement de l'utilisateur {} effectué avec succès",u.getMatricule());
        } catch (Exception e) {
            log.error("Erreur survenu lors de l'enregistrement des données de l'utilisateur {}",user.getMatricule());
            System.err.println("Erreur survenu lors de l'enregistrement des données de l'utilisateur "+user.getMatricule());
        }

        return u;
    }

    public boolean verifPassword(String password, String matricule) {
        boolean success=false;

        try {
            User u=userRepository.findById(matricule).orElse(new User());
            success=passwordEncoder.matches(password, u.getPassword());
            log.info("Verification du mot de passe effectué avec succès");
            success=true;
        } catch (Exception e) {
            log.info("Echec de la verification du mot de passe {}",e.getMessage());
            System.err.println("Echec de la verification du mot de passe "+e.getMessage());
            success=false;
        }

        return success;
    }

    //edit methods
    public void editUser(String username, String codeExploitant, String matricule) {
        log.info("Modification de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updateUser(username, codeExploitant, matricule);
    }

    public void editPassword(String password, String matricule) {
        log.info("Modification du mot de passe de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updatePassword(password, matricule);
    }

    public void editEtat(boolean etat, String matricule) {
        log.info("Modification de l'etat de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updateEtatActivated(etat, matricule);
    }

    //Login
    @Override
    public UserDetails loadUserByUsername(String matricule) throws UsernameNotFoundException {

        Objects.requireNonNull(matricule);

        log.info("Chargement des informations de l'utilisateur {} effectué avec succès",matricule );
        User user = userRepository.findUserWithMatricule(matricule)
                .orElseThrow(() -> new UsernameNotFoundException("User non trouvé"));

        return user;
    }

}
</code>```

the WebSecurityConfig class

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandler() {

            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response,
                    AccessDeniedException accessDeniedException) throws IOException, ServletException {
            }
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(new Http403ForbiddenEntryPoint() {
                })
                .and()
                .authenticationProvider(getProvider())
                .formLogin()
                .loginProcessingUrl("/login")
                .passwordParameter("password")
                .usernameParameter("username")
                .successHandler(new AuthentificationLoginSuccessHandler())
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
                .invalidateHttpSession(true)
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/logout").permitAll()
                .antMatchers("/user").authenticated()
                .anyRequest().permitAll();
    }

    private class AuthentificationLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    private class AuthentificationLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
        @Override
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                    Authentication authentication) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    @Bean
    public AuthenticationProvider getProvider() {
        AppAuthProvider provider = new AppAuthProvider();
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }
}
</code>```

the IUser repository class

```<code>@Repository
public interface IUser extends JpaRepository<User, String>{

    public List<User> findByUsername(String username);

    public List<User> findAll();

    @Query("SELECT u FROM User u WHERE u.matricule=:matricule AND u.activated=true")
    public Optional<User> findUserWithMatricule(String matricule);

    //update user
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.username=:username, u.codeExploitant=:codeExploitant WHERE u.matricule=:matricule")
    public void updateUser(@Param("username") String username, @Param("codeExploitant") String codeExploitant,
            @Param("matricule") String matricule);

    //update password
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.password=:password WHERE u.matricule=:matricule")
    public void updatePassword(@Param("password") String password, @Param("matricule") String matricule);

    //update etat
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.activated=:etat WHERE u.matricule=:matricule")
    public void updateEtatActivated(@Param("etat") boolean etat, @Param("matricule") String matricule);

}
</code>```

the errors generated

```<code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
10:25:40.442 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\PROJETBNI\ECLIPSE_WORKSPACE\Gestion_Operation\target\classes\org\bni\gestionoperation\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SparingApplication.java:1215)
    at org.bni.gestionoperation.GestionOperationApplication.main(GestionOperationApplication.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\PROJETBNI\ECLIPSE_WORKSPACE\Gestion_Operation\target\classes\org\bni\gestionoperation\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:226)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
    ... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778)
    ... 37 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582)
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:74)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:211)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:161)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:144)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:312)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297)
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:212)
    at org.springframework.data.util.Lazy.get(Lazy.java:94)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:121)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799)
    ... 48 common frames omitted
</code>```

答:
my datasources are manually generated and I forgot to modify the package in entityScan from the factory.</p>

```<code>factory.setPackagesToScan("org.bni.gestionoperation.model");
</code>```

Body:
I wrote a lot of code so I can't find exactly the code that generates this error but I have been trying to fix it for days without success. This is an error concerning the userDetailsService that I have implemented on userService, the user entity class implements UserDetails and serializable. Please I need help.

the User entity class

@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User implements UserDetails, Serializable{

  @Id
  private String matricule;

  private String password;

  private String username;

  private String codeExploitant;

  private Boolean activated;

  @Column(nullable=true)
  private String createdBy;

   @OneToMany(mappedBy="user", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
   private List<UserCaisse> caisses;

   public void addCaisse(Caisse caisse) {
       //recupereration de la date systeme
       LocalDateTime dateTime = LocalDateTime.now();

          UserCaisse userCaisse = new UserCaisse(this, caisse);
          userCaisse.setDate(dateTime);
          caisses.add(userCaisse);
          caisse.getUsers().add(userCaisse);
      }

   public void removeCaisse(Caisse caisse) {
          for (Iterator<UserCaisse> iterator = caisses.iterator();
               iterator.hasNext(); ) {
              UserCaisse userCaisse = iterator.next();

              if (userCaisse.getUser().equals(this) &&
                      userCaisse.getCaisse().equals(caisse)) {
                  iterator.remove();
                  userCaisse.getCaisse().getUsers().remove(userCaisse);
                  userCaisse.setUser(null);
                  userCaisse.setCaisse(null);
              }
          }
   }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
      return null;
  }

  @Override
  public boolean isAccountNonExpired() {
      return false;
  }

  @Override
  public boolean isAccountNonLocked() {
      return false;
  }

  @Override
  public boolean isCredentialsNonExpired() {
      return false;
  }

  @Override
  public boolean isEnabled() {
      return false;
  }
}

the UserService class

@Service
@Slf4j
public class UserService implements UserDetailsService{

    private final IUser userRepository;

    private final ICaisse caisseRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    private User user;

    @Autowired
    public UserService(IUser userRepository, ICaisse caisseRepository) {
        this.userRepository=userRepository;
        this.caisseRepository=caisseRepository;
    }

    //find methods
    public User findById(String matricule) {
        log.info("Selection d'un enregistrement de user a partir du matricule {} effectué avec succès", matricule);
        return userRepository.findById(matricule).orElse(new User());
    }

    public List<User> find(String username) {
        log.info("Selection d'une liste d'enregistrement de user a partir de username effectué avec succès");
        return userRepository.findByUsername(username);
    }

    public List<User> find(){
        List<User> lstUser=userRepository.findAll();

        try {
            lstUser.forEach(item->{
                item.setPassword(null);
            });

            log.info("Selection de tous les users effectué avec succès");
        } catch (Exception e) {
            log.error("Erreur lors de la selection de tous les users {}",e.getMessage());
            System.err.println("Erreur lors de la selection de tous les users "+e.getMessage());
        }

        return lstUser;
    }

    public User getOne(String matricule) {
        log.info("Selection d'un enregistrement de user a partir de matricule: {} effectué avec succès",matricule);
        return userRepository.getOne(matricule);
    }

    //Delete methods
    public boolean delete(String matricule) {
        boolean success=false;

        try {
            if(!StringUtils.isEmpty(matricule)) {
                user=userRepository.findById(matricule).orElse(new User());
                userRepository.deleteById(user.getMatricule());
                success=true;
            }

            log.info("Suppression de l'utilisateur de matricule {} effectuée avec succès",matricule);
        } catch (Exception e) {
            log.error("Erreur survenu lors de la suppression de l'enregistrement {} erreur:{}",matricule,e.getMessage());
            System.err.println("Erreur survenu lors de la suppression de l'enregistrement "+matricule+" "+e.getMessage());
        }

        return success;
    }

    public List<Caisse> getCaisseByUser(String matricule){
        List<Caisse> caisses=caisseRepository.findAll();
        User user=userRepository.findById(matricule).orElse(new User());
        List<Caisse> lstCaisses=new ArrayList<Caisse>();

        try {
            List<UserCaisse> uc=user.getCaisses();

            caisses.forEach(item->{
                uc.forEach(data->{
                    if(item.getIdCaisse().equals(data.getId().getIdCaisse())) {
                        lstCaisses.add(item);
                    }
                });
            });

            log.info("Recuperation d'une liste de caisse selon l'utlisateur {} effectué avec succès",matricule);
        } catch (Exception e) {
            log.error("Erreur lors de la recuperation de la liste de caisse selon l'utilisateur");
            System.err.println("Erreur lors de la recuperation de la liste de caisse selon l'utilisateur "+e.getMessage());
        }

        return lstCaisses;
    }

    //save
    public User save(User user, String mode) {
        User u=new User();

        try {
            if(mode=="create") {
                //cryptage de password
                String passwordEncrypt=passwordEncoder.encode(user.getPassword());
                user.setPassword(passwordEncrypt);
                u=userRepository.save(user);
            }
            else if(mode=="update"){
                if(user.getPassword()==null) {
                    User getUser=userRepository.findById(user.getMatricule()).orElse(new User());
                    user.setPassword(getUser.getPassword());
                }else {
                    user.setPassword(passwordEncoder.encode(user.getPassword()));
                }

                u=userRepository.save(user);
            }else{
                u=userRepository.save(user);
            }

            log.info("Enregistrement de l'utilisateur {} effectué avec succès",u.getMatricule());
        } catch (Exception e) {
            log.error("Erreur survenu lors de l'enregistrement des données de l'utilisateur {}",user.getMatricule());
            System.err.println("Erreur survenu lors de l'enregistrement des données de l'utilisateur "+user.getMatricule());
        }

        return u;
    }

    public boolean verifPassword(String password, String matricule) {
        boolean success=false;

        try {
            User u=userRepository.findById(matricule).orElse(new User());
            success=passwordEncoder.matches(password, u.getPassword());
            log.info("Verification du mot de passe effectué avec succès");
            success=true;
        } catch (Exception e) {
            log.info("Echec de la verification du mot de passe {}",e.getMessage());
            System.err.println("Echec de la verification du mot de passe "+e.getMessage());
            success=false;
        }

        return success;
    }

    //edit methods
    public void editUser(String username, String codeExploitant, String matricule) {
        log.info("Modification de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updateUser(username, codeExploitant, matricule);
    }

    public void editPassword(String password, String matricule) {
        log.info("Modification du mot de passe de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updatePassword(password, matricule);
    }

    public void editEtat(boolean etat, String matricule) {
        log.info("Modification de l'etat de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updateEtatActivated(etat, matricule);
    }

    //Login
    @Override
    public UserDetails loadUserByUsername(String matricule) throws UsernameNotFoundException {

        Objects.requireNonNull(matricule);

        log.info("Chargement des informations de l'utilisateur {} effectué avec succès",matricule );
        User user = userRepository.findUserWithMatricule(matricule)
                .orElseThrow(() -> new UsernameNotFoundException("User non trouvé"));

        return user;
    }

}

the WebSecurityConfig class

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandler() {

            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response,
                    AccessDeniedException accessDeniedException) throws IOException, ServletException {
            }
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(new Http403ForbiddenEntryPoint() {
                })
                .and()
                .authenticationProvider(getProvider())
                .formLogin()
                .loginProcessingUrl("/login")
                .passwordParameter("password")
                .usernameParameter("username")
                .successHandler(new AuthentificationLoginSuccessHandler())
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
                .invalidateHttpSession(true)
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/logout").permitAll()
                .antMatchers("/user").authenticated()
                .anyRequest().permitAll();
    }

    private class AuthentificationLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    private class AuthentificationLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
        @Override
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                    Authentication authentication) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    @Bean
    public AuthenticationProvider getProvider() {
        AppAuthProvider provider = new AppAuthProvider();
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }
}

the IUser repository class

@Repository
public interface IUser extends JpaRepository<User, String>{

    public List<User> findByUsername(String username);

    public List<User> findAll();

    @Query("SELECT u FROM User u WHERE u.matricule=:matricule AND u.activated=true")
    public Optional<User> findUserWithMatricule(String matricule);

    //update user
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.username=:username, u.codeExploitant=:codeExploitant WHERE u.matricule=:matricule")
    public void updateUser(@Param("username") String username, @Param("codeExploitant") String codeExploitant,
            @Param("matricule") String matricule);

    //update password
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.password=:password WHERE u.matricule=:matricule")
    public void updatePassword(@Param("password") String password, @Param("matricule") String matricule);

    //update etat
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.activated=:etat WHERE u.matricule=:matricule")
    public void updateEtatActivated(@Param("etat") boolean etat, @Param("matricule") String matricule);

}

the errors generated

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
10:25:40.442 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\PROJETBNI\ECLIPSE_WORKSPACE\Gestion_Operation\target\classes\org\bni\gestionoperation\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SparingApplication.java:1215)
    at org.bni.gestionoperation.GestionOperationApplication.main(GestionOperationApplication.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\PROJETBNI\ECLIPSE_WORKSPACE\Gestion_Operation\target\classes\org\bni\gestionoperation\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:226)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
    ... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778)
    ... 37 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582)
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:74)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:211)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:161)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:144)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:312)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297)
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:212)
    at org.springframework.data.util.Lazy.get(Lazy.java:94)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:121)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799)
    ... 48 common frames omitted

Body:
my datasources are manually generated and I forgot to modify the package in entityScan from the factory.

factory.setPackagesToScan("org.bni.gestionoperation.model");


来源: stackexchange

问:
Bootstrap 4 Change Tab on Hover
Here is the Bootstrap 4 Tab Default tab structure, How to toggle between the tabs on mouse hover? someone kindly add solution using jquery or javascript.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

    Home

    Profile

    Contact

Home

Profile

Contact

```

答:
This will help you you just need to trigger the click on hover function

$(".nav-link").hover(function(){
$(this).click();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    Home
  </li>
  <li class="nav-item">
    Profile
  </li>
  <li class="nav-item">
    Contact
  </li>
</ul>
<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="home" role="tabpanel">Home</div>
  <div class="tab-pane fade" id="profile" role="tabpanel">Profile</div>
  <div class="tab-pane fade" id="contact" role="tabpanel">Contact</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Bootstrap 4 Change Tab on Hover

Body:
This will help you you just need to trigger the click on hover function

$(".nav-link").hover(function(){
$(this).click();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile">Profile</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact">Contact</a>
  </li>
</ul>
<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="home" role="tabpanel">Home</div>
  <div class="tab-pane fade" id="profile" role="tabpanel">Profile</div>
  <div class="tab-pane fade" id="contact" role="tabpanel">Contact</div>
</div>


问:
How to optimize query with Inline Function in it?
I have a table TAB_1 with following Schema

```<code>    CAR_NO(Varchar)  START_DATE(Date)  ACTUAL_ARRIVAL_TIME(Number)  SOURCE_POINT(Varchar)
   END_POINT(Varchar)
</code>```

Table TAB_2 with following Schema

```<code>CAR_NO(Varchar)   ACTL_TIME_OF_ARRVL(Date)  EVENT_CODE(Varchar)
</code>```

My query is :

```<code> SELECT DISTINCT CAR_NO,START_DATE FROM TAB_1 WHERE
(TRUNC(START_DATE +CASE WHEN ACTUAL_ARRIVAL_TIME=0 THEN NULL ELSE ACTUAL_ARRIVAL_TIME END/1440)='10-Feb-2020' )
    AND SOURCE_POINT=END_POINT
    UNION
    SELECT DISTINCT  CAR_NO,START_DATE FROM TAB_2 WHERE EVENT_CODE='TD'
    AND TRUNC( ACTL_TIME_OF_ARRVL)='10-Feb-2020'
</code>```

Column ACTUAL_ARRIVAL_TIME stores the time value in minutes,Column ACTL_TIME_OF_ARRVL stores the date as timestamp value , I am trying to find all the cars which terminate on 10-Feb-2020 .Data can be absent from any of the tables so I have used UNION Operation here ,on top of this query I have to apply more operations ,so overall it is taking time of 35 seconds aprox. Please guide to optimize this query .

答:
Using trunc() on the column value will prevent an index on that column being used (unless it's a function-based index). It's better to use a date range, covering the entire day you're interested in. Adding the time offset to the start_date will also impact the index; and '10-Feb-2020' is a string not a date, so you're forcing implicit conversion - never a good idea. You also don't need distinct with union as (unlike union all) that eliminates duplicates anyway.

I'd suggest something like this as a starting point:

```<code>select car_no, start_date
from tab_1
where source_point = end_point
and start_date >= date '2020-02-10' - actual_arrival_time * interval '1' minute
and start_date < date '2020-02-11' - actual_arrival_time * interval '1' minute
union
select car_no, start_date
from tab_2
where event_code='TD'
and actl_time_of_arrvl >= date '2020-02-10'
and actl_time_of_arrvl < date '2020-02-11'
</code>```

The actual_arrival_time * interval '1' minute gives you same effect as ACTUAL_ARRIVAL_TIME END/1440; the first is an interval data type, the second is a fraction of a day, but both represent the number of minutes as a value that can be added to a date value.

I'm using date literals, which are still hard-coded. If you're really using a parameter you can add interval '1' day to the date you want instead of hard-coding one day later. Either way that will look for values at or after midnight on the first date, and before midnight on the second date - which covers all possible times that day.

The first branch still can't really use the index properly because of the variability of referring to another column value in the range calculation, but if you know for example that actual_arrival_time is within 24 hours you could help it with that more rigid restriction:

```<code>select car_no,start_date
from tab_1
where source_point = end_point
and start_date >= date '2020-02-10'
and start_date < date '2020-02-10' + interval '2' day -- depending on allowed ranges
and start_date + actual_arrival_time * interval '1' minute >= date '2020-02-10'
and start_date + actual_arrival_time * interval '1' minute < date '2020-02-10' + interval '1' day
union
select car_no, start_date
from tab_2
where event_code='TD'
and actl_time_of_arrvl >= date '2020-02-10'
and actl_time_of_arrvl < date '2020-02-10' + interval '1' day
</code>```

Here start_date >= date '2020-02-10' gives the index a lower bound to search for (assuming actual_arrival_time can't be negative, which seems reasonable); and start_date < date '2020-02-10' + interval '2' day gives an upper bound. What that upper bound is will depend on the allowed values, particularly for actual_arrival_time.

It's unclear in your question whether tab1.start_date is always midnight, so you might be able to simplify the first part of the check to an exact date match instead of a range. But then looking at actual_arrival_time probably wouldn't be necessary... if start_date is actually always midnight and actual_arrival_time is constrained to between 0 and 1440 then it could be as simple as:

```<code>select car_no,start_date
from tab_1
where source_point = end_point
and start_date >= date '2020-02-10'
and start_date < date '2020-02-10' + interval '1' day
union
...
</code>```

just like the second branch. But the way you've tried to approach it suggests that might not be the case, and you just need to narrow the initial index search as much as possible before then filtering on the exact time. I suspect the actual_arrival_time could represent several days, or even weeks or months; so going back to the previous version, the

```<code>and start_date < date '2020-02-10' + interval '2' day -- depending on allowed ranges
</code>```

would extend to the maximum you'd expect to see; or could probably be omitted completely.

You need to look at the execution plan to see what it is actually doing though, probably for the overall query and each branch of the union separately.

If you're going to be doing this a lot it might be worth adding the calculated value start_date + actual_arrival_time * interval '1' minute to tab1 as a virtual column, and indexing that.

Body:
I have a table TAB_1 with following Schema

    CAR_NO(Varchar)  START_DATE(Date)  ACTUAL_ARRIVAL_TIME(Number)  SOURCE_POINT(Varchar)
   END_POINT(Varchar)

Table TAB_2 with following Schema

CAR_NO(Varchar)   ACTL_TIME_OF_ARRVL(Date)  EVENT_CODE(Varchar)

My query is :

 SELECT DISTINCT CAR_NO,START_DATE FROM TAB_1 WHERE
(TRUNC(START_DATE +CASE WHEN ACTUAL_ARRIVAL_TIME=0 THEN NULL ELSE ACTUAL_ARRIVAL_TIME END/1440)='10-Feb-2020' )
    AND SOURCE_POINT=END_POINT
    UNION
    SELECT DISTINCT  CAR_NO,START_DATE FROM TAB_2 WHERE EVENT_CODE='TD'
    AND TRUNC( ACTL_TIME_OF_ARRVL)='10-Feb-2020'

Column ACTUAL_ARRIVAL_TIME stores the time value in minutes,Column ACTL_TIME_OF_ARRVL stores the date as timestamp value , I am trying to find all the cars which terminate on 10-Feb-2020 .Data can be absent from any of the tables so I have used UNION Operation here ,on top of this query I have to apply more operations ,so overall it is taking time of 35 seconds aprox. Please guide to optimize this query .

Body:
Using trunc() on the column value will prevent an index on that column being used (unless it's a function-based index). It's better to use a date range, covering the entire day you're interested in. Adding the time offset to the start_date will also impact the index; and '10-Feb-2020' is a string not a date, so you're forcing implicit conversion - never a good idea. You also don't need distinct with union as (unlike union all) that eliminates duplicates anyway.

I'd suggest something like this as a starting point:

select car_no, start_date
from tab_1
where source_point = end_point
and start_date >= date '2020-02-10' - actual_arrival_time * interval '1' minute
and start_date < date '2020-02-11' - actual_arrival_time * interval '1' minute
union
select car_no, start_date
from tab_2
where event_code='TD'
and actl_time_of_arrvl >= date '2020-02-10'
and actl_time_of_arrvl < date '2020-02-11'

The actual_arrival_time * interval '1' minute gives you same effect as ACTUAL_ARRIVAL_TIME END/1440; the first is an interval data type, the second is a fraction of a day, but both represent the number of minutes as a value that can be added to a date value.

I'm using date literals, which are still hard-coded. If you're really using a parameter you can add interval '1' day to the date you want instead of hard-coding one day later. Either way that will look for values at or after midnight on the first date, and before midnight on the second date - which covers all possible times that day.

The first branch still can't really use the index properly because of the variability of referring to another column value in the range calculation, but if you know for example that actual_arrival_time is within 24 hours you could help it with that more rigid restriction:

select car_no,start_date
from tab_1
where source_point = end_point
and start_date >= date '2020-02-10'
and start_date < date '2020-02-10' + interval '2' day -- depending on allowed ranges
and start_date + actual_arrival_time * interval '1' minute >= date '2020-02-10'
and start_date + actual_arrival_time * interval '1' minute < date '2020-02-10' + interval '1' day
union
select car_no, start_date
from tab_2
where event_code='TD'
and actl_time_of_arrvl >= date '2020-02-10'
and actl_time_of_arrvl < date '2020-02-10' + interval '1' day

Here start_date >= date '2020-02-10' gives the index a lower bound to search for (assuming actual_arrival_time can't be negative, which seems reasonable); and start_date < date '2020-02-10' + interval '2' day gives an upper bound. What that upper bound is will depend on the allowed values, particularly for actual_arrival_time.

It's unclear in your question whether tab1.start_date is always midnight, so you might be able to simplify the first part of the check to an exact date match instead of a range. But then looking at actual_arrival_time probably wouldn't be necessary... if start_date is actually always midnight and actual_arrival_time is constrained to between 0 and 1440 then it could be as simple as:

select car_no,start_date
from tab_1
where source_point = end_point
and start_date >= date '2020-02-10'
and start_date < date '2020-02-10' + interval '1' day
union
...

just like the second branch. But the way you've tried to approach it suggests that might not be the case, and you just need to narrow the initial index search as much as possible before then filtering on the exact time. I suspect the actual_arrival_time could represent several days, or even weeks or months; so going back to the previous version, the

and start_date < date '2020-02-10' + interval '2' day -- depending on allowed ranges

would extend to the maximum you'd expect to see; or could probably be omitted completely.

You need to look at the execution plan to see what it is actually doing though, probably for the overall query and each branch of the union separately.

If you're going to be doing this a lot it might be worth adding the calculated value start_date + actual_arrival_time * interval '1' minute to tab1 as a virtual column, and indexing that.


问:
How to filter out multiple specific keys and values from an array
I have this array of objects. I want to filter out only few of them, particularly the ones containing numbers.

```<code>const arr = [
    {
      Title: "Joker",
      Year: "2019",
      Rated: "R",
      Released: "04 Oct 2019",
      Runtime: "122 min",
      Genre: "Crime, Drama, Thriller",
      Director: "Todd Phillips",
      Writer:
        "Todd Phillips, Scott Silver, Bob Kane (based on characters created by), Bill Finger (based on characters created by), Jerry Robinson (based on characters created by)",
      Actors: "Joaquin Phoenix, Robert De Niro, Zazie Beetz, Frances Conroy",
      Plot:
        "In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime. This path brings him face-to-face with his alter-ego: the Joker.",
      Language: "English",
      Country: "USA, Canada",
      Awards: "Won 2 Oscars. Another 57 wins & 163 nominations.",
      Poster:
        "https://m.media-amazon.com/images/M/MV5BNGVjNWI4ZGUtNzE0MS00YTJmLWE0ZDctN2ZiYTk2YmI3NTYyXkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg",
      Ratings: [
        { Source: "Internet Movie Database", Value: "8.6/10" },
        { Source: "Rotten Tomatoes", Value: "69%" },
        { Source: "Metacritic", Value: "59/100" }
      ],
      Metascore: "59",
      imdbRating: "8.6",
      imdbVotes: "665,555",
      imdbID: "tt7286456",
      Type: "movie",
      DVD: "17 Dec 2019",
      BoxOffice: "N/A",
      Production: "Warner Bros. Pictures",
      Website: "N/A",
      Response: "True"
    }
  ];

</code>```

Initially Api response was in object, so I converted the object to an array somehow. Now I want to filter out the numbers to compare. Here's what I tried:

```<code>const makeArr = obj => {
    let arr = [];
    for (let [key, value] of Object.entries(obj)) {
      arr.push({
        [key]: value
      });
    }
    return arr.filter(item => {
      if (Object.values(item).includes(isNaN(parseInt(Object.values(item))))) {
        return item;
      }
    });
  };

</code>```

答: parseInt does properly works on primitives, so iterate over the object values and check with !isNaN(parseInt(value))</p>

Body:
I have this array of objects. I want to filter out only few of them, particularly the ones containing numbers.

const arr = [
    {
      Title: "Joker",
      Year: "2019",
      Rated: "R",
      Released: "04 Oct 2019",
      Runtime: "122 min",
      Genre: "Crime, Drama, Thriller",
      Director: "Todd Phillips",
      Writer:
        "Todd Phillips, Scott Silver, Bob Kane (based on characters created by), Bill Finger (based on characters created by), Jerry Robinson (based on characters created by)",
      Actors: "Joaquin Phoenix, Robert De Niro, Zazie Beetz, Frances Conroy",
      Plot:
        "In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime. This path brings him face-to-face with his alter-ego: the Joker.",
      Language: "English",
      Country: "USA, Canada",
      Awards: "Won 2 Oscars. Another 57 wins & 163 nominations.",
      Poster:
        "https://m.media-amazon.com/images/M/MV5BNGVjNWI4ZGUtNzE0MS00YTJmLWE0ZDctN2ZiYTk2YmI3NTYyXkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg",
      Ratings: [
        { Source: "Internet Movie Database", Value: "8.6/10" },
        { Source: "Rotten Tomatoes", Value: "69%" },
        { Source: "Metacritic", Value: "59/100" }
      ],
      Metascore: "59",
      imdbRating: "8.6",
      imdbVotes: "665,555",
      imdbID: "tt7286456",
      Type: "movie",
      DVD: "17 Dec 2019",
      BoxOffice: "N/A",
      Production: "Warner Bros. Pictures",
      Website: "N/A",
      Response: "True"
    }
  ];

Initially Api response was in object, so I converted the object to an array somehow. Now I want to filter out the numbers to compare. Here's what I tried:

const makeArr = obj => {
    let arr = [];
    for (let [key, value] of Object.entries(obj)) {
      arr.push({
        [key]: value
      });
    }
    return arr.filter(item => {
      if (Object.values(item).includes(isNaN(parseInt(Object.values(item))))) {
        return item;
      }
    });
  };


问:
ubuntu upstart not respawning the daemon despite respawn in the config file
I have problems with my deamon restart. upstart is not spawning the daemon when the daemon crashes.
here is my upstart init file .
pls advise.</p>

```<code>description "bezkon watch dog"

start on runlevel [2345]

stop on runlevel  [!2345]

respawn

expect fork

script

        logger -s "Bezkon watch dog booting ..."

        logger -s "Waiting for engine to complete booting sleeping for 60 seconds "

        sleep 300

        export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

        export LUA_PATH=$LUA_PATH:/usr/local/bezkon/

        export LUA_CPATH=$LUA_CPATH:/usr/local/bezkon/

        chdir /usr/local/bezkon;

end script

exec /usr/local/bezkon/bezkon_dog >> /var/log/bezkon_crash.log 2>&1
</code>```

答:
I don't think you can use script and exec together. Try pre-start script instead. Or put the exec line inside the script stanza. Not sure how this works together with expect fork though.

EDIT: Take a look at this bug comment by Scott Remnant, the lead Upstart dev. It looks like it would apply to your config file, and it doesn't appear that it has been fixed yet. I still think you might want to try pre-start script, or experiment with expect daemon vs. expect fork vs. nothing. Assuming you haven't done this already, it can't hurt.

ContentLicense: CC BY-SA 3.0

Body:
I have problems with my deamon restart. upstart is not spawning the daemon when the daemon crashes.
here is my upstart init file .
pls advise.

description "bezkon watch dog"

start on runlevel [2345]

stop on runlevel  [!2345]

respawn

expect fork

script

        logger -s "Bezkon watch dog booting ..."

        logger -s "Waiting for engine to complete booting sleeping for 60 seconds "

        sleep 300

        export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

        export LUA_PATH=$LUA_PATH:/usr/local/bezkon/

        export LUA_CPATH=$LUA_CPATH:/usr/local/bezkon/

        chdir /usr/local/bezkon;

end script

exec /usr/local/bezkon/bezkon_dog >> /var/log/bezkon_crash.log 2>&1


问:
Implementing Cross Validation for CNN model
I have built my CNN model to classify images for 8 classes. The Training and testing steps have been done through randomly splitting 80% for training images and 20% for testing images, where Acuuracy and F-measure results have been calculated.

I have noticed that my training accuracy results are slightly less, compared to my testing results (where I believe that the training accuracy should be higher). After conducting a lot of search, I found two reasons:

1- The use of droput(0.5), which affects the training accuracy results

2-The testing dataset is simple to be classified.

I am planning to evaluate my CNN classifier by conducting 10-k cross validation. However, since I am still new in this area, most of the answers I found were for .csv files, where I have the image files.

How can I code to get the cross validation?

Can I get a confusion matrix for cross validation?

My code:

```<code>from keras.models import Sequential
from keras.layers import Conv2D,Activation,MaxPooling2D,Dense,Flatten,Dropout
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import classification_report, confusion_matrix
import keras
from keras.layers import BatchNormalization
from keras.optimizers import Adam

classifier = Sequential()
classifier.add(Conv2D(32,(3,3),input_shape=(200,200,3)))
classifier.add(Activation('relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(128))
classifier.add(Activation('relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(8))
classifier.add(Activation('softmax'))
classifier.summary()
classifier.compile(optimizer =keras.optimizers.Adam(lr=0.001),
                   loss ='categorical_crossentropy',
                   metrics =['accuracy'])
train_datagen = ImageDataGenerator(rescale =1./255,
                                   shear_range =0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip =True)
test_datagen = ImageDataGenerator(rescale = 1./255)

batchsize=10
training_set = train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train/',
                                                target_size=(200,200),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Test/',
                                           target_size = (200,200),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch = 3067 // batchsize,
                        epochs = 50,
                        validation_data =test_set,
                        validation_steps = 769 // batchsize)

Y_pred = classifier.predict_generator(test_set, steps= 769 // batchsize + 1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))
print('Classification Report')
target_names = test_set.classes
class_labels = list(test_set.class_indices.keys())
target_names = ['coinhive','emotent','fareit', 'flystudio', 'gafgyt','gamarue', 'mirai','razy']
report = classification_report(test_set.classes, y_pred, target_names=class_labels)
print(report)

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
</code>```

答:
According to Wikipedia

In k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k − 1 subsamples are used as training data.

For example, like you want to do 10-fold cross validation, you will

Partition the data into ten random, equal parts

Train ten separate models with nine subsets of the data,

Validate on a different subset of data for each model

Find the confusion matrix on each model separately

The code for training and testing will remain the same, just the data input can be taken via either custom generators, or by using SKLearn's KFold.

Body:
I have built my CNN model to classify images for 8 classes. The Training and testing steps have been done through randomly splitting 80% for training images and 20% for testing images, where Acuuracy and F-measure results have been calculated.

I have noticed that my training accuracy results are slightly less, compared to my testing results (where I believe that the training accuracy should be higher). After conducting a lot of search, I found two reasons:

1- The use of droput(0.5), which affects the training accuracy results

2-The testing dataset is simple to be classified.

I am planning to evaluate my CNN classifier by conducting 10-k cross validation. However, since I am still new in this area, most of the answers I found were for .csv files, where I have the image files.

How can I code to get the cross validation?

Can I get a confusion matrix for cross validation?

My code:

from keras.models import Sequential
from keras.layers import Conv2D,Activation,MaxPooling2D,Dense,Flatten,Dropout
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import classification_report, confusion_matrix
import keras
from keras.layers import BatchNormalization
from keras.optimizers import Adam

classifier = Sequential()
classifier.add(Conv2D(32,(3,3),input_shape=(200,200,3)))
classifier.add(Activation('relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(128))
classifier.add(Activation('relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(8))
classifier.add(Activation('softmax'))
classifier.summary()
classifier.compile(optimizer =keras.optimizers.Adam(lr=0.001),
                   loss ='categorical_crossentropy',
                   metrics =['accuracy'])
train_datagen = ImageDataGenerator(rescale =1./255,
                                   shear_range =0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip =True)
test_datagen = ImageDataGenerator(rescale = 1./255)

batchsize=10
training_set = train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train/',
                                                target_size=(200,200),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Test/',
                                           target_size = (200,200),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch = 3067 // batchsize,
                        epochs = 50,
                        validation_data =test_set,
                        validation_steps = 769 // batchsize)

Y_pred = classifier.predict_generator(test_set, steps= 769 // batchsize + 1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))
print('Classification Report')
target_names = test_set.classes
class_labels = list(test_set.class_indices.keys())
target_names = ['coinhive','emotent','fareit', 'flystudio', 'gafgyt','gamarue', 'mirai','razy']
report = classification_report(test_set.classes, y_pred, target_names=class_labels)
print(report)

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()


问:
Expand Searchbar with Search icon as well as show close icon onclick using Javascript
I am trying to open the expanded search bar with a search icon as well as a close icon on click using javascript. Here I am attaching my code. Your help will be appreciated in advance. I am also attaching the image so it can be understood very well. My code is on hover but I want to make it on click.

//Search Bar
        var searchBar = document.getElementById("express-form-typeahead");
        searchBar.addEventListener('click' , function(){
            var closeSearch = document.getElementById("closeSearch");
            closeSearch.style.display = "block";
        });
        window.addEventListener('mouseup', e =>{
            //alert(e);
                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    var closeSearch = document.getElementById("closeSearch");
                    closeSearch.style.display = "";
                }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-search{position: relative;right:-12px;}
    #express-form-typeahead{background-color:transparent;background-image:url('../images/search.svg');background-position:5px center;background-repeat:no-repeat;background-size:15px;border:none;cursor:pointer;height:30px;padding:0 0 0 34px;position:relative;-webkit-transition:width 1.1s ease, background 1.1s ease;transition:width 1.1s ease, background 1.1s ease;width:0;}
    .close-search{display:none;-webkit-animation: fadeEffect1 2s;animation: fadeEffect1 2s;
    position: absolute;top:9px;right:9px;background-image: url('../images/close-icon-grey.png');width: 15px;
    height: 15px;background-repeat: no-repeat;background-size: 15px;}
    #express-form-typeahead:focus{background-color:#fff;border-bottom:1px solid #e7e7e7;cursor:text;outline:0;width:200px;border-radius: 0;}
    .search-btn{display:none;}
    input[type="search"]{-webkit-appearance:textfield;}
   /* Fade in tabs */
    @-webkit-keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }</code>```

                                <input required="" name="q" placeholder="Blue Book" class="form-control" id="express-form-typeahead"  type="search">
                                <button class="search-btn" type="submit"></button>

```

答:
If your code snippet was able to work, I could give you the answer. But now I can guide you only. In such cases you better to use a toggle class. When user clicks on element, toggle class will be added and when click out it will be removed.

var searchBar = document.getElementById("searchBar");
        searchBar.addEventListener('click' , function(){
            searchBar.classList.add("toggleClass");
        });
        window.addEventListener('mouseup', e =>{

                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    searchBar.classList.remove("toggleClass");
                }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.searchBar{
  width: 100px;
  background-color: silver;
  height: 50px;
  display: inline-block;
  transition-duration: 0.5s;
}

.searchBar .icon{
display: none;
}

.toggleClass{
  width: 300px;
  }

  .toggleClass .icon{
  display: block;
  }</code>```

  icon

```

Body:
I am trying to open the expanded search bar with a search icon as well as a close icon on click using javascript. Here I am attaching my code. Your help will be appreciated in advance. I am also attaching the image so it can be understood very well. My code is on hover but I want to make it on click.

//Search Bar
        var searchBar = document.getElementById("express-form-typeahead");
        searchBar.addEventListener('click' , function(){
            var closeSearch = document.getElementById("closeSearch");
            closeSearch.style.display = "block";
        });
        window.addEventListener('mouseup', e =>{
            //alert(e);
                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    var closeSearch = document.getElementById("closeSearch");
                    closeSearch.style.display = "";
                }
        });

.custom-search{position: relative;right:-12px;}
    #express-form-typeahead{background-color:transparent;background-image:url('../images/search.svg');background-position:5px center;background-repeat:no-repeat;background-size:15px;border:none;cursor:pointer;height:30px;padding:0 0 0 34px;position:relative;-webkit-transition:width 1.1s ease, background 1.1s ease;transition:width 1.1s ease, background 1.1s ease;width:0;}
    .close-search{display:none;-webkit-animation: fadeEffect1 2s;animation: fadeEffect1 2s;
    position: absolute;top:9px;right:9px;background-image: url('../images/close-icon-grey.png');width: 15px;
    height: 15px;background-repeat: no-repeat;background-size: 15px;}
    #express-form-typeahead:focus{background-color:#fff;border-bottom:1px solid #e7e7e7;cursor:text;outline:0;width:200px;border-radius: 0;}
    .search-btn{display:none;}
    input[type="search"]{-webkit-appearance:textfield;}
   /* Fade in tabs */
    @-webkit-keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }

                                <input required="" name="q" placeholder="Blue Book" class="form-control" id="express-form-typeahead"  type="search">
                                <button class="search-btn" type="submit"></button>

Body:
If your code snippet was able to work, I could give you the answer. But now I can guide you only. In such cases you better to use a toggle class. When user clicks on element, toggle class will be added and when click out it will be removed.

var searchBar = document.getElementById("searchBar");
        searchBar.addEventListener('click' , function(){
            searchBar.classList.add("toggleClass");
        });
        window.addEventListener('mouseup', e =>{

                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    searchBar.classList.remove("toggleClass");
                }
        });

.searchBar{
  width: 100px;
  background-color: silver;
  height: 50px;
  display: inline-block;
  transition-duration: 0.5s;
}

.searchBar .icon{
display: none;
}

.toggleClass{
  width: 300px;
  }

  .toggleClass .icon{
  display: block;
  }

<div id="searchBar" class="searchBar">
  <span class="icon">icon</span>
</div>


问:
How to scroll UICollectionView by scrolling slider in Swift?
I want to make collectionView that scrolls, when user scrolls UISlider. I'm using UISlider with same number of values as collection. But it is not very smooth. My code:

```<code>let currentValue = Int(sender.value)
collectionView.scrollToItem(at: IndexPath(row: currentValue, section: 0), at: .top, animated: true)
</code>```

Maybe there is more efficient way to do this? Like scrolling by offset? But I don't know how to calculate values to do this by using method collectionView.setContentOffset

答:
You can try:</p>

```<code>self.collectionView.contentOffset.y += sender.value // sender is your UISlider
</code>```

Body:
I want to make collectionView that scrolls, when user scrolls UISlider. I'm using UISlider with same number of values as collection. But it is not very smooth. My code:

let currentValue = Int(sender.value)
collectionView.scrollToItem(at: IndexPath(row: currentValue, section: 0), at: .top, animated: true)

Maybe there is more efficient way to do this? Like scrolling by offset? But I don't know how to calculate values to do this by using method collectionView.setContentOffset

Body:
You can try:

self.collectionView.contentOffset.y += sender.value // sender is your UISlider


问:
Stubbing Redis interactions in javascript using Sinon
I am working in node.js.  My app interacts with Redis via the node_redis module. I'm using mocha and sinon to automate testing of my app.  My app looks something like this:

```<code>...snip
var redisClient = redis.createClient(redisPort, redisHost);
var someValue = redisClient.get("someKey");
return someValue;
....
</code>```

I want to stub the call to redisClient.get().  To do this I also need to stub the call to redis.createClient() - I think...  Here's my test code:

```<code>...
var redis = require("redis");
var redisClient;
...
sinon.stub(redisClient, 'get').returns("someValue");
sinon.stub(redis, "createClient").returns(redisClient);
...
assert.equal(redis_client_underTest.call_to_redis(), "someValue");
...
</code>```

The test fails with AssertionError: false == "someValue"

How do I stub out redisClient, or is this even possible?

答:
Few key points are:

Stub redisClient before loading main module.

Stub the CRUD methods for redisClient.

Below is my main module:

```<code>/* Main module */
const redis = require('redis');
const redisClient = redis.createClient();

function value(){
  return redisClient.get('someKey');
}

module.exports = {value: value}
</code>```

Below is my test script:

```<code>/* Test */
var sinon = require('sinon');
var redis = require('redis');

// stub redis.createClient

var redisClient = {
    'get': () => "someValue"
}

var redisGetSpy = sinon.spy(redisClient, "get");
var redisClientStub = sinon.stub(redis,
                                 "createClient").callsFake(() => redisClient);

// require main module
var main = require('./main.js');

console.log(main.value(),
            redisClientStub.called,
            redisGetSpy.called,
            redisGetSpy.callCount);
</code>```

Body:
I am working in node.js.  My app interacts with Redis via the node_redis module. I'm using mocha and sinon to automate testing of my app.  My app looks something like this:

...snip
var redisClient = redis.createClient(redisPort, redisHost);
var someValue = redisClient.get("someKey");
return someValue;
....

I want to stub the call to redisClient.get().  To do this I also need to stub the call to redis.createClient() - I think...  Here's my test code:

...
var redis = require("redis");
var redisClient;
...
sinon.stub(redisClient, 'get').returns("someValue");
sinon.stub(redis, "createClient").returns(redisClient);
...
assert.equal(redis_client_underTest.call_to_redis(), "someValue");
...

The test fails with AssertionError: false == "someValue"

How do I stub out redisClient, or is this even possible?

Body:
Few key points are:

Stub redisClient before loading main module.

Stub the CRUD methods for redisClient.

Below is my main module:

/* Main module */
const redis = require('redis');
const redisClient = redis.createClient();

function value(){
  return redisClient.get('someKey');
}

module.exports = {value: value}

Below is my test script:

/* Test */
var sinon = require('sinon');
var redis = require('redis');

// stub redis.createClient

var redisClient = {
    'get': () => "someValue"
}

var redisGetSpy = sinon.spy(redisClient, "get");
var redisClientStub = sinon.stub(redis,
                                 "createClient").callsFake(() => redisClient);

// require main module
var main = require('./main.js');

console.log(main.value(),
            redisClientStub.called,
            redisGetSpy.called,
            redisGetSpy.callCount);


问:
what is key in CTTelephonyNetworkInfo().serviceSubscriberCellularProviders and CTTelephonyNetworkInfo().serviceCurrentRadioAccessTechnology
I'm playing around with CoreTelephony framework to get some information about cellular data provider out of it. I execute below code:

let obj = CTTelephonyNetworkInfo()
if let array = obj.serviceSubscriberCellularProviders {
    for (key, value) in array {
        print("{")
        print("\(key)=<\(value.carrierName)>")
        print("\(key)=<\(value.mobileCountryCode)>")
        print("\(key)=<\(value.mobileNetworkCode)>")
        print("}")
    }
}

if let array = obj.serviceCurrentRadioAccessTechnology {
    for (key, value) in array1 {
        print("{")
        print("\(key)=<\(value)>")
        print("}")
    }
}
```

<p>I get this out put:</p>

```{
    0000000100000001=<Optional("Carrier")>
    0000000100000001=<Optional("432")>
    0000000100000001=<Optional("11")>
}
{
    0000000100000001=<CTRadioAccessTechnologyLTE>
}
```

Question
I'm wondering what is "0000000100000001" and what information we can get from it?

答:
The official docs are pretty clear now:

Although the actual value of a key isn’t important, you can also use it to get the carrier information associated with the service. To do so, pass the key to the serviceSubscriberCellularProviders dictionary.

So you can pass the "0000000100000001" as key to serviceSubscriberCellularProviders.

I think the API was changed to accommodate for iPhones with multiple SIMs.

Body:
I'm playing around with CoreTelephony framework to get some information about cellular data provider out of it. I execute below code:

let obj = CTTelephonyNetworkInfo()
if let array = obj.serviceSubscriberCellularProviders {
    for (key, value) in array {
        print("{")
        print("\(key)=<\(value.carrierName)>")
        print("\(key)=<\(value.mobileCountryCode)>")
        print("\(key)=<\(value.mobileNetworkCode)>")
        print("}")
    }
}

if let array = obj.serviceCurrentRadioAccessTechnology {
    for (key, value) in array1 {
        print("{")
        print("\(key)=<\(value)>")
        print("}")
    }
}

I get this out put:

{
    0000000100000001=<Optional("Carrier")>
    0000000100000001=<Optional("432")>
    0000000100000001=<Optional("11")>
}
{
    0000000100000001=<CTRadioAccessTechnologyLTE>
}

Question
I'm wondering what is "0000000100000001" and what information we can get from it?