问:
Spring security returns error, even when I entered valid data
I'm using spring data, spring mvc, spring core, spring security, maven, tomcat, mysql.

I'm learning Spring Security and I'm trying to create an app (registration + login).

Registration is working, but login page returns error even when I enter valid data.

I don't know why it isn't working. Thanks for help!

My code:

```<code>repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @Query("from User where username=:username")
    public User findByUserName(@Param("username")String username);

}

@Repository
public interface RoleRepository extends JpaRepository<Role, Long>{

    @Query("from Role where name=:name")
    public Role findByRoleName(@Param("name")String name);
}

entity:

package com.myapp.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Role {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private Long rid;

    @Column
    private String name;

    public Role() {
    }

    public Role(Long rid, String name) {
        super();
        this.rid = rid;
        this.name = name;
    }

    public Long getRid() {
        return rid;
    }

    public void setRid(Long rid) {
        this.rid = rid;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Role [rid=" + rid + ", name=" + name + "]";
    }

}

@Entity
@Table
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private Long uid;

    @Column
    private String username;

    @Column
    private String password;

    @ManyToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
    @JoinTable
    (name="users_roles",
    joinColumns=@JoinColumn(name="user_id", referencedColumnName="uid"),
    inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="rid"))
    private Collection<Role>roles;

    public User() {
    }

    public User(Long uid, String username, String password, Collection<Role> roles) {
        super();
        this.uid = uid;
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    public Long getUid() {
        return uid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

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

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

    @Override
    public String toString() {
        return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", roles=" + roles + "]";
    }

}

service:

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private RoleRepository roleRepo;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user =userRepo.findByUserName(username);

        if(user==null)
        {
            System.out.println("USER WAS NOT FOUND");
            throw new UsernameNotFoundException("Invalid username or password");
        }
        System.out.println("USER REPO RETURN: L: "+user.getUsername()+" P: "+user.getPassword());

        System.out.println(user.getUsername()+ user.getPassword());

        org.springframework.security.core.userdetails.User userDetails= new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(),
                user.getRoles().stream().map(r->new SimpleGrantedAuthority(r.getName())).collect(Collectors.toList()));
        return userDetails;

    }

    @Override
    @Transactional
    public User findByUserName(String name) {
        return userRepo.findByUserName(name);
    }

    @Override
    @Transactional
    public void save(User user)
    {
        User protectedUser=new User();
        Set<Role>roles=new HashSet<>();
        roles.add(roleRepo.findByRoleName("ROLE_EMPLOYEE"));
        protectedUser.setUsername(user.getUsername());
        protectedUser.setPassword(passwordEncoder.encode(user.getPassword()));      protectedUser.setRoles(roles);
        userRepo.save(protectedUser);
    }

}

public interface UserService extends UserDetailsService{

    public User findByUserName(String username);

    public void save(User user);
}

Config:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{

}

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserService userService;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    /*
    @Autowired
    private CustomAuthenticationProvider ownProvider;
    */

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/").hasRole("EMPLOYEE")
        .and()
        .formLogin()
        .loginPage("/showMyLoginPage")
        .loginProcessingUrl("/authenticateTheUser")
        .successHandler(customAuthenticationSuccessHandler)
        .permitAll()
        .and()
        .logout().permitAll()
        .and()
        .exceptionHandling().accessDeniedPage("/denied-page");
    }

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

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }

}

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[] {};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[] {WebMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        return new String[] {"/"};
    }

}

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.myapp"})
public class WebMvcConfig implements WebMvcConfigurer{

    @Bean
    public InternalResourceViewResolver viewResolver()
    {
        InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
        .addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    }

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator=new LocalValidatorFactoryBean();
        return validator;

    }

}

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name=authentication.getName();
        String password=authentication.getCredentials().toString();

        System.out.println("CUSTOM AUTHENTICATION PROVIDER : NAME: "+name+" Password: "+password);
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        System.out.println("\n\nIn customAuthenticationSuccessHandler\n\n");

        String userName = authentication.getName();

        System.out.println("userName=" + userName);

        User theUser = userService.findByUserName(userName);
        HttpSession session = request.getSession();
        session.setAttribute("user", theUser);

        response.sendRedirect(request.getContextPath() + "/");
    }

}

controllers:

@Controller
public class LoginController {

    @GetMapping("/showMyLoginPage")
    public String showMyLoginPage()
    {
        return "login-page";
    }

}

@Controller
public class MainController {

    @GetMapping("/")
    public String home()
    {
        return "home";
    }

    @GetMapping("/system")
    public String system()
    {
        return "system";
    }
}

@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;

    @GetMapping("/showRegisterForm")
    public String showRegisterForm(Model model)
    {
        User user=new User();
        model.addAttribute(user);
        return "register-form";
    }

    @PostMapping("/saveUser")
    public String saveUser(@ModelAttribute("user") User user)
    {
        userService.save(user);
        return "register-confirmation";
    }

}

</code>```

and jsp:

```<code>login:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="post" action="${pageContext.request.contextPath}/authenticateTheUser">

    <c:if test="${param.error != null}">
    <i style="color:red;">Sorry! You entered invalid date.</i>
    </c:if>

    <p>User name: <input type="text" name="username"/> </p>
    <p>Password: <input type="password" name="password"/> </p>

    <input type="submit" value="Login"/>
</form:form>

Register here! <a href="${pageContext.request.contextPath}/register/showRegisterForm" > Register now!</a>

</body>
</html>

register:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration form</title>
</head>
<body>

<form:form action="${pageContext.request.contextPath}/register/saveUser" modelAttribute="user">

Name: <form:input path="username"/>

Password <form:password path="password"/>

<button type="submit">Register</button>
</form:form>

</body>
</html>

</code>```

答:
I think that you should read documentation here:
Spring security on baeldung

And that quick fix may be to add in your

```<code>CustomAuthenticationProvider
</code>```

in method

```<code>authenticate
</code>```

some code like this:

```<code>if (shouldAuthenticateAgainstThirdPartySystem()) {

        // use the credentials
        // and authenticate against the third-party system
        return new UsernamePasswordAuthenticationToken(
          name, password, new ArrayList<>());
    } else {
        return null;
    }
</code>```

Because I understand that you never authenticate a user.

Body:
I'm using spring data, spring mvc, spring core, spring security, maven, tomcat, mysql.

I'm learning Spring Security and I'm trying to create an app (registration + login).

Registration is working, but login page returns error even when I enter valid data.

I don't know why it isn't working. Thanks for help!

My code:

repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @Query("from User where username=:username")
    public User findByUserName(@Param("username")String username);

}

@Repository
public interface RoleRepository extends JpaRepository<Role, Long>{

    @Query("from Role where name=:name")
    public Role findByRoleName(@Param("name")String name);
}

entity:

package com.myapp.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Role {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private Long rid;

    @Column
    private String name;

    public Role() {
    }

    public Role(Long rid, String name) {
        super();
        this.rid = rid;
        this.name = name;
    }

    public Long getRid() {
        return rid;
    }

    public void setRid(Long rid) {
        this.rid = rid;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Role [rid=" + rid + ", name=" + name + "]";
    }

}

@Entity
@Table
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private Long uid;

    @Column
    private String username;

    @Column
    private String password;

    @ManyToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
    @JoinTable
    (name="users_roles",
    joinColumns=@JoinColumn(name="user_id", referencedColumnName="uid"),
    inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="rid"))
    private Collection<Role>roles;

    public User() {
    }

    public User(Long uid, String username, String password, Collection<Role> roles) {
        super();
        this.uid = uid;
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    public Long getUid() {
        return uid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

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

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

    @Override
    public String toString() {
        return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", roles=" + roles + "]";
    }

}

service:

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private RoleRepository roleRepo;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user =userRepo.findByUserName(username);

        if(user==null)
        {
            System.out.println("USER WAS NOT FOUND");
            throw new UsernameNotFoundException("Invalid username or password");
        }
        System.out.println("USER REPO RETURN: L: "+user.getUsername()+" P: "+user.getPassword());

        System.out.println(user.getUsername()+ user.getPassword());

        org.springframework.security.core.userdetails.User userDetails= new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(),
                user.getRoles().stream().map(r->new SimpleGrantedAuthority(r.getName())).collect(Collectors.toList()));
        return userDetails;

    }

    @Override
    @Transactional
    public User findByUserName(String name) {
        return userRepo.findByUserName(name);
    }

    @Override
    @Transactional
    public void save(User user)
    {
        User protectedUser=new User();
        Set<Role>roles=new HashSet<>();
        roles.add(roleRepo.findByRoleName("ROLE_EMPLOYEE"));
        protectedUser.setUsername(user.getUsername());
        protectedUser.setPassword(passwordEncoder.encode(user.getPassword()));      protectedUser.setRoles(roles);
        userRepo.save(protectedUser);
    }

}

public interface UserService extends UserDetailsService{

    public User findByUserName(String username);

    public void save(User user);
}

Config:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{

}

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserService userService;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    /*
    @Autowired
    private CustomAuthenticationProvider ownProvider;
    */

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/").hasRole("EMPLOYEE")
        .and()
        .formLogin()
        .loginPage("/showMyLoginPage")
        .loginProcessingUrl("/authenticateTheUser")
        .successHandler(customAuthenticationSuccessHandler)
        .permitAll()
        .and()
        .logout().permitAll()
        .and()
        .exceptionHandling().accessDeniedPage("/denied-page");
    }

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

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }

}

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[] {};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[] {WebMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        return new String[] {"/"};
    }

}

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.myapp"})
public class WebMvcConfig implements WebMvcConfigurer{

    @Bean
    public InternalResourceViewResolver viewResolver()
    {
        InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
        .addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    }

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator=new LocalValidatorFactoryBean();
        return validator;

    }

}

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name=authentication.getName();
        String password=authentication.getCredentials().toString();

        System.out.println("CUSTOM AUTHENTICATION PROVIDER : NAME: "+name+" Password: "+password);
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        System.out.println("\n\nIn customAuthenticationSuccessHandler\n\n");

        String userName = authentication.getName();

        System.out.println("userName=" + userName);

        User theUser = userService.findByUserName(userName);
        HttpSession session = request.getSession();
        session.setAttribute("user", theUser);

        response.sendRedirect(request.getContextPath() + "/");
    }

}

controllers:

@Controller
public class LoginController {

    @GetMapping("/showMyLoginPage")
    public String showMyLoginPage()
    {
        return "login-page";
    }

}

@Controller
public class MainController {

    @GetMapping("/")
    public String home()
    {
        return "home";
    }

    @GetMapping("/system")
    public String system()
    {
        return "system";
    }
}

@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;

    @GetMapping("/showRegisterForm")
    public String showRegisterForm(Model model)
    {
        User user=new User();
        model.addAttribute(user);
        return "register-form";
    }

    @PostMapping("/saveUser")
    public String saveUser(@ModelAttribute("user") User user)
    {
        userService.save(user);
        return "register-confirmation";
    }

}

and jsp:

login:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

<form:form method="post" action="${pageContext.request.contextPath}/authenticateTheUser">

    <c:if test="${param.error != null}">
    Sorry! You entered invalid date.
    </c:if>

User name: <input type="text" name="username"/>

Password: <input type="password" name="password"/>

    <input type="submit" value="Login"/>
</form:form>

Register here!  Register now!

register:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Registration form</title>

<form:form action="${pageContext.request.contextPath}/register/saveUser" modelAttribute="user">

Name: <form:input path="username"/>

Password <form:password path="password"/>

<button type="submit">Register</button>
</form:form>

Body:
I think that you should read documentation here:
Spring security on baeldung

And that quick fix may be to add in your

CustomAuthenticationProvider

in method

authenticate

some code like this:

if (shouldAuthenticateAgainstThirdPartySystem()) {

        // use the credentials
        // and authenticate against the third-party system
        return new UsernamePasswordAuthenticationToken(
          name, password, new ArrayList<>());
    } else {
        return null;
    }

Because I understand that you never authenticate a user.


来源: stackexchange

问:
How can I add shadow to the widget in flutter?
How can I add shadow to the widget like in the picture below?

This is my current widget code.

答:
Use Material with shadowColor inside Container like this:</p>
```<code>Container(
  decoration: BoxDecoration(
      borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(10),
          bottomRight: Radius.circular(10)),
      boxShadow: [
        BoxShadow(
            color: Color(0xffA22447).withOpacity(.05),
            offset: Offset(0, 0),
            blurRadius: 20,
            spreadRadius: 3)
      ]),
  child: Material(
    borderRadius: BorderRadius.only(
        bottomLeft: Radius.circular(10),
        bottomRight: Radius.circular(10)),
    elevation: 5,
    shadowColor: Color(0xffA22447).withOpacity(.05),
    color: Color(0xFFF7F7F7),
    child: SizedBox(
      height: MediaQuery.of(context).size.height / 3,
    ),
  ),
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use Material with shadowColor inside Container like this:

Container(
  decoration: BoxDecoration(
      borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(10),
          bottomRight: Radius.circular(10)),
      boxShadow: [
        BoxShadow(
            color: Color(0xffA22447).withOpacity(.05),
            offset: Offset(0, 0),
            blurRadius: 20,
            spreadRadius: 3)
      ]),
  child: Material(
    borderRadius: BorderRadius.only(
        bottomLeft: Radius.circular(10),
        bottomRight: Radius.circular(10)),
    elevation: 5,
    shadowColor: Color(0xffA22447).withOpacity(.05),
    color: Color(0xFFF7F7F7),
    child: SizedBox(
      height: MediaQuery.of(context).size.height / 3,
    ),
  ),
)


问:
php Array how to iterate
I am using a code-igniter query which returns the the array below with additional calculated [year_totalsales] added to array.

```<code>Array ( [0] => Array ( [year] => 2009 [month] => November [month_sales] => 524 [year_totalsales] => 3610 ) [1] => Array ( [year] => 2009 [month] => December [month_sales] => 521 [year_totalsales] => 3610 ) [2] => Array ( [year] => 2010 [month] => January [month_sales] => 609 [year_totalsales] => 3610 ) [3] => Array ( [year] => 2010 [month] => February [month_sales] => 619 [year_totalsales] => 3610 ) [4] => Array ( [year] => 2010 [month] => March [month_sales] => 732 [year_totalsales] => 3610 ) [5] => Array ( [year] => 2010 [month] => April [month_sales] => 605 [year_totalsales] => 3610 ) )
</code>```

Is there a way to get the output result to look this:

```<code>year-------------------------

month---------------monthsales
</code>```

答:
well you could do something like:

```<code><?
$myarray = array( 0 => array( 'year' => 2009, 'month' => "November", 'month_sales' => 524, 'year_totalsales' => 3610 ),
1 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 521, 'year_totalsales' => 3610 ),
                  2 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 609, 'year_totalsales' => 3610 ));

$linewidth = 29; // Change to the width you want of course
$sep = "-"; // Change the seperator you want
$lastyear = "";
function pad($output, $length) {
    global $sep;
    $output = (string)$output;
    while (strlen($output) < $length) {
        $output .= $sep;
    }
    return $output;
}
foreach($myarray as $row) {
    if ($row['year'] != $lastyear) {
        echo pad($row['year'], $linewidth), PHP_EOL;
        $lastyear = $row['year'];
    }
    echo pad($row['month'], $linewidth-strlen((string)$row['month_sales'])), $row['month_sales'], PHP_EOL;
}
?>
</code>```

Of course you could add your own formatting or whatever if this isn't satisfactory.

Edit: tested, it works properly now.

Outputs:

```<code>2009-------------------------
November------------------524
December------------------521
2010-------------------------
January-------------------609
</code>```

Edit this uses an HTML table instead:

```<code><?
$myarray = array( 0 => array( 'year' => 2009, 'month' => "November", 'month_sales' => 524, 'year_totalsales' => 3610 ),
1 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 521, 'year_totalsales' => 3610 ),
                  2 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 609, 'year_totalsales' => 3610 ));

$lastyear = "";
echo "<table><tr><th>Month</th><th>Sales</th></tr>", PHP_EOL;
foreach($myarray as $row) {
    if ($row['year'] != $lastyear) {
        echo "<tr><th colspan=2>", $row['year'], "</th></tr>", PHP_EOL;
        $lastyear = $row['year'];
    }
    echo "<tr><td>", $row['month'], "</td><td>", $row['month_sales'], "</td></tr>", PHP_EOL;
}
echo "</table>", PHP_EOL;
?>
</code>```

This outputs:

```<code><table><tr><th>Month</th><th>Sales</th></tr>
<tr><th colspan=2>2009</th></tr>
<tr><td>November</td><td>524</td></tr>
<tr><td>December</td><td>521</td></tr>
<tr><th colspan=2>2010</th></tr>
<tr><td>January</td><td>609</td></tr>
</table>
</code>```

Title: php Array how to iterate

Body:
I am using a code-igniter query which returns the the array below with additional calculated [year_totalsales] added to array.

Array ( [0] => Array ( [year] => 2009 [month] => November [month_sales] => 524 [year_totalsales] => 3610 ) [1] => Array ( [year] => 2009 [month] => December [month_sales] => 521 [year_totalsales] => 3610 ) [2] => Array ( [year] => 2010 [month] => January [month_sales] => 609 [year_totalsales] => 3610 ) [3] => Array ( [year] => 2010 [month] => February [month_sales] => 619 [year_totalsales] => 3610 ) [4] => Array ( [year] => 2010 [month] => March [month_sales] => 732 [year_totalsales] => 3610 ) [5] => Array ( [year] => 2010 [month] => April [month_sales] => 605 [year_totalsales] => 3610 ) )

Is there a way to get the output result to look this:

year-------------------------

month---------------monthsales

Body:
well you could do something like:

<?
$myarray = array( 0 => array( 'year' => 2009, 'month' => "November", 'month_sales' => 524, 'year_totalsales' => 3610 ),
1 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 521, 'year_totalsales' => 3610 ),
                  2 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 609, 'year_totalsales' => 3610 ));

$linewidth = 29; // Change to the width you want of course
$sep = "-"; // Change the seperator you want
$lastyear = "";
function pad($output, $length) {
    global $sep;
    $output = (string)$output;
    while (strlen($output) < $length) {
        $output .= $sep;
    }
    return $output;
}
foreach($myarray as $row) {
    if ($row['year'] != $lastyear) {
        echo pad($row['year'], $linewidth), PHP_EOL;
        $lastyear = $row['year'];
    }
    echo pad($row['month'], $linewidth-strlen((string)$row['month_sales'])), $row['month_sales'], PHP_EOL;
}
?>

Of course you could add your own formatting or whatever if this isn't satisfactory.

Edit: tested, it works properly now.

Outputs:

2009-------------------------
November------------------524
December------------------521
2010-------------------------
January-------------------609

Edit this uses an HTML table instead:

<?
$myarray = array( 0 => array( 'year' => 2009, 'month' => "November", 'month_sales' => 524, 'year_totalsales' => 3610 ),
1 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 521, 'year_totalsales' => 3610 ),
                  2 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 609, 'year_totalsales' => 3610 ));

$lastyear = "";
echo "<table><tr><th>Month</th><th>Sales</th></tr>", PHP_EOL;
foreach($myarray as $row) {
    if ($row['year'] != $lastyear) {
        echo "<tr><th colspan=2>", $row['year'], "</th></tr>", PHP_EOL;
        $lastyear = $row['year'];
    }
    echo "<tr><td>", $row['month'], "</td><td>", $row['month_sales'], "</td></tr>", PHP_EOL;
}
echo "</table>", PHP_EOL;
?>

This outputs:

<table><tr><th>Month</th><th>Sales</th></tr>
<tr><th colspan=2>2009</th></tr>
<tr><td>November</td><td>524</td></tr>
<tr><td>December</td><td>521</td></tr>
<tr><th colspan=2>2010</th></tr>
<tr><td>January</td><td>609</td></tr>
</table>

ContentLicense: CC BY-SA 3.0


问:
Using local git repository with Ansible Tower
I have been successful configuring Ansible Tower project to pull from remote git repos, and also pulling from a local repo using ssh and stored credentials (keys). On this server, allowing ssh login to access git is not acceptable, so I am trying to configure Ansible Tower to use a local git repository; not using git: or ssh: protocol to access, just accessing it via file:///path/to/AnsibleTower.git

The Ansible Tower project-update function tries to 'git clone', but it gives an error:

```<code>        "fatal: Could not read from remote repository.",
        "Please make sure you have the correct access rights",
        "and the repository exists."
</code>```

And it shows this is the command it used to attempt to clone:

```<code>"cmd": "/usr/bin/git clone --origin origin file:///path/to/AnsibleTower.git/ /var/lib/awx/projects/_114__00_test"
</code>```

When I execute the above command directly on the server, as the awx user, I get no error and the clone works. I can see that the git commands is being executed with the awx user when Tower attempts to update (watching ps for the process). The awx user owns the AnsibleTower.git directory and everything in it.

The reason this is important and the reason I have tagged this 'ansible-inventory' is that using an SCM-backed project seems to be the only way to import/synchronize a text-based inventory to Tower. I would really like to avoid re-creating/updating my inventory using the Tower web interface; I want that tracked in SCM as well.

I even went so far as to grant all users access to the .git directory (temporarily); that didn't work either, it doesn't seem to be a user-permission issue.

答:
You can omit the file:// at the begin of the origin.
All local repositories do not need this and some OS cannot handle file:// uri‘s for local files/directories </p>

Body:
I have been successful configuring Ansible Tower project to pull from remote git repos, and also pulling from a local repo using ssh and stored credentials (keys). On this server, allowing ssh login to access git is not acceptable, so I am trying to configure Ansible Tower to use a local git repository; not using git: or ssh: protocol to access, just accessing it via file:///path/to/AnsibleTower.git

The Ansible Tower project-update function tries to 'git clone', but it gives an error:

        "fatal: Could not read from remote repository.",
        "Please make sure you have the correct access rights",
        "and the repository exists."

And it shows this is the command it used to attempt to clone:

"cmd": "/usr/bin/git clone --origin origin file:///path/to/AnsibleTower.git/ /var/lib/awx/projects/_114__00_test"

When I execute the above command directly on the server, as the awx user, I get no error and the clone works. I can see that the git commands is being executed with the awx user when Tower attempts to update (watching ps for the process). The awx user owns the AnsibleTower.git directory and everything in it.

The reason this is important and the reason I have tagged this 'ansible-inventory' is that using an SCM-backed project seems to be the only way to import/synchronize a text-based inventory to Tower. I would really like to avoid re-creating/updating my inventory using the Tower web interface; I want that tracked in SCM as well.

I even went so far as to grant all users access to the .git directory (temporarily); that didn't work either, it doesn't seem to be a user-permission issue.


问:
Compare string of unknown length against string of known length
I want to compare a null-terminated string of an unknown length (s1) with an unterminated string of a known length (s2).

!strncmp(s1, s2, s2_len) is close to correct, but also becomes evaluates to true if s2 is a prefix of s1.

strlen(s1) == s2_len && !strcmp(s1, s2) is correct, but scans s1 twice.

Obviously, manually comparing the strings also works, but loses me all the shiny optimizations the C library has picked up in the last forty years.

Is there a good way to achieve this with C library functions?

答:
You can use the strncmp approach and check for a NUL terminator in s1:

```<code>!strncmp(s1, s2, s2_len) && !s1[s2_len]
</code>```

Body:
You can use the strncmp approach and check for a NUL terminator in s1:

!strncmp(s1, s2, s2_len) && !s1[s2_len]


问:
GET from Flask RESTful API with API Key
I'm pretty new to this field and I'm struggling to perform a successful GET from my flask server. I have my server running in docker on a Ubuntu 18.04 Server VM and my host OS is Ubuntu 19.10.

I don't know which information you need to help me. I got a YAML file which I generated my API from. First a few lines from my YAML file, I generated everything from:

```<code>servers:
    - url: /v1
paths:
  /supported_types:
    get:
      operationId: getSupportedTypes
      summary: Retrieve supported types
      responses:
        200:
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  username:
                    type: boolean
                  email_address:
                    type: boolean
</code>```

And my security section:

```<code>security:
  - APIKey: []
components:
  securitySchemes:
    APIKey:
      type: apiKey
      in: header
      name: Authorization
</code>```

In my code I didn't change much so my authentication_controller.py looks like this:

```<code>def check_APIKey(api_key, required_scopes):
    return {'test_key': 'test_value'}
</code>```

In my default_controller.py there is this method which I assume to be the specified GET method:

```<code>def get_supported_types():  # noqa: E501
    """Retrieve supported types
     # noqa: E501
    :rtype: InlineResponse200
    """
    notes = {username:true, email_address:true}
    return notes
</code>```

So when I run curl -H 'X-Api-Key: DEMO_KEY' --trace-ascii /tmp/dump.txt  http://127.0.0.1:3080/v1/supported_types I get this output via console:

```<code>{
  "detail": "No authorization token provided",
  "status": 401,
  "title": "Unauthorized",
  "type": "about:blank"
}
</code>```

And in the dump.txt it says:

```<code>== Info:   Trying 127.0.0.1:3080...
== Info: TCP_NODELAY set
== Info: Connected to 127.0.0.1 (127.0.0.1) port 3080 (#0)
=> Send header, 120 bytes (0x78)
0000: GET /v1/supported_types HTTP/1.1
0025: Host: 127.0.0.1:3080
003b: User-Agent: curl/7.65.3
0054: Accept: */*
0061: X-Api-Key: DEMO_KEY
0076:
== Info: Mark bundle as not supporting multiuse
== Info: HTTP 1.0, assume close after body
<= Recv header, 27 bytes (0x1b)
0000: HTTP/1.0 401 UNAUTHORIZED
<= Recv header, 40 bytes (0x28)
0000: Content-Type: application/problem+json
<= Recv header, 21 bytes (0x15)
0000: Content-Length: 119
<= Recv header, 39 bytes (0x27)
0000: Server: Werkzeug/0.16.0 Python/3.6.10
<= Recv header, 37 bytes (0x25)
0000: Date: Sun, 16 Feb 2020 14:17:22 GMT
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 119 bytes (0x77)
0000: {.  "detail": "No authorization token provided",.  "status": 401
0040: ,.  "title": "Unauthorized",.  "type": "about:blank".}.
== Info: Closing connection 0
</code>```

I'm pretty sure I'm missing something really dump, but maybe someone can tell me what it is (and maybe explain what I may be misunderstanding.

答:
I figured out what the problem was: like I was told in the comments I had to adjust the header

I think you send the DEMO_KEY in the Authorization header instead of the X-Api-Key header – mtshaikh

I changed curl -H 'X-Api-Key: DEMO_KEY' to curl -H 'Authorization: DEMO_KEY'.

Then I found another error with my code in

```<code>def get_supported_types():  # noqa: E501
    """Retrieve supported types
     # noqa: E501
    :rtype: InlineResponse200
    """
    notes = {username:true, email_address:true}
    return notes
</code>```

where I changed

```<code>notes = {username:true, email_address:true}
        return notes
</code>```

into return "test" so it will become interpretable

Title: GET from Flask RESTful API with API Key

Body:
I'm pretty new to this field and I'm struggling to perform a successful GET from my flask server. I have my server running in docker on a Ubuntu 18.04 Server VM and my host OS is Ubuntu 19.10.

I don't know which information you need to help me. I got a YAML file which I generated my API from. First a few lines from my YAML file, I generated everything from:

servers:
    - url: /v1
paths:
  /supported_types:
    get:
      operationId: getSupportedTypes
      summary: Retrieve supported types
      responses:
        200:
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  username:
                    type: boolean
                  email_address:
                    type: boolean

And my security section:

security:
  - APIKey: []
components:
  securitySchemes:
    APIKey:
      type: apiKey
      in: header
      name: Authorization

In my code I didn't change much so my authentication_controller.py looks like this:

def check_APIKey(api_key, required_scopes):
    return {'test_key': 'test_value'}

In my default_controller.py there is this method which I assume to be the specified GET method:

def get_supported_types():  # noqa: E501
    """Retrieve supported types
     # noqa: E501
    :rtype: InlineResponse200
    """
    notes = {username:true, email_address:true}
    return notes

So when I run curl -H 'X-Api-Key: DEMO_KEY' --trace-ascii /tmp/dump.txt  http://127.0.0.1:3080/v1/supported_types I get this output via console:

{
  "detail": "No authorization token provided",
  "status": 401,
  "title": "Unauthorized",
  "type": "about:blank"
}

And in the dump.txt it says:

== Info:   Trying 127.0.0.1:3080...
== Info: TCP_NODELAY set
== Info: Connected to 127.0.0.1 (127.0.0.1) port 3080 (#0)
=> Send header, 120 bytes (0x78)
0000: GET /v1/supported_types HTTP/1.1
0025: Host: 127.0.0.1:3080
003b: User-Agent: curl/7.65.3
0054: Accept: */*
0061: X-Api-Key: DEMO_KEY
0076:
== Info: Mark bundle as not supporting multiuse
== Info: HTTP 1.0, assume close after body
<= Recv header, 27 bytes (0x1b)
0000: HTTP/1.0 401 UNAUTHORIZED
<= Recv header, 40 bytes (0x28)
0000: Content-Type: application/problem+json
<= Recv header, 21 bytes (0x15)
0000: Content-Length: 119
<= Recv header, 39 bytes (0x27)
0000: Server: Werkzeug/0.16.0 Python/3.6.10
<= Recv header, 37 bytes (0x25)
0000: Date: Sun, 16 Feb 2020 14:17:22 GMT
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 119 bytes (0x77)
0000: {.  "detail": "No authorization token provided",.  "status": 401
0040: ,.  "title": "Unauthorized",.  "type": "about:blank".}.
== Info: Closing connection 0

I'm pretty sure I'm missing something really dump, but maybe someone can tell me what it is (and maybe explain what I may be misunderstanding.

Body:
I figured out what the problem was: like I was told in the comments I had to adjust the header

I think you send the DEMO_KEY in the Authorization header instead of the X-Api-Key header – mtshaikh

I changed curl -H 'X-Api-Key: DEMO_KEY' to curl -H 'Authorization: DEMO_KEY'.

Then I found another error with my code in

def get_supported_types():  # noqa: E501
    """Retrieve supported types
     # noqa: E501
    :rtype: InlineResponse200
    """
    notes = {username:true, email_address:true}
    return notes

where I changed

notes = {username:true, email_address:true}
        return notes

into return "test" so it will become interpretable


问:
What does it mean to pre-increment $#array?
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

```<code>$array [++$#array] = 'data';
</code>```

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

答:
This code works too:

```<code>$ perl -le 'my @a; $a[@a]="Hello"; $a[@a]=" world!"; print @a'
Hello world!
</code>```

Perl array is dynamic and grows when assign beyond limits.

OwnerDisplayName: Paul Beckingham

ContentLicense: CC BY-SA 2.5

Body:
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

$array [++$#array] = 'data';

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

LastEditorDisplayName: brian d foy

Body:
This code works too:

$ perl -le 'my @a; $a[@a]="Hello"; $a[@a]=" world!"; print @a'
Hello world!

Perl array is dynamic and grows when assign beyond limits.

OwnerDisplayName: Hynek -Pichi- Vychodil


问:
Append with input value with <li> tag
Thanks in advance.
I am trying to append a list using the input value. I can append a list using predefined string, and I can append using input value to non list item. But I'm having trouble combining these, it seems to add extra list items.
This is the code I'm using:</p>

```<code>    <ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<form>
    <div><textarea class="example-default-value" id="example-textarea" style="width: 400px; height: 50px;">Type some text in here to be appended</textarea></div>
    <div><input type="button" value="Append" onclick="example_append()" /></div>
</form>
<script language="javascript">
$('.example-default-value').each(function() {
    var default_value = this.value;
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            this.value = default_value;
        }
    });
});
function example_append() {
    $('ol').append("<li>"+($('#example-textarea').val())+"<li>");
}
</script>
</code>```

答:
OH OK I see - I'm using two li tags instead of one li and one /li closing tag! Oh dear... more coffee required!!</p>

```<code>    function example_append() {
    $('ol').append("<li>"+($('#example-textarea').val())+"</li>");
}
</code>```

Title: Append with input value with <li> tag

Body:
Thanks in advance.
I am trying to append a list using the input value. I can append a list using predefined string, and I can append using input value to non list item. But I'm having trouble combining these, it seems to add extra list items.
This is the code I'm using:

List item 1

List item 2

List item 3

<form>

<textarea class="example-default-value" id="example-textarea" style="width: 400px; height: 50px;">Type some text in here to be appended</textarea>

<input type="button" value="Append" onclick="example_append()" />

</form>

Body:
OH OK I see - I'm using two li tags instead of one li and one /li closing tag! Oh dear... more coffee required!!

    function example_append() {
    $('ol').append("<li>"+($('#example-textarea').val())+"</li>");
}


问:
How to retrigger UITableView canMoveRowAt
I'm using canMoveRowAt() and moveRowAt() to show drag handles on my rows. Within canMoveRowAt I test a condition based on some of the row's data:

... get reference to row data ...

return rowData.myCondition()

This works fine when the table is first put into Edit mode. However while in Edit mode the data in the row can change (it's still the same row though). I'd like to retrigger canMoveRowAt to re-evaluate the condition and potentially change whether a drag handle is shown for the row.

So far I've managed to do this only by ending and restarting Edit mode. When I do that it clears the selections in the table, so I have to save and reapply them. This seems like a bit of a hack.

Is there a more elegant way of re-triggering canMoveRowAt to avoid this?

答:
OK, in the end I just went for reloadRows(at:), saving and restoring the selections around this:</p>

```<code>let savedSelections = vList.indexPathsForSelectedRows ?? []
vList.reloadRows(at: [dragHandleRowIndexPath], with: .automatic)
for indexPath in savedSelections {
    vList.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
</code>```

Body:
OK, in the end I just went for reloadRows(at:), saving and restoring the selections around this:

let savedSelections = vList.indexPathsForSelectedRows ?? []
vList.reloadRows(at: [dragHandleRowIndexPath], with: .automatic)
for indexPath in savedSelections {
    vList.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}


问:
Why is a reference needed in operator overloading?
In what situations would a reference be needed when overloading, as the code still works without it? I am aware it has something to with chaining, but I do not understand exactly why the reference is needed.

Example:

```<code>Object& operator++();
</code>```

答:
The built-in unary operator ++ returns a reference to the object for which the operator is applied.

For example you may write

```<code>int i = 10;
++++i;
</code>```

So to simulate the same behavior user-defined operators also should return a reference to object.

Body:
In what situations would a reference be needed when overloading, as the code still works without it? I am aware it has something to with chaining, but I do not understand exactly why the reference is needed.

Example:

Object& operator++();

Body:
The built-in unary operator ++ returns a reference to the object for which the operator is applied.

For example you may write

int i = 10;
++++i;

So to simulate the same behavior user-defined operators also should return a reference to object.


问:
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>```

答:
On any mouse event listener, there will always be a MouseEvent parameter passed to the event handler. That MouseEvent object has the propertie target, which is the HTMLElement that was the target of the event. For example:

let div = document.querySelector('div.button');
let toggleState = 0;
let messages = ['Clicked!', 'Click me!'];
let handler = function(event) {
  event.target.innerText = messages[toggleState];
  toggleState ^= 1;
}

div.addEventListener("click", handler, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="button">Click me!</div></code>```

In addition, every HTMLElement has a remove() method, which removes it from the DOM. For example:

document.querySelector('div').remove()
```

<p>or:</p>

<pre class="lang-js prettyprint-override"><code>let handler = function(event) {
  event.target.remove();
}
document.querySelector('div').addEventListener('click', handler, false);
</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:
On any mouse event listener, there will always be a MouseEvent parameter passed to the event handler. That MouseEvent object has the propertie target, which is the HTMLElement that was the target of the event. For example:

let div = document.querySelector('div.button');
let toggleState = 0;
let messages = ['Clicked!', 'Click me!'];
let handler = function(event) {
  event.target.innerText = messages[toggleState];
  toggleState ^= 1;
}

div.addEventListener("click", handler, false);

<div class="button">Click me!</div>

In addition, every HTMLElement has a remove() method, which removes it from the DOM. For example:

document.querySelector('div').remove()

or:

let handler = function(event) {
  event.target.remove();
}
document.querySelector('div').addEventListener('click', handler, false);


问:
How to make this image effect, any library that can help with it
Do you know if an emboss effect like this can be done with a programming package. Can someone suggest something

答:
Typically simple effects like this are implemented using a convolution kernel, where an image is transformed from its source to a new copy.  Each new pixel is computed as a linear combination (i.e. a weighted sum) of its source pixel and a subset of its neighbors within the source image.

As an example, you might (abstractly) define a kernel such as:

```<code> 0  0  0
 0  9 -3
 0 -3 -3
</code>```

Here, the center of the matrix represents the weighting applied to the corresponding source pixel for each new pixel value to be computed.  The surrounding values represent the weighting that should be applied to the corresponding neighbor pixels before summing to compute the new pixel's total value.

In practice, this might be applied to create a new embossed image with the following pseudocode:

```<code>for y in source.height:
    for x in source.width:
        newImage[x,y] = source[x,y]*9
                      + source[x+1,y]*-3
                      + source[x,y+1]*-3
                      + source[x+1,y+1]*-3
</code>```

There are obvious implementation details left out, such as how to handle the edge of the image (one option is to assume the image is mirrored about its edges), as well as actually applying an arbitrary matrix of coefficients rather than hard-coding the weighted sum as above.  Hopefully this at least conveys how simple the operation really is at its core.

Body:
Typically simple effects like this are implemented using a convolution kernel, where an image is transformed from its source to a new copy.  Each new pixel is computed as a linear combination (i.e. a weighted sum) of its source pixel and a subset of its neighbors within the source image.

As an example, you might (abstractly) define a kernel such as:

 0  0  0
 0  9 -3
 0 -3 -3

Here, the center of the matrix represents the weighting applied to the corresponding source pixel for each new pixel value to be computed.  The surrounding values represent the weighting that should be applied to the corresponding neighbor pixels before summing to compute the new pixel's total value.

In practice, this might be applied to create a new embossed image with the following pseudocode:

for y in source.height:
    for x in source.width:
        newImage[x,y] = source[x,y]*9
                      + source[x+1,y]*-3
                      + source[x,y+1]*-3
                      + source[x+1,y+1]*-3

There are obvious implementation details left out, such as how to handle the edge of the image (one option is to assume the image is mirrored about its edges), as well as actually applying an arbitrary matrix of coefficients rather than hard-coding the weighted sum as above.  Hopefully this at least conveys how simple the operation really is at its core.


问:
Write pandas dataframe into AWS athena database
I have run a query using pyathena, and have created a pandas dataframe. Is there a way to write the pandas dataframe to AWS athena database directly?
Like data.to_sql for MYSQL database.

Sharing a example of dataframe code below for reference  need to write into AWS athena database:

```<code>data=pd.DataFrame({'id':[1,2,3,4,5,6],'name':['a','b','c','d','e','f'],'score':[11,22,33,44,55,66]})
</code>```

答:
Another modern (as for February 2020) way to achieve this goal is to use aws-data-wrangler library. It's authomating many routine (and sometimes annoying) tasks in data processing.

Combining the case from the question the code would look like below:

import pandas as pd
import awswrangler as wr

data=pd.DataFrame({'id':[1,2,3,4,5,6],'name':['a','b','c','d','e','f'],'score':[11,22,33,44,55,66]})

# Typical Pandas, Numpy or Pyarrow transformation HERE!

wr.pandas.to_parquet(  # Storing the data and metadata to Data Lake
    dataframe=data,
    database="database",
    path="s3://your-s3-bucket/path/to/new/table",
    partition_cols=["name"],
)
```
<p>This is amazingly helpful, because aws-data-wrangler knows to parse table name from the path (but you can provide table name in the parameter) and define proper types in Glue catalog according to the dataframe.</p>
<p>It also helpful for querying the data with Athena directly to pandas dataframe:</p>
<pre class="lang-py prettyprint-override"><code>df = wr.pandas.read_table(database="dataase", table="table")
</code>```

All the process will be fast and convenient.

Body:
I have run a query using pyathena, and have created a pandas dataframe. Is there a way to write the pandas dataframe to AWS athena database directly?
Like data.to_sql for MYSQL database.

Sharing a example of dataframe code below for reference  need to write into AWS athena database:

data=pd.DataFrame({'id':[1,2,3,4,5,6],'name':['a','b','c','d','e','f'],'score':[11,22,33,44,55,66]})

Body:
Another modern (as for February 2020) way to achieve this goal is to use aws-data-wrangler library. It's authomating many routine (and sometimes annoying) tasks in data processing.

Combining the case from the question the code would look like below:

import pandas as pd
import awswrangler as wr

data=pd.DataFrame({'id':[1,2,3,4,5,6],'name':['a','b','c','d','e','f'],'score':[11,22,33,44,55,66]})

# Typical Pandas, Numpy or Pyarrow transformation HERE!

wr.pandas.to_parquet(  # Storing the data and metadata to Data Lake
    dataframe=data,
    database="database",
    path="s3://your-s3-bucket/path/to/new/table",
    partition_cols=["name"],
)

This is amazingly helpful, because aws-data-wrangler knows to parse table name from the path (but you can provide table name in the parameter) and define proper types in Glue catalog according to the dataframe.

It also helpful for querying the data with Athena directly to pandas dataframe:

df = wr.pandas.read_table(database="dataase", table="table")

All the process will be fast and convenient.


问:
Update user with Firebase Cloud Functions
I would like to find a user by their phone number and update their displayName in Firebase Cloud Functions using the Admin SDK.
When I try to run this code for example:

```<code>import * as admin from 'firebase-admin'
admin.auth().getUserByPhoneNumber(phone).then((user) => {
   user.displayName = newName;
}).catch((reason) => console.log(reason['message']));
</code>```

I get the following message:

Cannot assign to read only property 'displayName' of object '#UserRecord'

Although I undestand this exception, I cannot think of a diffrent way to do this. Any idea?

答:
The getUserByPhoneNumber() method returns a UserRecord which doesn't have any method to modify the user object.

You need to use the updateUser() method to do so, as follows:

```<code>//....
return admin.auth().getUserByPhoneNumber(phone)
.then(userRecord => {
   return admin.auth().updateUser(userRecord.uid, {displayName: newName});
})
.catch((reason) => console.log(reason['message']));
</code>```

Don't forget to return the Promise chain if your Cloud Function is a background-triggered one, see https://firebase.google.com/docs/functions/terminate-functions

Body:
I would like to find a user by their phone number and update their displayName in Firebase Cloud Functions using the Admin SDK.
When I try to run this code for example:

import * as admin from 'firebase-admin'
admin.auth().getUserByPhoneNumber(phone).then((user) => {
   user.displayName = newName;
}).catch((reason) => console.log(reason['message']));

I get the following message:

Cannot assign to read only property 'displayName' of object '#UserRecord'

Although I undestand this exception, I cannot think of a diffrent way to do this. Any idea?

Body:
The getUserByPhoneNumber() method returns a UserRecord which doesn't have any method to modify the user object.

You need to use the updateUser() method to do so, as follows:

//....
return admin.auth().getUserByPhoneNumber(phone)
.then(userRecord => {
   return admin.auth().updateUser(userRecord.uid, {displayName: newName});
})
.catch((reason) => console.log(reason['message']));

Don't forget to return the Promise chain if your Cloud Function is a background-triggered one, see https://firebase.google.com/docs/functions/terminate-functions


问:
How to read .tif image in OpenCV
I want to load and display a .tif image in OpenCV Python. I load the image using cv2.imread('1_00001.tif') and then I display it using plt.imshow(img), but the image displayed is all black instead of what it was originally.

I can load and display the image correctly using PIL's Image.open() and matplotlib's mpimg.imread() so I think it is a cv2 specific problem. However, I have also successfully displayed .jpg and .tiff images using the same cv2.imread() function so it may also be a problem with specifically that .tif image.

```<code>import cv2
import matplotlib.pyplot as plt

img = cv2.imread('1_00001.tif')
plt.imshow(img)
</code>```

I expect an image of a circle with a few blurry lines inside, but the actual output is just a black image.

答: Check your image pixel values. plt.imshow clips pixel values from 0-255, so I would guess that you're feeding in a PNG image with values greater than 255, and they're all getting clipped to 255 (black). Usually you'll want to normalize a TIFF or PNG image before feeding them to plt.imshow, so it's interesting that you're not seeing this problem on some tiff images.

Title: How to read .tif image in OpenCV

Body:
I want to load and display a .tif image in OpenCV Python. I load the image using cv2.imread('1_00001.tif') and then I display it using plt.imshow(img), but the image displayed is all black instead of what it was originally.

I can load and display the image correctly using PIL's Image.open() and matplotlib's mpimg.imread() so I think it is a cv2 specific problem. However, I have also successfully displayed .jpg and .tiff images using the same cv2.imread() function so it may also be a problem with specifically that .tif image.

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('1_00001.tif')
plt.imshow(img)

I expect an image of a circle with a few blurry lines inside, but the actual output is just a black image.


问:
Will Terrafrom allow new EC2(s) to be deployed into established cloud infrastructure
Is it possible to deploy additional resources like EC2(s) into the same VPC once deployed using terraform? Concerned that the established resources in the VPC: EC2(s), NIC configurations, and VPC subnets will be overwritten?

I am wanting to deploy additional EC2(s) without overwriting the VPC, subnets, and established EC2?   I am wondering if the subnets will be recreated hence impacting working EC2(s). (Looking for way to deploy additional EC2(s) once the infrastructure is established with Transit Gateways or peering, Internet Gateway (IGW) which are in production.)

答:
I would recommend importing your existing resources into Terraform so it's all managed by TF. To do this, you would create Resource objects for all the existing resources then run terraform import ... on each, you can start with a basic Resource object, then after importing, run terraform plan and make any changes that it detects as drift (or the changes it wants to make to the resource). Keep going until terraform plan reports it's not going to change anything, now they are completely managed by TF.

If you don't want to do that you can describe existing AWS resources using the TF Data object, that's what they are meant for. Then just reference those Data objects in your new EC2 Resource objects.


问:
How can I share my stylesheets between different solutions in ASP.NET MVC 3?
I have three solutions; all share one thing in common which is the stylesheets. I would like to have only one version of the stylesheets.

I thought to put this and maybe other things like common scripts in one project and then have all three solutions reference this same project.

But how can I link in the stylesheets to my layout pages. Currently I use:

```<code><link href="@Url.Content("~/Content/Stylesheets/Package3.css")"
      rel="stylesheet" type="text/css" />
</code>```

Any advice would be appreciated.

答: You can use the 'Add as link' option.</p>

Body:
I have three solutions; all share one thing in common which is the stylesheets. I would like to have only one version of the stylesheets.

I thought to put this and maybe other things like common scripts in one project and then have all three solutions reference this same project.

But how can I link in the stylesheets to my layout pages. Currently I use:

<link href="@Url.Content("~/Content/Stylesheets/Package3.css")"
      rel="stylesheet" type="text/css" />

Any advice would be appreciated.

Body: You can use the 'Add as link' option.


问:
How to pass data from one component to another while using API in reactjs
In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in?
When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

```<code>{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "qwerty@yahoo.com",
      "password": "Aertyuio",
    }
  ]
}
</code>```

答:
Since you are using react-router push method. It also has the ability to send different props value along with your pathname and this push will work only on components wrapped in .

In your case, you need to pass a state along with your route name. Below changes, you have to pass state along with your route name in history.push.

this.props.history.push("/Welcome", { ...res }); on Login.js.

And get the response values on your Welcome.js by using this.props.location.state.firstName.

Attaching the document for your reference - https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md

And Also, I attached a basic demonstration of history.push in this - https://codesandbox.io/s/broken-flower-hbglx.

Body:
In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in?
When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "qwerty@yahoo.com",
      "password": "Aertyuio",
    }
  ]
}


问:
How to implement efficient algorith for calculating multiple distinct values for large dataset?
I am trying to find a fastest way to calculate a number of unique values in a huge table, where the number of rows can easily be between 100 million to 10 billion. In this particular case, I am dealing with 128-bit integers.

I'm trying to understand, why pandas approach achieves a better result (tested with 1 million rows) as it appears to make operations on columns level, which feels inefficient. How this should be implemented in c++? My initial attempt to create c++ version was extremely slow (slower than Python). I used std:set, std:pair and std:map.

The first attempt looks like this:

import time
from collections import defaultdict as ddict
import pandas as pd

df = pd.DataFrame([])  # Load table with two columns containing 128 bit integers.

class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        self.interval = self.end - self.start
        print("time elapsed:" ,self.interval)

with Timer():
    print(df['left'].nunique())
    print(df['right'].nunique())
    left_grp = df.groupby('left')
    print(left_grp['right'].nunique().max())
    right_grp = df.groupby('right')
    print(right_grp['left'].nunique().max())
```

<p>Below is the pure Python example, which goes the array through row-by-row basis, which should to my understanding be more efficient. It is just 3 times slower than pandas version.</p>

<pre class="lang-py prettyprint-override"><code>with Timer():
    uniques1 = set()
    uniques2 = set()

    uniques3 = ddict(set)
    uniques4 = ddict(set)

    for i in range(len(ndarray)):
        uniques1.add(ndarray[i]['left'])
        uniques2.add(ndarray[i]['right'])
        uniques3[ndarray[i]['left']].add(ndarray[i]['right'])
        uniques4[ndarray[i]['right']].add(ndarray[i]['left'])

    print(len(uniques1))
    print(len(uniques2))
    print(max(len(v) for v in uniques3.values()))
    print(max(len(v) for v in uniques4.values()))
</code>```

Any advice on how to implement the above pure Python code efficiently in c++? My attempt with c++ below.

#include <stdint.h>
#include <map>
#include <bits/stdc++.h>
#include <algorithm>

typedef std::pair<uint64_t, uint64_t> uint128_t;
typedef std::set<uint128_t> set128_t;
typedef std::map<uint128_t, set128_t > map128_t;

namespace nunique_highperf{
    int get_max(const map128_t& map) {
        int best = 0;
        auto it = map.begin();

        while (it != map.end()) {
            best = std::max(best, (int)it->second.size());
            it++;
        }

        return best;
    }

    void default_update(map128_t &map, uint128_t left, uint128_t right) {
        set128_t temp;
        map.emplace(left, temp);
        temp = map[left];
        temp.insert(right);
        map[left] = temp;
    }

    void uniques_from_table(uint64_t **sessions, int rows) {
        set128_t uniques1;
        set128_t uniques2;
        map128_t uniques3;
        map128_t uniques4;

        for (int i=0; i<rows; i++) {
            uint128_t left = std::make_pair(sessions[i][0], sessions[i][1]);
            uint128_t right = std::make_pair(sessions[i][2], sessions[i][3]);

            uniques1.insert(left);
            uniques2.insert(right);

            default_update(uniques3, left, right);
            default_update(uniques4, right, left);
        }

        printf("%d\n", uniques1.size());
        printf("%d\n", uniques2.size());
        printf("%d\n", get_max(uniques3));
        printf("%d\n", get_max(uniques4));
    }
}
```

In actual implementation, there will be multiple columns (not 2 as in the example), from which the number of unique elements is counted, hence I'm not just asking the fastest way to calculate distinct values for a single column, but over multiple columns as well as column pairs.

EDIT: Added c++ code

答:
Solution was actually simple.

Replacing default_update function with this:

    void default_update(map128_t &map, uint128_t left, uint128_t right) {
        set128_t temp;
        auto temp_pair = map.emplace(left, temp);
        temp_pair.first->second.insert(right);
    }
```

did the trick.

Body:
I am trying to find a fastest way to calculate a number of unique values in a huge table, where the number of rows can easily be between 100 million to 10 billion. In this particular case, I am dealing with 128-bit integers.

I'm trying to understand, why pandas approach achieves a better result (tested with 1 million rows) as it appears to make operations on columns level, which feels inefficient. How this should be implemented in c++? My initial attempt to create c++ version was extremely slow (slower than Python). I used std:set, std:pair and std:map.

The first attempt looks like this:

import time
from collections import defaultdict as ddict
import pandas as pd

df = pd.DataFrame([])  # Load table with two columns containing 128 bit integers.

class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        self.interval = self.end - self.start
        print("time elapsed:" ,self.interval)

with Timer():
    print(df['left'].nunique())
    print(df['right'].nunique())
    left_grp = df.groupby('left')
    print(left_grp['right'].nunique().max())
    right_grp = df.groupby('right')
    print(right_grp['left'].nunique().max())

Below is the pure Python example, which goes the array through row-by-row basis, which should to my understanding be more efficient. It is just 3 times slower than pandas version.

with Timer():
    uniques1 = set()
    uniques2 = set()

    uniques3 = ddict(set)
    uniques4 = ddict(set)

    for i in range(len(ndarray)):
        uniques1.add(ndarray[i]['left'])
        uniques2.add(ndarray[i]['right'])
        uniques3[ndarray[i]['left']].add(ndarray[i]['right'])
        uniques4[ndarray[i]['right']].add(ndarray[i]['left'])

    print(len(uniques1))
    print(len(uniques2))
    print(max(len(v) for v in uniques3.values()))
    print(max(len(v) for v in uniques4.values()))

Any advice on how to implement the above pure Python code efficiently in c++? My attempt with c++ below.

#include <stdint.h>
#include <map>
#include <bits/stdc++.h>
#include <algorithm>

typedef std::pair<uint64_t, uint64_t> uint128_t;
typedef std::set<uint128_t> set128_t;
typedef std::map<uint128_t, set128_t > map128_t;

namespace nunique_highperf{
    int get_max(const map128_t& map) {
        int best = 0;
        auto it = map.begin();

        while (it != map.end()) {
            best = std::max(best, (int)it->second.size());
            it++;
        }

        return best;
    }

    void default_update(map128_t &map, uint128_t left, uint128_t right) {
        set128_t temp;
        map.emplace(left, temp);
        temp = map[left];
        temp.insert(right);
        map[left] = temp;
    }

    void uniques_from_table(uint64_t **sessions, int rows) {
        set128_t uniques1;
        set128_t uniques2;
        map128_t uniques3;
        map128_t uniques4;

        for (int i=0; i<rows; i++) {
            uint128_t left = std::make_pair(sessions[i][0], sessions[i][1]);
            uint128_t right = std::make_pair(sessions[i][2], sessions[i][3]);

            uniques1.insert(left);
            uniques2.insert(right);

            default_update(uniques3, left, right);
            default_update(uniques4, right, left);
        }

        printf("%d\n", uniques1.size());
        printf("%d\n", uniques2.size());
        printf("%d\n", get_max(uniques3));
        printf("%d\n", get_max(uniques4));
    }
}

In actual implementation, there will be multiple columns (not 2 as in the example), from which the number of unique elements is counted, hence I'm not just asking the fastest way to calculate distinct values for a single column, but over multiple columns as well as column pairs.

EDIT: Added c++ code

Body:
Solution was actually simple.

Replacing default_update function with this:

    void default_update(map128_t &map, uint128_t left, uint128_t right) {
        set128_t temp;
        auto temp_pair = map.emplace(left, temp);
        temp_pair.first->second.insert(right);
    }

did the trick.


问:
Cognito - Client is not enabled for OAuth2.0 flows
I've successfully set up an AWS Cognito environment that runs on Localhost following this tutorial.

For the next step, I published the app to my external web server.  I confirmed that the Cognito configuration (i.e. Client ID, Metadata Address, Region, etc) is correct.  However, when I access and try to sign into the newly published public site I receive the follow error: " Client is not enabled for OAuth2.0 flows."

EDIT:

Here are my App Client Settings

I would like help with what I should look into in the AWS Cognito config or the Server config settings.  The server is NOT using a load balancer.  I believe the issue may lie somewhere in the Reverse Proxy or HTTPS settings.

答: I have seen this issue before. When making the request to Cognito, please take a close look at the redirect URL/ Call back URL you are specifying. If I remember correctly, I have seen this issue if you have a trailing '/' or a missing '/' in the redirect URL depending on what you have specified in the App Client Settings.</p>


问:
php Array how to iterate
I am using a code-igniter query which returns the the array below with additional calculated [year_totalsales] added to array.

```<code>Array ( [0] => Array ( [year] => 2009 [month] => November [month_sales] => 524 [year_totalsales] => 3610 ) [1] => Array ( [year] => 2009 [month] => December [month_sales] => 521 [year_totalsales] => 3610 ) [2] => Array ( [year] => 2010 [month] => January [month_sales] => 609 [year_totalsales] => 3610 ) [3] => Array ( [year] => 2010 [month] => February [month_sales] => 619 [year_totalsales] => 3610 ) [4] => Array ( [year] => 2010 [month] => March [month_sales] => 732 [year_totalsales] => 3610 ) [5] => Array ( [year] => 2010 [month] => April [month_sales] => 605 [year_totalsales] => 3610 ) )
</code>```

Is there a way to get the output result to look this:

```<code>year-------------------------

month---------------monthsales
</code>```

答:
Try this:</p>

```<code>foreach($year_array as $months_array)
{
echo 'year        '.$year_array[0];
foreach($months_array as $months)
{
echo 'monthsales        '.$months[0];
}
}
</code>```

Title: php Array how to iterate

Body:
I am using a code-igniter query which returns the the array below with additional calculated [year_totalsales] added to array.

Array ( [0] => Array ( [year] => 2009 [month] => November [month_sales] => 524 [year_totalsales] => 3610 ) [1] => Array ( [year] => 2009 [month] => December [month_sales] => 521 [year_totalsales] => 3610 ) [2] => Array ( [year] => 2010 [month] => January [month_sales] => 609 [year_totalsales] => 3610 ) [3] => Array ( [year] => 2010 [month] => February [month_sales] => 619 [year_totalsales] => 3610 ) [4] => Array ( [year] => 2010 [month] => March [month_sales] => 732 [year_totalsales] => 3610 ) [5] => Array ( [year] => 2010 [month] => April [month_sales] => 605 [year_totalsales] => 3610 ) )

Is there a way to get the output result to look this:

year-------------------------

month---------------monthsales

Body:
Try this:

foreach($year_array as $months_array)
{
echo 'year        '.$year_array[0];
foreach($months_array as $months)
{
echo 'monthsales        '.$months[0];
}
}


问:
How to convert the header as a new column
I'm working with pandas, and I'm trying to convert the header row of the dataframe to a column, i have tried the stack() function, but it looks not working for me.

I have a file which contains data as the follow, it has double header - date and temperature (min & Max)

```<code>      2/16/2020  2/16/2020   2/17/2020   2/17/2020   2/18/2020  2/18/2020   ......
         Min        Max         Min         Max         Min        Max
Paris    44         61          41          52          39         47
Berlin   47         59          42          52          41         45
Milan    46         64          40          46          37         44
.
.
.
</code>```

Expected output:

```<code>City    MIN MAX Date
Paris   44  61  2/16/2020
Paris   41  52  2/17/2020
Paris   39  47  2/18/2020
Berlin  47  59  2/16/2020
Berlin  42  52  2/17/2020
Berlin  41  45  2/18/2020
Milan   46  64  2/16/2020
Milan   40  46  2/17/2020
Milan   37  44  2/18/2020
</code>```

I tried to use df= pd.read_csv(StringIO(csv.text), header=[1]) to select the second row as the header but how to set only City, Min, Max, and create 'Date' which the new column?

I'm grateful if you can help me.

Cheers,

答:
I read your question as a struggle to read the dataframe, then stacking the columns to achieve the output you want. Assuming you have a data.csv file that looks like this:

```<code>        2/16/2020  2/16/2020   2/17/2020   2/17/2020   2/18/2020  2/18/2020
        Min        Max         Min         Max         Min        Max
Paris    44         61          41          52          39         47
Berlin   47         59          42          52          41         45
Milan    46         64          40          46          37         44
</code>```

Your need to read it twice, once for the headers and once for the data:

```<code># Read the headers on the first 2 lines
header = pd.read_csv('data.csv', sep='\\s+', nrows=2, header=None)

# There are 7 columns but only 6 headers
# We have to manually create the missing one
header.insert(0, 'City', 'City')

# Make a MultiIndex containing the names of the 7 columns
names = pd.MultiIndex.from_frame(header.T)

# Now read the data
df = pd.read_csv('data.csv', sep='\\s+', names=names, skiprows=2)

# Then the transformation
final = df.set_index(('City', 'City')) \
    .stack(0) \
    .rename_axis(['City', 'Date']) \
    .reset_index()
</code>```

Body:
I'm working with pandas, and I'm trying to convert the header row of the dataframe to a column, i have tried the stack() function, but it looks not working for me.

I have a file which contains data as the follow, it has double header - date and temperature (min & Max)

      2/16/2020  2/16/2020   2/17/2020   2/17/2020   2/18/2020  2/18/2020   ......
         Min        Max         Min         Max         Min        Max
Paris    44         61          41          52          39         47
Berlin   47         59          42          52          41         45
Milan    46         64          40          46          37         44
.
.
.

Expected output:

City    MIN MAX Date
Paris   44  61  2/16/2020
Paris   41  52  2/17/2020
Paris   39  47  2/18/2020
Berlin  47  59  2/16/2020
Berlin  42  52  2/17/2020
Berlin  41  45  2/18/2020
Milan   46  64  2/16/2020
Milan   40  46  2/17/2020
Milan   37  44  2/18/2020

I tried to use df= pd.read_csv(StringIO(csv.text), header=[1]) to select the second row as the header but how to set only City, Min, Max, and create 'Date' which the new column?

I'm grateful if you can help me.

Cheers,

Body:
I read your question as a struggle to read the dataframe, then stacking the columns to achieve the output you want. Assuming you have a data.csv file that looks like this:

        2/16/2020  2/16/2020   2/17/2020   2/17/2020   2/18/2020  2/18/2020
        Min        Max         Min         Max         Min        Max
Paris    44         61          41          52          39         47
Berlin   47         59          42          52          41         45
Milan    46         64          40          46          37         44

Your need to read it twice, once for the headers and once for the data:

# Read the headers on the first 2 lines
header = pd.read_csv('data.csv', sep='\\s+', nrows=2, header=None)

# There are 7 columns but only 6 headers
# We have to manually create the missing one
header.insert(0, 'City', 'City')

# Make a MultiIndex containing the names of the 7 columns
names = pd.MultiIndex.from_frame(header.T)

# Now read the data
df = pd.read_csv('data.csv', sep='\\s+', names=names, skiprows=2)

# Then the transformation
final = df.set_index(('City', 'City')) \
    .stack(0) \
    .rename_axis(['City', 'Date']) \
    .reset_index()


答:
So you can write something like: x = i++; I don't think that it is needed; it is just used this way in general and it might cause problem in code that assumes that the operator return the value/reference - in which case you won't be able to utilize your object in that code if it doesn't return appropriate value. Furthermore, other programmers might find your code misleading if operators do weird things they don't expect.

Note: some types return copy of the object instead of reference: i++ (copy of old val) vs ++i (new value).

Title: Why is a reference needed in operator overloading?

Body:
In what situations would a reference be needed when overloading, as the code still works without it? I am aware it has something to with chaining, but I do not understand exactly why the reference is needed.

Example:

Object& operator++();


问:
TypeError: 'module' object is not subscriptable (Python)
At line 15, getting an error

TypeError: 'module' object is not subscriptable

```<code>import csv
from wsgiref import headers

size = []
gender = []
gender_count = []
final_gender_list = {
    'male': 0,
    'female': 0
}
with open('Clothing.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)
    for line in csv_reader:
        size.append(line[headers['size']])
        gender.append(line[headers['gender']])
    for index, item in enumerate(size):
        if item == 'S':
            gender_count.append(gender[index])
        final_gender_list['male'] = gender_count.count('Male')
        final_gender_list['female'] = gender_count.count('Female')
    print(final_gender_list)
</code>```

答: According to the documentation and the actual code, headers is a module itself, so headers['size'] makes no sense.

Body:
At line 15, getting an error

TypeError: 'module' object is not subscriptable

import csv
from wsgiref import headers

size = []
gender = []
gender_count = []
final_gender_list = {
    'male': 0,
    'female': 0
}
with open('Clothing.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)
    for line in csv_reader:
        size.append(line[headers['size']])
        gender.append(line[headers['gender']])
    for index, item in enumerate(size):
        if item == 'S':
            gender_count.append(gender[index])
        final_gender_list['male'] = gender_count.count('Male')
        final_gender_list['female'] = gender_count.count('Female')
    print(final_gender_list)


问:
Convert a list of strings containing list-of-integers into an array
I have a series that is a list of lists that contain integers that I am attempting to turn into an array. This is a small snip-it of the list I am trying to convert into an array.

```<code>['[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]',

'[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]',

'[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]',

'[0, 0, 0, 0, 0, 0, 0, 1, 0, 1]',

'[0, 0, 0, 0, 0, 0, 0, 1, 1, 1]']
</code>```

I've tried to replace the quotes with .replace, but that hasn't worked out.

```<code>sequence = [i.replace(" '' ", ' ') for i in sequence]
</code>```

Body:
I have a series that is a list of lists that contain integers that I am attempting to turn into an array. This is a small snip-it of the list I am trying to convert into an array.

['[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]',

'[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]',

'[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]',

'[0, 0, 0, 0, 0, 0, 0, 1, 0, 1]',

'[0, 0, 0, 0, 0, 0, 0, 1, 1, 1]']

I've tried to replace the quotes with .replace, but that hasn't worked out.

sequence = [i.replace(" '' ", ' ') for i in sequence]

Body:
You can use ast.literal_eval to change the string to list of lists of ints

sequence = [literal_eval(i) for i in sequence]

# [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]

You can change it to numpy array

import numpy as np

array = np.asarray(sequence)
print(array)

output

[[0 0 0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 0 1 0 0]
 [0 0 0 0 0 0 0 1 0 1]
 [0 0 0 0 0 0 0 1 1 1]]

Or to 1d pandas array

import pandas as pd

array = pd.array([item for items in sequence for item in items])
print(array)

outout

<IntegerArray>
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
Length: 50, dtype: Int64


问:
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 ?

答:
You can do it with several mask. First check where the value is 1 in taken. Then you need to check either: still the same id and difference with the previous row is not 0 or not same idea:</p>

```<code>print (df[df.taken.eq(1) & (df.id.diff().eq(0) & df.taken.diff().ne(0) | df.id.diff().ne(0))])
   id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1
</code>```

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:
You can do it with several mask. First check where the value is 1 in taken. Then you need to check either: still the same id and difference with the previous row is not 0 or not same idea:

print (df[df.taken.eq(1) & (df.id.diff().eq(0) & df.taken.diff().ne(0) | df.id.diff().ne(0))])
   id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1


问:
I have 2 boxes and a picture. The user can drag the picture between the 2 boxes. How do I tell which box the picture is dragged from?
I have 2 boxes and a picture. The user can drag the picture between the 2 boxes. How do I tell which box the picture is dragged from? I tried looking at the parent element of the picture but that didn't work because the HTML doesn't change, I guess.

<!DOCTYPE html>

```

Or, view a TryIt here: https://www.w3schools.com/code/tryit.asp?filename=GBYRXSX3L0PP

Thanks in advance!

答:
On drop() function you get the a parameter ev. You can get from this one the id of the target using ev.toElement.id. You can so just check wich id has the target:

<!DOCTYPE html>

```

Body:
I have 2 boxes and a picture. The user can drag the picture between the 2 boxes. How do I tell which box the picture is dragged from? I tried looking at the parent element of the picture but that didn't work because the HTML doesn't change, I guess.

<!DOCTYPE html>

Or, view a TryIt here: https://www.w3schools.com/code/tryit.asp?filename=GBYRXSX3L0PP

Thanks in advance!

Body:
On drop() function you get the a parameter ev. You can get from this one the id of the target using ev.toElement.id. You can so just check wich id has the target:

<!DOCTYPE html>
<html>

<head>
  <script>
    function allowDrop(ev) {
      ev.preventDefault();
    }

    function drag(ev) {
      ev.dataTransfer.setData("text", ev.target.id);
    }

    function dropone(ev) {
      ev.preventDefault();
      var data = ev.dataTransfer.getData("text");
      var nodeCopy = document.getElementById(data).cloneNode(true);
      nodeCopy.id = "newId";
      nodeCopy.setAttribute("style", "position:absolute; left:" + ev.x + "px;top:" + ev.y + "px;transform:translate(-" + nodeCopy.width / 2 + "px,-" + nodeCopy.height / 2 + "px)");
      ev.target.appendChild(nodeCopy);
    }

    function drop(ev) {
      if (ev.toElement.id == 'redbox') {    // <-- Check the id
        alert("YOU DRAGGED FROM THE BLUE BOX!");
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        var nodeCopy = document.getElementById(data).cloneNode(true);
        nodeCopy.id = "newId";
        nodeCopy.setAttribute("style", "position:absolute; left:" + ev.x + "px;top:" + ev.y + "px;transform:translate(-" + nodeCopy.width / 2 + "px,-" + nodeCopy.height / 2 + "px)");
        ev.target.appendChild(nodeCopy);
      } else if (ev.toElement.id == 'bluebox') {  // <-- Check the id
        alert("YOU DRAGGED FROM THE RED BOX!");
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        var nodeCopy = document.getElementById(data).cloneNode(true);
        nodeCopy.id = "newId";
        nodeCopy.setAttribute("style", "position:absolute; left:" + ev.x + "px;top:" + ev.y + "px;transform:translate(-" + nodeCopy.width / 2 + "px,-" + nodeCopy.height / 2 + "px)");
        ev.target.appendChild(nodeCopy);
      }
    }
  </script>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      display: block;
      height: 300px;
      width: 300px;
      background-color: red;
    }

    .boxtwo {
      display: block;
      height: 300px;
      width: 300px;
      background-color: lightblue;
    }
  </style>
</head>

<body>

  <span id="redbox" class="box" ondrop="drop(event)" ondragover="allowDrop(event)"></span>

  <br />

  <span id="bluebox" class="boxtwo" ondrop="drop(event)" ondragover="allowDrop(event)">
  <div id="picture" ondrop="drop(event)">
      <img src="https://www.w3schools.com/html/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
  </div>
</span>
</body>

</html>


问:
Finding the different elements between two ArrayLists in Java
How can I know the different element between 2 array list in java? I need the exact element not a Boolean value which can be retrieved using removeAll().

答:
If I understood your question correctly then following method nonOverLap in the code below should get you that:

```<code><T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
    Set<T> union = new HashSet<>(coll1);
    union.addAll(new HashSet<>(coll2));
    return union;
}

<T> Collection<T> intersect(Collection<T> coll1, Collection<T> coll2) {
    Set<T> intersection = new HashSet<>(coll1);
    intersection.retainAll(new HashSet<>(coll2));
    return intersection;
}

<T> Collection<T> nonOverLap(Collection<T> coll1, Collection<T> coll2) {
    Collection<T> result = union(coll1, coll2);
    result.removeAll(intersect(coll1, coll2));
    return result;
}
</code>```

Body:
If I understood your question correctly then following method nonOverLap in the code below should get you that:

<T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
    Set<T> union = new HashSet<>(coll1);
    union.addAll(new HashSet<>(coll2));
    return union;
}

<T> Collection<T> intersect(Collection<T> coll1, Collection<T> coll2) {
    Set<T> intersection = new HashSet<>(coll1);
    intersection.retainAll(new HashSet<>(coll2));
    return intersection;
}

<T> Collection<T> nonOverLap(Collection<T> coll1, Collection<T> coll2) {
    Collection<T> result = union(coll1, coll2);
    result.removeAll(intersect(coll1, coll2));
    return result;
}