问:
How to implement Role Permission based system in Spring Boot
I am trying to implement role permissions based system using spring boot and spring security. For this, I have taken an example from http://www.baeldung.com/role-and-privilege-for-spring-security-registration
, but failed to do that.

Efforts

SpringSecurity Configuration

```<code>package com.insight;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

        @Autowired
        private LogoutSuccessHandler myLogoutSuccessHandler;

        @Autowired
        private AuthenticationFailureHandler authenticationFailureHandler;

        @Override
        protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(authProvider());
        }

        @Override
        public void configure(final WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/resources/**");
        }

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequests()
            .antMatchers("/js/**","/css/**","/images/**","/fonts/**").permitAll()
            .antMatchers("/user/signup/**","/about", "/","/user/login/").permitAll() // #4
            .anyRequest().authenticated() // 7
            .and()
            .formLogin().failureUrl("/user/login?error=true")
            .defaultSuccessUrl("/")
            .loginProcessingUrl("/user/validateLogin")
            .usernameParameter("email")
            .passwordParameter("password")
            .loginPage("/user/login")
            .permitAll()
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/user/logout")).logoutSuccessUrl("/user/login")
            .permitAll();
        }
        @Bean
        public DaoAuthenticationProvider authProvider() {
            final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
            authProvider.setUserDetailsService(userDetailsService);
            authProvider.setPasswordEncoder(encoder());
            return authProvider;
        }

        @Bean
        public PasswordEncoder encoder() {
            return new BCryptPasswordEncoder(11);
        }
    }
</code>```

User Model

```<code>package com.insight.models;

import java.util.Collection;
import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;

@Entity
@Table(name = "users")
public class User {

     // An autogenerated id (unique for each user in the db)
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;

      @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
      private Set<Address> addresses;

      @NotNull
      @OneToOne(cascade = CascadeType.ALL)
      @JoinColumn(name = "title")
      private Configuration title;

      @OneToOne(cascade=CascadeType.ALL)
        @JoinTable(name="user_roles",
            joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")},
            inverseJoinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")}
        )
        private Collection<Role> roles;

      @NotNull
      private String firstName;
      @NotNull
      private String lastName;

      @NotNull
      @Column(unique = true)
      @Email
      private String email;
      @NotNull
      private String password;

      private String profileImage;

      @Column(name = "created_at")
      private Date createdAt;
      @Column(name = "created_by")
      private String createdBy;

      @Column(name = "updated_at")
      private Date updatedAt;
      @Column(name = "updated_by")
      private String updatedBy;

      private String status;
      private String deleteFlag;
      private String confirmationCode;
      private String lastLoginAt;
      private boolean enabled;
      private boolean tokenExpired;

      public User() {
            super();
            this.enabled = false;
        }

      @PrePersist
      void createdAt() {
        this.createdAt = this.updatedAt = new Date();
      }

      @PreUpdate
      void updatedAt() {
        this.updatedAt = new Date();
      }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Set<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(Set<Address> addresses) {
        this.addresses = addresses;
    }

    public Configuration getTitle() {
        return title;
    }

    public void setTitle(Configuration title) {
        this.title = title;
    }

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getProfileImage() {
        return profileImage;
    }

    public void setProfileImage(String profileImage) {
        this.profileImage = profileImage;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getUpdatedBy() {
        return updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDeleteFlag() {
        return deleteFlag;
    }

    public void setDeleteFlag(String deleteFlag) {
        this.deleteFlag = deleteFlag;
    }

    public String getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(String confirmationCode) {
        this.confirmationCode = confirmationCode;
    }

    public String getLastLoginAt() {
        return lastLoginAt;
    }

    public void setLastLoginAt(String lastLoginAt) {
        this.lastLoginAt = lastLoginAt;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isTokenExpired() {
        return tokenExpired;
    }

    public void setTokenExpired(boolean tokenExpired) {
        this.tokenExpired = tokenExpired;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = (prime * result) + ((email == null) ? 0 : email.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final User user = (User) obj;
        if (!email.equals(user.email)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
        return builder.toString();
    }

}
</code>```

Role Model

```<code>package com.insight.models;

import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="roles")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "roles")
    private Collection<User> userRoles;

    @ManyToMany
    @JoinTable(
        name = "roles_privileges",
        joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"))
    private Collection<Permission> permissions;

    public Role(String name) {
        this.name=name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<User> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(Collection<User> userRoles) {
        this.userRoles = userRoles;
    }

    public Collection<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(Collection<Permission> permissions) {
        this.permissions = permissions;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Role role = (Role) obj;
        if (!role.equals(role.name)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
        return builder.toString();
    }
}
</code>```

Permission Model

```<code>package com.insight.models;

import java.util.Collection;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

public class Permission {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "permissions")
    private Collection<Role> roles;

    public Permission(String name2) {
        name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Permission other = (Permission) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("Permission [name=").append(name).append("]").append("[id=").append(id).append("]");
        return builder.toString();
    }
}
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.insight</groupId>
    <artifactId>insight</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>insight</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
         </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>1.3.6.RELEASE</version><!--$NO-MVN-MAN-VER$-->
         </dependency>
         <dependency>
            <groupId>org.passay</groupId>
            <artifactId>passay</artifactId>
            <version>1.0</version>
         </dependency>
         <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
         </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

CustomUserDetailsService

```<code>package com.insight.services;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.insight.models.Permission;
import com.insight.models.Role;
import com.insight.models.User;
import com.insight.repositories.RoleRepository;
import com.insight.repositories.UserRepository;

@Service("userDetailsService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IUserService service;
    @Autowired
    private MessageSource messages;
    @Autowired
    private RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(email);
        if (user == null) {
            return new org.springframework.security.core.userdetails.User(
              " ", " ", true, true, true, true,
              getAuthorities(Arrays.asList(roleRepository.findByName("ROLE_USER"))));
        }

        return new org.springframework.security.core.userdetails.User(
          user.getEmail(), user.getPassword(), user.isEnabled(), true, true,
          true, getAuthorities(user.getRoles()));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {
        return getGrantedAuthorities(getPrivileges(roles));
    }

    private List<String> getPrivileges(Collection<Role> roles) {
        List<String> privileges = new ArrayList<String>();
        List<Permission> collection = new ArrayList<Permission>();
        for (Role role : roles) {
            collection.addAll(role.getPermissions());
        }
        for (Permission item : collection) {
            privileges.add(item.getName());
        }
        return privileges;
    }

    private List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        return authorities;
    }
}
</code>```

There some etc. classes also there, but I am not posting due to large segment, if anyone requires specifics, I will post.

When I tried to run, I am getting following error on console:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.insight.SecurityConfiguration.userDetailsService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.insight.repositories.UserRepository com.insight.services.CustomUserDetailsService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#778bd3a2' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#778bd3a2': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
          at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at

Please friends help me.

答:
As Michal pointed out, this is a DB problem -

```
Error creating bean with name 'entityManagerFactory' defined in class path resource[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is javax.persistence.PersistenceException:
[PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
```

Your MySQL DB may not be running, or you may not have provided the datasource connection in the spring properties [I see you have a MySQL dependency reference]

For debugging or test cases you might try H2 -

```<code><!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>test</scope>
</dependency>
</code>```

Body:
I am trying to implement role permissions based system using spring boot and spring security. For this, I have taken an example from http://www.baeldung.com/role-and-privilege-for-spring-security-registration
, but failed to do that.

Efforts

SpringSecurity Configuration

package com.insight;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

        @Autowired
        private LogoutSuccessHandler myLogoutSuccessHandler;

        @Autowired
        private AuthenticationFailureHandler authenticationFailureHandler;

        @Override
        protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(authProvider());
        }

        @Override
        public void configure(final WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/resources/**");
        }

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequests()
            .antMatchers("/js/**","/css/**","/images/**","/fonts/**").permitAll()
            .antMatchers("/user/signup/**","/about", "/","/user/login/").permitAll() // #4
            .anyRequest().authenticated() // 7
            .and()
            .formLogin().failureUrl("/user/login?error=true")
            .defaultSuccessUrl("/")
            .loginProcessingUrl("/user/validateLogin")
            .usernameParameter("email")
            .passwordParameter("password")
            .loginPage("/user/login")
            .permitAll()
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/user/logout")).logoutSuccessUrl("/user/login")
            .permitAll();
        }
        @Bean
        public DaoAuthenticationProvider authProvider() {
            final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
            authProvider.setUserDetailsService(userDetailsService);
            authProvider.setPasswordEncoder(encoder());
            return authProvider;
        }

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

User Model

package com.insight.models;

import java.util.Collection;
import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;

@Entity
@Table(name = "users")
public class User {

     // An autogenerated id (unique for each user in the db)
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;

      @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
      private Set<Address> addresses;

      @NotNull
      @OneToOne(cascade = CascadeType.ALL)
      @JoinColumn(name = "title")
      private Configuration title;

      @OneToOne(cascade=CascadeType.ALL)
        @JoinTable(name="user_roles",
            joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")},
            inverseJoinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")}
        )
        private Collection<Role> roles;

      @NotNull
      private String firstName;
      @NotNull
      private String lastName;

      @NotNull
      @Column(unique = true)
      @Email
      private String email;
      @NotNull
      private String password;

      private String profileImage;

      @Column(name = "created_at")
      private Date createdAt;
      @Column(name = "created_by")
      private String createdBy;

      @Column(name = "updated_at")
      private Date updatedAt;
      @Column(name = "updated_by")
      private String updatedBy;

      private String status;
      private String deleteFlag;
      private String confirmationCode;
      private String lastLoginAt;
      private boolean enabled;
      private boolean tokenExpired;

      public User() {
            super();
            this.enabled = false;
        }

      @PrePersist
      void createdAt() {
        this.createdAt = this.updatedAt = new Date();
      }

      @PreUpdate
      void updatedAt() {
        this.updatedAt = new Date();
      }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Set<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(Set<Address> addresses) {
        this.addresses = addresses;
    }

    public Configuration getTitle() {
        return title;
    }

    public void setTitle(Configuration title) {
        this.title = title;
    }

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getProfileImage() {
        return profileImage;
    }

    public void setProfileImage(String profileImage) {
        this.profileImage = profileImage;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getUpdatedBy() {
        return updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDeleteFlag() {
        return deleteFlag;
    }

    public void setDeleteFlag(String deleteFlag) {
        this.deleteFlag = deleteFlag;
    }

    public String getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(String confirmationCode) {
        this.confirmationCode = confirmationCode;
    }

    public String getLastLoginAt() {
        return lastLoginAt;
    }

    public void setLastLoginAt(String lastLoginAt) {
        this.lastLoginAt = lastLoginAt;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isTokenExpired() {
        return tokenExpired;
    }

    public void setTokenExpired(boolean tokenExpired) {
        this.tokenExpired = tokenExpired;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = (prime * result) + ((email == null) ? 0 : email.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final User user = (User) obj;
        if (!email.equals(user.email)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
        return builder.toString();
    }

}

Role Model

package com.insight.models;

import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="roles")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "roles")
    private Collection<User> userRoles;

    @ManyToMany
    @JoinTable(
        name = "roles_privileges",
        joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"))
    private Collection<Permission> permissions;

    public Role(String name) {
        this.name=name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<User> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(Collection<User> userRoles) {
        this.userRoles = userRoles;
    }

    public Collection<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(Collection<Permission> permissions) {
        this.permissions = permissions;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Role role = (Role) obj;
        if (!role.equals(role.name)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
        return builder.toString();
    }
}

Permission Model

package com.insight.models;

import java.util.Collection;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

public class Permission {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "permissions")
    private Collection<Role> roles;

    public Permission(String name2) {
        name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Permission other = (Permission) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("Permission [name=").append(name).append("]").append("[id=").append(id).append("]");
        return builder.toString();
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.insight</groupId>
    <artifactId>insight</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>insight</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
         </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>1.3.6.RELEASE</version>
         </dependency>
         <dependency>
            <groupId>org.passay</groupId>
            <artifactId>passay</artifactId>
            <version>1.0</version>
         </dependency>
         <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
         </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

CustomUserDetailsService

package com.insight.services;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.insight.models.Permission;
import com.insight.models.Role;
import com.insight.models.User;
import com.insight.repositories.RoleRepository;
import com.insight.repositories.UserRepository;

@Service("userDetailsService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IUserService service;
    @Autowired
    private MessageSource messages;
    @Autowired
    private RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(email);
        if (user == null) {
            return new org.springframework.security.core.userdetails.User(
              " ", " ", true, true, true, true,
              getAuthorities(Arrays.asList(roleRepository.findByName("ROLE_USER"))));
        }

        return new org.springframework.security.core.userdetails.User(
          user.getEmail(), user.getPassword(), user.isEnabled(), true, true,
          true, getAuthorities(user.getRoles()));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {
        return getGrantedAuthorities(getPrivileges(roles));
    }

    private List<String> getPrivileges(Collection<Role> roles) {
        List<String> privileges = new ArrayList<String>();
        List<Permission> collection = new ArrayList<Permission>();
        for (Role role : roles) {
            collection.addAll(role.getPermissions());
        }
        for (Permission item : collection) {
            privileges.add(item.getName());
        }
        return privileges;
    }

    private List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        return authorities;
    }
}

There some etc. classes also there, but I am not posting due to large segment, if anyone requires specifics, I will post.

When I tried to run, I am getting following error on console:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.insight.SecurityConfiguration.userDetailsService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.insight.repositories.UserRepository com.insight.services.CustomUserDetailsService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#778bd3a2' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#778bd3a2': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
          at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
          at

Please friends help me.

Body:
As Michal pointed out, this is a DB problem -

Error creating bean with name 'entityManagerFactory' defined in class path resource[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is javax.persistence.PersistenceException:
[PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)

Your MySQL DB may not be running, or you may not have provided the datasource connection in the spring properties [I see you have a MySQL dependency reference]

For debugging or test cases you might try H2 -

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>test</scope>
</dependency>


来源: stackexchange

问:
Using Selenium in Python to click all buttons in a webpage
I am trying to click on all the buttons on a webpage. I'd like to be able to click them all.
webpage
i can click on one of them by using css selector

```<code>browser.find_element_by_css_selector('li.clickable_area:nth-child(1) > div:nth-child(3)').click()
</code>```

these are the css selector for the 5 buttons

the 5 buttons follow this pattern:

Button 1: li.clickable_area: nth - child(1) > div:nth - child(3)

Button 2: li.clickable_area: nth - child(2) > div:nth - child(3)

Button 3: li.clickable_area: nth - child(3) > div:nth - child(3)

Button 4: li.clickable_area: nth - child(4) > div:nth - child(3)

Button 5: li.clickable_area: nth - child(5) > div:nth - child(3)

How i can i click them all using css selector without writing a code for each one?

答:
You can use the loop to iterate through and click on the number of buttons.

```<code>number_of_buttons = 5
for x in range(number_of_buttons):
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()
</code>```

If you want to click on all the li(x) > div:nth-child(3) then you can use the below.

```<code>number_li_elems=len(WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area"))))
for x in range(number_li_elems):
    # you have to get the element by index every time, otherwise you will get StaleElement Exception
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to click on all the buttons on a webpage. I'd like to be able to click them all.
webpage
i can click on one of them by using css selector

browser.find_element_by_css_selector('li.clickable_area:nth-child(1) > div:nth-child(3)').click()

these are the css selector for the 5 buttons

the 5 buttons follow this pattern:

Button 1: li.clickable_area: nth - child(1) > div:nth - child(3)

Button 2: li.clickable_area: nth - child(2) > div:nth - child(3)

Button 3: li.clickable_area: nth - child(3) > div:nth - child(3)

Button 4: li.clickable_area: nth - child(4) > div:nth - child(3)

Button 5: li.clickable_area: nth - child(5) > div:nth - child(3)

How i can i click them all using css selector without writing a code for each one?

Body:
You can use the loop to iterate through and click on the number of buttons.

number_of_buttons = 5
for x in range(number_of_buttons):
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()

If you want to click on all the li(x) > div:nth-child(3) then you can use the below.

number_li_elems=len(WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area"))))
for x in range(number_li_elems):
    # you have to get the element by index every time, otherwise you will get StaleElement Exception
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()


问:
Error: Not an enclosing class - MainActivity
public class Splash extends AppCompatActivity {

```<code>@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.lactivity_main);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
</code>```

}

class Logoutluncher  extends Thread{

```<code>@Override
public void run() {
    try {
        sleep(1000);
    }catch (InterruptedException e){
        e.printStackTrace();

    }Intent myIntent = new Intent(MainActivity.this, MainActivity.class);
    startActivity(myIntent);

}
</code>```

}

答:
Using MainActivity.this is referring to the object MainActivity as if it were the current object but the current object is of type Logoutluncher.

Translating "not an enclosing class" would be "not an engaging class" .

To have MainActivity.this valid within the Logoutluncher class, MainActivity must "wrap" the Logoutluncher class, in Logoutluncher must be an inner MainActivity class.

Body:
public class Splash extends AppCompatActivity {

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.lactivity_main);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

}

class Logoutluncher  extends Thread{

@Override
public void run() {
    try {
        sleep(1000);
    }catch (InterruptedException e){
        e.printStackTrace();

    }Intent myIntent = new Intent(MainActivity.this, MainActivity.class);
    startActivity(myIntent);

}

}


问:
HttpUrlConnection.connect fails
I've been trying to create a small app that connects to url in editText and returns the status code.

Here is the onCreate code:

```<code> override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button.setOnClickListener {
        val url = editText.text.toString()
        var connection: HttpURLConnection? = null
        if (URLUtil.isValidUrl(url)) {
            connection = URL(url).openConnection() as HttpURLConnection
            var thr = Thread {
                connection.connect()
                val code = connection.responseCode
                runOnUiThread {
                    if (code != 404 && code != 500) {
                        textView.text = "Ok"
                    } else {
                        textView.text = "Failed"
                    }
                }

            }
            thr.start()
            thr.join()
        } else {
            textView.text = "Failed"
        }
    }
</code>```

The problem is that whenever URL is valid, runtime error occurs in .connect() method. Internet permission is set up in android manifest. What causes that issue?

```<code>E/AndroidRuntime: FATAL EXCEPTION: Thread-2
Process: com.example.company.myapplication, PID: 27183
java.net.SocketException: socket failed: EPERM (Operation not permitted)
    at java.net.Socket.createImpl(Socket.java:492)
    at java.net.Socket.getImpl(Socket.java:552)
    at java.net.Socket.setSoTimeout(Socket.java:1180)
    at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
    at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
    at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
    at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
    at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
    at com.example.company.myapplication.MainActivity$onCreate$1$thr$1.run(MainActivity.kt:25)
    at java.lang.Thread.run(Thread.java:919)
</code>```

答:
For those who didn't read chat:

URLUtil.isValidUrl(url) doesn't check that the url in question actually can be resolved to a website/server. This means that when connect is called on a website/server that doesn't exist, an exception is thrown, since there is nothing to connect to.

Title: HttpUrlConnection.connect fails

Body:
I've been trying to create a small app that connects to url in editText and returns the status code.

Here is the onCreate code:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button.setOnClickListener {
        val url = editText.text.toString()
        var connection: HttpURLConnection? = null
        if (URLUtil.isValidUrl(url)) {
            connection = URL(url).openConnection() as HttpURLConnection
            var thr = Thread {
                connection.connect()
                val code = connection.responseCode
                runOnUiThread {
                    if (code != 404 && code != 500) {
                        textView.text = "Ok"
                    } else {
                        textView.text = "Failed"
                    }
                }

            }
            thr.start()
            thr.join()
        } else {
            textView.text = "Failed"
        }
    }

The problem is that whenever URL is valid, runtime error occurs in .connect() method. Internet permission is set up in android manifest. What causes that issue?

E/AndroidRuntime: FATAL EXCEPTION: Thread-2
Process: com.example.company.myapplication, PID: 27183
java.net.SocketException: socket failed: EPERM (Operation not permitted)
    at java.net.Socket.createImpl(Socket.java:492)
    at java.net.Socket.getImpl(Socket.java:552)
    at java.net.Socket.setSoTimeout(Socket.java:1180)
    at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
    at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
    at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
    at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
    at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
    at com.example.company.myapplication.MainActivity$onCreate$1$thr$1.run(MainActivity.kt:25)
    at java.lang.Thread.run(Thread.java:919)


问:
regex with 'Named Capture Group' to catch a pattern or an alternate one
I try to catch with one unique regex

```<code>either: ' PIC S9(17).'            # with 'S9(17)'      in Named Capture Group pic
either: ' PIC S9(13)V9(2).'       # with 'S9(13)V9(2)' in Named Capture Group pic
either: ' PIC S9(9)V9(2) COMP-3.' # with 'S9(9)V9(2)'  in Named Capture Group pic
either: ' PIC X(16).'             # with 'X(16)'       in Named Capture Group pic
</code>```

with r'\s*PIC\s+(?P<pic>\S+)'
  I catch all but ' PIC S9(9)V9(2) COMP-3.'

with r'\s*PIC\s+(?P<pic>\S+) COMP-3'
  I catch only ' PIC S9(9)V9(2) COMP-3.'

This is my Python code:

```<code>import re
def get_pics(data, pic):
    base = r'^(?P<level>\d{2})\s+(?P<name>\S+)'
    end = r'\.$'
    pformat = "({})?"
    pattern = re.compile(base + pformat.format(pic) + end)

    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""
</code>```

So we get:

```<code>>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+)')
ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL  PIC S9(9)V9(2) COMP-3.
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>
</code>```

or

```<code>>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+) COMP-3')
 => NOP:
     12 M-AR03-MONTANT-RDJ         PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ       PIC X(8).
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL  PIC X(5).
>>>
</code>```

What is strange is that in https://regex101.com/ the '\s*PIC\s+(?P<pic>\S+)'
match for all 4 lines:

```<code>PIC S9(17).
PIC S9(13)V9(2).
PIC S9(9)V9(2) COMP-3.
PIC X(16).
</code>```

If I try the @the-fourth-bird regex I get:

```<code>In [2]: get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
   ...:
 => NOP:
     12 M-AR03-MONTANT-RDJ          PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ           PIC X(8).
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL    PIC S9(9)V9(2) COMP-3.
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL      PIC X(5).

In [3]:
</code>```

答:
I modified your base pattern to include whitespace at the end and crafted a different pattern for pic.

```<code>pat2 = r'(?P<level>\d{2})\s+(?P<name>\S+)\s+'
picpat = r'PIC\s(?P<pic>[^.\s]+)'
</code>```

picpat matches anything after 'PIC ' till it gets to a dot or whitespace.

I changed the function a bit using an f-string to combine it with the pic pattern, iterating over matches instead of lines.

```<code>def get_pics(data,pic):
    pat2 = r'(?P<level>\d{2})\s+(?P<name>\S+)\s+'
    pattern = f'{pat2}{pic}'
    #pattern = '{}{}'.format(pat2,pic)
    pattern = re.compile(pattern)
    for match in pattern.finditer(data):
        print(match.groupdict())

>>> get_pics(data,picpat)
{'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
{'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
{'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
{'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>
</code>```

Body:
I try to catch with one unique regex

either: ' PIC S9(17).'            # with 'S9(17)'      in Named Capture Group pic
either: ' PIC S9(13)V9(2).'       # with 'S9(13)V9(2)' in Named Capture Group pic
either: ' PIC S9(9)V9(2) COMP-3.' # with 'S9(9)V9(2)'  in Named Capture Group pic
either: ' PIC X(16).'             # with 'X(16)'       in Named Capture Group pic

with r'\s*PIC\s+(?P<pic>\S+)'
  I catch all but ' PIC S9(9)V9(2) COMP-3.'

with r'\s*PIC\s+(?P<pic>\S+) COMP-3'
  I catch only ' PIC S9(9)V9(2) COMP-3.'

This is my Python code:

import re
def get_pics(data, pic):
    base = r'^(?P<level>\d{2})\s+(?P<name>\S+)'
    end = r'\.$'
    pformat = "({})?"
    pattern = re.compile(base + pformat.format(pic) + end)

    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""

So we get:

>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+)')
ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL  PIC S9(9)V9(2) COMP-3.
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>

or

>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+) COMP-3')
 => NOP:
     12 M-AR03-MONTANT-RDJ         PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ       PIC X(8).
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL  PIC X(5).
>>>

What is strange is that in https://regex101.com/ the '\s*PIC\s+(?P<pic>\S+)'
match for all 4 lines:

PIC S9(17).
PIC S9(13)V9(2).
PIC S9(9)V9(2) COMP-3.
PIC X(16).

If I try the @the-fourth-bird regex I get:

In [2]: get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
   ...:
 => NOP:
     12 M-AR03-MONTANT-RDJ          PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ           PIC X(8).
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL    PIC S9(9)V9(2) COMP-3.
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL      PIC X(5).

In [3]:

Body:
I modified your base pattern to include whitespace at the end and crafted a different pattern for pic.

pat2 = r'(?P<level>\d{2})\s+(?P<name>\S+)\s+'
picpat = r'PIC\s(?P<pic>[^.\s]+)'

picpat matches anything after 'PIC ' till it gets to a dot or whitespace.

I changed the function a bit using an f-string to combine it with the pic pattern, iterating over matches instead of lines.

def get_pics(data,pic):
    pat2 = r'(?P<level>\d{2})\s+(?P<name>\S+)\s+'
    pattern = f'{pat2}{pic}'
    #pattern = '{}{}'.format(pat2,pic)
    pattern = re.compile(pattern)
    for match in pattern.finditer(data):
        print(match.groupdict())

>>> get_pics(data,picpat)
{'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
{'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
{'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
{'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>


问:
Assigning column name as cell value if column contains specific value
I am pretty new to R. I have a data frame with pairs of admission and discharge variables that should match e.g.:

```<code>  V1adm V1dis V2adm V2dis V3adm V3dis
1   120   120   yes   yes    60    60
2   110   110   yes  <NA>    40    40
3    60    NA    no  <NA>    NA    NA
4    90    NA  <NA>    no    20    NA
</code>```

I have created a data frame with TRUE if either one of the variable pairs is missing:

```<code># Variable names
adm_vars<- c("V1adm", "V2adm", "V3adm")
dis_vars<- c("V1dis", "V2dis", "V3dis")

# Create empty dataframe
pairs_NA<- matrix(NA, ncol=3, nrow=nrow(data))
pairs_NA<- as.data.frame(pairs_NA)
names(pairs_NA)<- paste(adm_vars, dis_vars, sep = '_')

# Add TRUE if adm OR dis variable NA
for(i in 1:3){
  x<- data[, adm_vars[i]]
  y<- data[, dis_vars[i]]
  pairs_NA[,i]<- is.na(x) | is.na(y)
}

  V1adm_V1dis V2adm_V2dis V3adm_V3dis
1       FALSE       FALSE       FALSE
2       FALSE        TRUE       FALSE
3        TRUE        TRUE        TRUE
4        TRUE        TRUE        TRUE
</code>```

For the rows where all 3 are missing, I would like to create a data frame that takes the column name from 'pairs_NA' as the cell value if that pair is missing (i.e. column is TRUE in pairs_NA). It should look something like this:

```<code>              1             2             3
3   V1adm_V1dis   V2adm_V2dis   V3adm_V3dis
4   V1adm_V1dis   V2adm_V2dis   V3adm_V3dis

</code>```

Is there a way I can assign the column name of 'pairs_NA' as the cell value if there is a 'TRUE' in that column for each specific row?

答:
We can create a logical index based on rowSums and replicate the column names of 'pairs_NA' after subsetting the rows where all the values are TRUE

```<code>i1 <- rowSums(pairs_NA) == ncol(pairs_NA)
matrix(names(pairs_NA)[col(pairs_NA[i1,])], ncol = ncol(pairs_NA))
#    [,1]          [,2]          [,3]
#[1,] "V1adm_V1dis" "V2adm_V2dis" "V3adm_V3dis"
#[2,] "V1adm_V1dis" "V2adm_V2dis" "V3adm_V3dis"
</code>```

Body:
I am pretty new to R. I have a data frame with pairs of admission and discharge variables that should match e.g.:

  V1adm V1dis V2adm V2dis V3adm V3dis
1   120   120   yes   yes    60    60
2   110   110   yes  <NA>    40    40
3    60    NA    no  <NA>    NA    NA
4    90    NA  <NA>    no    20    NA

I have created a data frame with TRUE if either one of the variable pairs is missing:

# Variable names
adm_vars<- c("V1adm", "V2adm", "V3adm")
dis_vars<- c("V1dis", "V2dis", "V3dis")

# Create empty dataframe
pairs_NA<- matrix(NA, ncol=3, nrow=nrow(data))
pairs_NA<- as.data.frame(pairs_NA)
names(pairs_NA)<- paste(adm_vars, dis_vars, sep = '_')

# Add TRUE if adm OR dis variable NA
for(i in 1:3){
  x<- data[, adm_vars[i]]
  y<- data[, dis_vars[i]]
  pairs_NA[,i]<- is.na(x) | is.na(y)
}

  V1adm_V1dis V2adm_V2dis V3adm_V3dis
1       FALSE       FALSE       FALSE
2       FALSE        TRUE       FALSE
3        TRUE        TRUE        TRUE
4        TRUE        TRUE        TRUE

For the rows where all 3 are missing, I would like to create a data frame that takes the column name from 'pairs_NA' as the cell value if that pair is missing (i.e. column is TRUE in pairs_NA). It should look something like this:

              1             2             3
3   V1adm_V1dis   V2adm_V2dis   V3adm_V3dis
4   V1adm_V1dis   V2adm_V2dis   V3adm_V3dis

Is there a way I can assign the column name of 'pairs_NA' as the cell value if there is a 'TRUE' in that column for each specific row?

Body:
We can create a logical index based on rowSums and replicate the column names of 'pairs_NA' after subsetting the rows where all the values are TRUE

i1 <- rowSums(pairs_NA) == ncol(pairs_NA)
matrix(names(pairs_NA)[col(pairs_NA[i1,])], ncol = ncol(pairs_NA))
#    [,1]          [,2]          [,3]
#[1,] "V1adm_V1dis" "V2adm_V2dis" "V3adm_V3dis"
#[2,] "V1adm_V1dis" "V2adm_V2dis" "V3adm_V3dis"


问:
Pathfinding between obstacles that sit on top of walkable tiles
Take the below picture as an example. Consider the following -

Blue square is the player

Orange square is the first destination

Pink square is the second destination

Green squares are walkable tiles

Black squares are walls / obstacles on top of a walkable tile

Each tile is 4x4

The intended behavior here is -

Walking to the orange square results in a straight downwards line

Walking to the pink square (from the blue square) walks around the black squares in close proximity

My current implementation takes a grid of tiles and hands it off to a typical A* algorithm for the shortest path to each square. However, just because a tile has a wall on it does not mean it's unwalkable - it should mean that the generated path does not clip through an object.

That being said, the current implementation results in this as I have no choice but to stick to a 4x4 grid of tiles, and without marking the entire tile as unwalkable, it'll clip through objects. Red tiles being unwalkable.

Which provides a very janky pathfinding system as it'll skip perfectly fine tiles (indicated in red). My question is, how do I make it so the walls aren't clippable, but the tile they sit on is still walkable?

答:
Idea for a solution:

The first solution obviously would be to increase A* accuracy by having each tile of 1x1.

Another idea is to don't use a simple int grid (or similar) when checking if a tile is walkable.
Use instead a function or a more complex data structure that use starting and ending tile to know if that route is available. In such a scenario each 4x4 tile has four possible route (east, north, west, south) and for each one you must know if it is walkable. If you allowed diagonal movements than you would to store/compute 8 routes for tile.

I can't give you more detailed answers since you didn't showed anything of your implementation.

I hope I was helpful


问:
apply ngclass in mat-cell getting error angular 8
I am trying to use ngclass for my condition to apply css for the below html code but it was showing error.

I want to use two class that is colorRed & colorOrange

Here is my Two class (CSS)

```<code>    .colorRed{
        color:red;
    }
    .colorOrange{
        color: orange;
    }
</code>```

Here is condition

If percentage is  >=5% and <10%, show orange color

If percentage is  >=10% need to show red color

Here is my html

```<code>    <ng-container matColumnDef="salaryIncrease">
     <th mat-header-cell *matHeaderCellDef mat-sort-header> </th>
     <td mat-cell [ngClass]="{'colorRed': element.salaryIncrease>= 5% }" *matCellDef="let element" > {{element.salaryIncreas| currency:'':''}}
     </td>
    </ng-container>
</code>```

答:
You are getting template parse error because you are using % symbol during comparison and % symbol can't be used for comparing. Just compare values of percentage.

Also in standard scenario only value is stored for percentage values. % symbol is added only where needed

Working example for you

https://stackblitz.com/edit/angular-5fbpjc?embed=1&file=app/table-basic-example.html

Body:
I am trying to use ngclass for my condition to apply css for the below html code but it was showing error.

I want to use two class that is colorRed & colorOrange

Here is my Two class (CSS)

    .colorRed{
        color:red;
    }
    .colorOrange{
        color: orange;
    }

Here is condition

If percentage is  >=5% and <10%, show orange color

If percentage is  >=10% need to show red color

Here is my html

    <ng-container matColumnDef="salaryIncrease">

     = 5% }" *matCellDef="let element" > {{element.salaryIncreas| currency:'':''}}

    </ng-container>


问:
Get file path using drag and drop (Swift macOS)?
how to implement a drag-and-drop zone in swift 2.0?

I built an app that processes kext files but, for now, i have to manually enter the path to the input kext.
my question is: how to get file path by performing a drag and drop on a zone?

答:
This implementation allows for multiple files.

Just set the view class to DragView in Interface Builder, implement DragViewDelegate in your controller, then hook up the delegate outlet in Interface Builder. This way you get a delegate callback with the file URLs.

func dragViewDidReceive(fileURLs: [URL])
{
    // Yay!
}
```

<p><strong><code>DragView.swift</code></strong></p>

<pre class="lang-swift prettyprint-override"><code>//
//  DragView.swift
//
//  Copyright (c) 2020 Geri Borbás http://www.twitter.com/_eppz
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import Cocoa

@objc protocol DragViewDelegate
{

    func dragViewDidReceive(fileURLs: [URL])
}

class DragView: NSView
{

    @IBOutlet weak var delegate: DragViewDelegate?
    let fileExtensions = ["kext"]

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
        color(to: .clear)
        registerForDraggedTypes([.fileURL])
    }

    override func draggingEntered(_ draggingInfo: NSDraggingInfo) -> NSDragOperation
    {
        var containsMatchingFiles = false
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if let eachURL = eachObject as? URL
            {
                containsMatchingFiles = containsMatchingFiles || fileExtensions.contains(eachURL.pathExtension.lowercased())
                if containsMatchingFiles { print(eachURL.path) }
            }
        }

        switch (containsMatchingFiles)
        {
            case true:
                color(to: .secondaryLabelColor)
                return .copy
            case false:
                color(to: .disabledControlTextColor)
                return .init()
        }
    }

    override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool
    {
        // Collect URLs.
        var matchingFileURLs: [URL] = []
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if
                let eachURL = eachObject as? URL,
                fileExtensions.contains(eachURL.pathExtension.lowercased())
            { matchingFileURLs.append(eachURL) }
        }

        // Only if any,
        guard matchingFileURLs.count > 0
        else { return false }

        // Pass to delegate.
        delegate?.dragViewDidReceive(fileURLs: matchingFileURLs)
        return true
    }

    override func draggingExited(_ sender: NSDraggingInfo?)
    { color(to: .clear) }

    override func draggingEnded(_ sender: NSDraggingInfo)
    { color(to: .clear) }

}

extension DragView
{

    func color(to color: NSColor)
    {
        self.wantsLayer = true
        self.layer?.backgroundColor = color.cgColor
    }
}

</code>```

Body:
This implementation allows for multiple files.

Just set the view class to DragView in Interface Builder, implement DragViewDelegate in your controller, then hook up the delegate outlet in Interface Builder. This way you get a delegate callback with the file URLs.

func dragViewDidReceive(fileURLs: [URL])
{
    // Yay!
}

DragView.swift

//
//  DragView.swift
//
//  Copyright (c) 2020 Geri Borbás http://www.twitter.com/_eppz
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import Cocoa

@objc protocol DragViewDelegate
{

    func dragViewDidReceive(fileURLs: [URL])
}

class DragView: NSView
{

    @IBOutlet weak var delegate: DragViewDelegate?
    let fileExtensions = ["kext"]

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
        color(to: .clear)
        registerForDraggedTypes([.fileURL])
    }

    override func draggingEntered(_ draggingInfo: NSDraggingInfo) -> NSDragOperation
    {
        var containsMatchingFiles = false
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if let eachURL = eachObject as? URL
            {
                containsMatchingFiles = containsMatchingFiles || fileExtensions.contains(eachURL.pathExtension.lowercased())
                if containsMatchingFiles { print(eachURL.path) }
            }
        }

        switch (containsMatchingFiles)
        {
            case true:
                color(to: .secondaryLabelColor)
                return .copy
            case false:
                color(to: .disabledControlTextColor)
                return .init()
        }
    }

    override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool
    {
        // Collect URLs.
        var matchingFileURLs: [URL] = []
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if
                let eachURL = eachObject as? URL,
                fileExtensions.contains(eachURL.pathExtension.lowercased())
            { matchingFileURLs.append(eachURL) }
        }

        // Only if any,
        guard matchingFileURLs.count > 0
        else { return false }

        // Pass to delegate.
        delegate?.dragViewDidReceive(fileURLs: matchingFileURLs)
        return true
    }

    override func draggingExited(_ sender: NSDraggingInfo?)
    { color(to: .clear) }

    override func draggingEnded(_ sender: NSDraggingInfo)
    { color(to: .clear) }

}

extension DragView
{

    func color(to color: NSColor)
    {
        self.wantsLayer = true
        self.layer?.backgroundColor = color.cgColor
    }
}


问:
How can I delete a JS created LI with a JS created button?
I am creating a TODO app in JavaScript. How can I understand how to link two created JavaScript items and remove them from the DOM?

TL;DR: The place where I keep getting stuck is navigating the DOM after the list item has been created. I have tried to use a a setAttribute to the created elements with an incriminating "id" tag, but I still can figure out how to iterate over the LI's to find which button was pressed.

Code:

```<code>        <div class="entry-field">
          <label class="task-input" for="task-input">Task:</label>
          <input type="text" class="task-field" placeholder="Enter Item"/>
          <button class="add-btn">ADD</button>
        </div>
        <section class="task-list">
          <h2>Task List</h2>
          <div class="list-wrap"></div>
            <ul class="item-log">
              <li class="list-item">
                <span class="item-text">this is the item</span>
                <button class="delete-btn">delete</button>
              </li>
            </ul>
          </div>
        </section>
      </main>

JavaScript:
let index = 0;

//Obtaining user text, creating a Span element, append span with user text:
function addItem() {
  let itemLog = document.querySelector(".item-log");
  let listItem = document.createElement("LI");
  let deleteBtn = document.createElement("BUTTON");
  let userEntry = document.querySelector(".task-field").value;
  let spanItem = document.createElement("SPAN");
  index++;
  //Creating LI "list-item" and append UL "itemLog"
  itemLog.appendChild(listItem);
  listItem.classList.add("list-item");

  listItem.setAttribute("id", index);
  //Create Span element, assign text from user input, append LI
  spanItem.innerHTML = userEntry;
  listItem.appendChild(spanItem);
  //Create deleteBtn and append to LI
  deleteBtn.innerHTML = "Delete";
  deleteBtn.classList.add("delete-btn");
  deleteBtn.setAttribute("onclick", "deleteItem()");
  deleteBtn.setAttribute("id", index);
  listItem.appendChild(deleteBtn);

  userEntry.value = "";
}

/*
2) Deleting item from list:
  -use event listener to trigger parent node
  -delete child
  */

function deleteItem() {
  let listItem = this.parentElement;
  listItem.parentElement.removeChild(listItem);
}

// Page event listeners
let addBtn = document.querySelector(".add-btn");

addBtn.addEventListener("click", addItem);

</code>```

答:
The issue in your example is what this refers to  in your deleteItem function. If you console.log it in the deleteItem function you'll see that this refers to the window not the button pressed.

If instead of using setAttribute to set the onClick, you can add an event listener:
deleteBtn.addEventListener("click", deleteItem);

Inside the deleteItem function you'll have access to the event object, as well as the target of that event, and your code will work as expected.

```<code>function deleteItem(event) {
  let listItem = event.target.parentElement;
  listItem.parentElement.removeChild(listItem);
}
</code>```

Body:
I am creating a TODO app in JavaScript. How can I understand how to link two created JavaScript items and remove them from the DOM?

TL;DR: The place where I keep getting stuck is navigating the DOM after the list item has been created. I have tried to use a a setAttribute to the created elements with an incriminating "id" tag, but I still can figure out how to iterate over the LI's to find which button was pressed.

Code:

          Task:
          <input type="text" class="task-field" placeholder="Enter Item"/>
          <button class="add-btn">ADD</button>

Task List

                this is the item
                <button class="delete-btn">delete</button>

JavaScript:
let index = 0;

//Obtaining user text, creating a Span element, append span with user text:
function addItem() {
  let itemLog = document.querySelector(".item-log");
  let listItem = document.createElement("LI");
  let deleteBtn = document.createElement("BUTTON");
  let userEntry = document.querySelector(".task-field").value;
  let spanItem = document.createElement("SPAN");
  index++;
  //Creating LI "list-item" and append UL "itemLog"
  itemLog.appendChild(listItem);
  listItem.classList.add("list-item");

  listItem.setAttribute("id", index);
  //Create Span element, assign text from user input, append LI
  spanItem.innerHTML = userEntry;
  listItem.appendChild(spanItem);
  //Create deleteBtn and append to LI
  deleteBtn.innerHTML = "Delete";
  deleteBtn.classList.add("delete-btn");
  deleteBtn.setAttribute("onclick", "deleteItem()");
  deleteBtn.setAttribute("id", index);
  listItem.appendChild(deleteBtn);

  userEntry.value = "";
}

/*
2) Deleting item from list:
  -use event listener to trigger parent node
  -delete child
  */

function deleteItem() {
  let listItem = this.parentElement;
  listItem.parentElement.removeChild(listItem);
}

// Page event listeners
let addBtn = document.querySelector(".add-btn");

addBtn.addEventListener("click", addItem);

Body:
The issue in your example is what this refers to  in your deleteItem function. If you console.log it in the deleteItem function you'll see that this refers to the window not the button pressed.

If instead of using setAttribute to set the onClick, you can add an event listener:
deleteBtn.addEventListener("click", deleteItem);

Inside the deleteItem function you'll have access to the event object, as well as the target of that event, and your code will work as expected.

function deleteItem(event) {
  let listItem = event.target.parentElement;
  listItem.parentElement.removeChild(listItem);
}


问:
How to choose the rows where the first occurrence of a value happens with groupby in pandas and also the first of the consequent occurrences
I have a dataframe that looks like this:

```<code>import pandas as pd

df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,0,1,0,1,0,1]})
</code>```

This df is already order with respect to id & time.

I would like to keep only the rows where taken has value 1 by id, and if there are two (or more) consequent 1s in the column taken to keep only the first of these.

My output df should like this:

```<code>  id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1
</code>```

Second example

To make the question a bit more clear, if the dataframe looks like this:

```<code>df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,1,1,1,1,0,1]})
</code>```

Then the output dataframe should look like this:

```<code>   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1
</code>```

Any ideas on how to do this ?

答:
Here's one approach:

```<code>taken_is_one = df.taken.eq(1)
df[taken_is_one & (~taken_is_one.shift(-1, fill_value=False)
                | df.groupby('id').id.shift(1).isna())]

   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1
</code>```

Where with:

```<code>~taken_is_one.shift(-1, fill_value=False)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7    False
8     True
</code>```

We will have True only if the next value in taken was not a 1, hence by combining with a & we can index on both conditions being True.

Body:
I have a dataframe that looks like this:

import pandas as pd

df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,0,1,0,1,0,1]})

This df is already order with respect to id & time.

I would like to keep only the rows where taken has value 1 by id, and if there are two (or more) consequent 1s in the column taken to keep only the first of these.

My output df should like this:

  id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1

Second example

To make the question a bit more clear, if the dataframe looks like this:

df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,1,1,1,1,0,1]})

Then the output dataframe should look like this:

   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1

Any ideas on how to do this ?

Body:
Here's one approach:

taken_is_one = df.taken.eq(1)
df[taken_is_one & (~taken_is_one.shift(-1, fill_value=False)
                | df.groupby('id').id.shift(1).isna())]

   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1

Where with:

~taken_is_one.shift(-1, fill_value=False)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7    False
8     True

We will have True only if the next value in taken was not a 1, hence by combining with a & we can index on both conditions being True.


问:
C# UDP Socket.ReceiveFrom() breaks loop without exeption
I'm trying to make a game using sockets and UDP, i made a server class where when i call the start method i run a task with a loop to receive packets and process them, i used Socket.ReceiveFrom(packet, ref sender); inside a try catch block with everything inside a while loop, first i forgot to add Socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25000)); so i got a loop of bind exeptions which is normal but now that i added this line my program is freaking out see the code bellow

```<code>    public class UDPServer
    {
        public UDPServer()
        {
            Socket = new Socket(AddressFamily.InterNetwork ,SocketType.Dgram,ProtocolType.Udp);
            Socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25000));
        }

        public void Start()
        {
            IsBound = true;

            try
            {
                Task.Run(NetworkLoop);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private void NetworkLoop()
        {
            EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            byte[] packet = new byte[1];
            int dataSize = 0;

            while (IsBound)
            {
                try
                {
                    dataSize = Socket.ReceiveFrom(packet, ref sender);
                    Console.WriteLine(sender.ToString() + " with " + packet.Length + " of " + dataSize);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Reading exeption : " + e.Message);
                }
            }
        }
    }
</code>```

I debugged this and it seems that now when going step by step to the line
dataSize = Socket.ReceiveFrom(packet, ref sender); it just both exit the try catch block without any exeption catched AND breaks the while loop...

Is this normal behaviour ??

答:
Your UDPServer.Start() method is not blocking, because Task.Run will run asynchronously.

Task.Run(NetworkLoop); // This is non-blocking
```

<p>Your UDP server will work by either:
</p>

```Task.Run(NetworkLoop).Wait(); // This is blocking
```

<p>or </p>

<pre class="lang-cs prettyprint-override"><code>new UDPServer().Start();

Console.WriteLine("Press <enter> key to stop UDP server...");
Console.ReadLine(); // This block until user hit <enter> key
</code>```

Body:
I'm trying to make a game using sockets and UDP, i made a server class where when i call the start method i run a task with a loop to receive packets and process them, i used Socket.ReceiveFrom(packet, ref sender); inside a try catch block with everything inside a while loop, first i forgot to add Socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25000)); so i got a loop of bind exeptions which is normal but now that i added this line my program is freaking out see the code bellow

    public class UDPServer
    {
        public UDPServer()
        {
            Socket = new Socket(AddressFamily.InterNetwork ,SocketType.Dgram,ProtocolType.Udp);
            Socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25000));
        }

        public void Start()
        {
            IsBound = true;

            try
            {
                Task.Run(NetworkLoop);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private void NetworkLoop()
        {
            EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            byte[] packet = new byte[1];
            int dataSize = 0;

            while (IsBound)
            {
                try
                {
                    dataSize = Socket.ReceiveFrom(packet, ref sender);
                    Console.WriteLine(sender.ToString() + " with " + packet.Length + " of " + dataSize);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Reading exeption : " + e.Message);
                }
            }
        }
    }

I debugged this and it seems that now when going step by step to the line
dataSize = Socket.ReceiveFrom(packet, ref sender); it just both exit the try catch block without any exeption catched AND breaks the while loop...

Is this normal behaviour ??

Body:
Your UDPServer.Start() method is not blocking, because Task.Run will run asynchronously.

Task.Run(NetworkLoop); // This is non-blocking

Your UDP server will work by either:

Task.Run(NetworkLoop).Wait(); // This is blocking

or

new UDPServer().Start();

Console.WriteLine("Press <enter> key to stop UDP server...");
Console.ReadLine(); // This block until user hit <enter> key