问:
Cyclic Dependency
I am having this error...I kind of know what it mean but I can't figure how to go about it. Someone willing to help me out? Thanks.

APPLICATION FAILED TO START

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  securityConfig (field private ro.sda.finalproject.service.UserService ro.sda.finalproject.config.security.SecurityConfig.userService)
↑     ↓
|  userService defined in file [D:\Proiect-Final\target\classes\ro\sda\finalproject\service\UserService.class]
└─────┘

enter image description here
Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Process finished with exit code 0

See below the two classes:

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.sda.finalproject.config.security.UserPrincipal;
import ro.sda.finalproject.controller.exception.ResourceAlreadyExistsException;
import ro.sda.finalproject.controller.exception.ResourceNotFoundException;
import ro.sda.finalproject.dto.UserDto;
import ro.sda.finalproject.enums.RoleType;
import ro.sda.finalproject.mapper.UserMapper;
import ro.sda.finalproject.model.Role;
import ro.sda.finalproject.model.User;
import ro.sda.finalproject.repository.RoleRepository;
import ro.sda.finalproject.repository.UserRepository;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;
    private RoleRepository roleRepository;
    private UserMapper userMapper;
    private PasswordEncoder passwordEncoder;

    public UserService(UserRepository userRepository,
                       RoleRepository roleRepository,
                       UserMapper userMapper,
                       PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Transactional
    public void save(UserDto userDto) {
        log.info("save user {}", userDto);

        String email = userDto.getEmail();
        userRepository.findByEmail(email)
                .map(existingUser -> {
                    log.error("user with email {} already exists", email);
                    throw new ResourceAlreadyExistsException("user with email " + email + " already exists");
                })
                .orElseGet(() -> saveUser(userDto));
    }

    public List<UserDto> findAll() {
        log.info("find users");

        return userRepository.findAll().stream()
                .map(user -> userMapper.map(user))
                .collect(Collectors.toList());
    }

    public User findByEmail(String email) {
        log.info("find user by email {}", email);

        return userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException(email + " not found"));
    }

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return userRepository.findByEmail(email)
                .map(user -> {

                    Set<Role> roles = roleRepository.getRoles(user.getUserId());
                    return new UserPrincipal(user, roles);
                })
                .orElseThrow(() -> new UsernameNotFoundException(email + " not found"));
    }

    public UserDto findById(Long id) {

        // find by id from repo
        return userRepository.findById(id)
                .map(user -> userMapper.map(user))
                .orElseThrow(() -> new ResourceNotFoundException("user not found"));
    }

    public void update(UserDto dto) {
        userRepository.findById(dto.getUserId())
                .map(user -> userMapper.update(user, dto))
                .map(updatedUser -> userRepository.save(updatedUser))
                .orElseThrow(() -> {
                    throw new ResourceNotFoundException("user not found");
                });
    }

    public void enable(Long id) {
        log.info("enable user {}", id);

        userRepository.findById(id)
                .map(foundUser -> {
                    foundUser.setEnabled(true);
                    return userRepository.save(foundUser);
                })
                .orElseThrow(() -> new ResourceNotFoundException("user not found"));
    }

    public void disable(Long id) {
        log.info("disable user {}", id);

        Role adminRole = roleRepository.findByType(RoleType.ADMIN)
                .orElseThrow(() -> new ResourceNotFoundException("role not found"));
        long enabledAdminsCount = userRepository.findAll().stream()
                .filter(user -> user.isEnabled())
                .filter(user -> user.getRoles().contains(adminRole))
                .count();
        if (enabledAdminsCount > 1) {
            userRepository.findById(id)
                    .map(foundUser -> {
                        foundUser.setEnabled(false);
                        return userRepository.save(foundUser);
                    })
                    .orElseThrow(() -> new ResourceNotFoundException("user not found"));

        } else {
            throw new RuntimeException("can't disable last admin");
        }
    }

    private User saveUser(UserDto userDto) {
        Role userRole = roleRepository.findByType(RoleType.USER)
                .orElseThrow(() -> new ResourceNotFoundException("role not found"));

        // convert user dto to user
        User user = userMapper.map(userDto);
        // encode password
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.addRole(userRole);
        return userRepository.save(user);
    }

    public void delete(Long id) {
        userRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("user not found" + id));
        userRepository.deleteById(id);
    }
}
</code>```
```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import ro.sda.finalproject.service.UserService;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // common
                .antMatchers("/", "/product-photos/**", "/index", "/about", "/contact", "/register/**", "/addToCart", "/login", "/search", "/shoppingCart").permitAll()

                // no authorization needed
                .antMatchers("/home", "/products/**").permitAll()

                // static resources
                .antMatchers("/static/favicon.ico", "/images/**", "/js/**", "/css/**").permitAll()

                // features and permissions
                // TODO: add all features before production
                .antMatchers().hasRole("ADMIN")
                .anyRequest().authenticated();

        // add custom login form
        http.formLogin(form -> form.loginPage("/login").permitAll());

        // login with email as username
        http.formLogin().usernameParameter("email");

        // after successful login go to page
        // TODO: find a way to load the correct page depending on role
        http.formLogin().defaultSuccessUrl("/home", true);

        // after logout go to login
        http.logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/home")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .permitAll();

        // add a custom access denied handler 404 unauthorized
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers("/resources/**", "/static/**", "/webjars/**");
    }

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

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider createDaoAuthentication() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userService);
        provider.setPasswordEncoder(passwordEncoder());

        return provider;
    }

    // notifies the session registry that the session is destroyed on logout
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }
}
</code>```

I tried eliminating the dependency one after another without success

Title: Cyclic Dependency

Body:
I am having this error...I kind of know what it mean but I can't figure how to go about it. Someone willing to help me out? Thanks.

APPLICATION FAILED TO START

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  securityConfig (field private ro.sda.finalproject.service.UserService ro.sda.finalproject.config.security.SecurityConfig.userService)
↑     ↓
|  userService defined in file [D:\Proiect-Final\target\classes\ro\sda\finalproject\service\UserService.class]
└─────┘

enter image description here
Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Process finished with exit code 0

See below the two classes:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.sda.finalproject.config.security.UserPrincipal;
import ro.sda.finalproject.controller.exception.ResourceAlreadyExistsException;
import ro.sda.finalproject.controller.exception.ResourceNotFoundException;
import ro.sda.finalproject.dto.UserDto;
import ro.sda.finalproject.enums.RoleType;
import ro.sda.finalproject.mapper.UserMapper;
import ro.sda.finalproject.model.Role;
import ro.sda.finalproject.model.User;
import ro.sda.finalproject.repository.RoleRepository;
import ro.sda.finalproject.repository.UserRepository;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;
    private RoleRepository roleRepository;
    private UserMapper userMapper;
    private PasswordEncoder passwordEncoder;

    public UserService(UserRepository userRepository,
                       RoleRepository roleRepository,
                       UserMapper userMapper,
                       PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Transactional
    public void save(UserDto userDto) {
        log.info("save user {}", userDto);

        String email = userDto.getEmail();
        userRepository.findByEmail(email)
                .map(existingUser -> {
                    log.error("user with email {} already exists", email);
                    throw new ResourceAlreadyExistsException("user with email " + email + " already exists");
                })
                .orElseGet(() -> saveUser(userDto));
    }

    public List<UserDto> findAll() {
        log.info("find users");

        return userRepository.findAll().stream()
                .map(user -> userMapper.map(user))
                .collect(Collectors.toList());
    }

    public User findByEmail(String email) {
        log.info("find user by email {}", email);

        return userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException(email + " not found"));
    }

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return userRepository.findByEmail(email)
                .map(user -> {

                    Set<Role> roles = roleRepository.getRoles(user.getUserId());
                    return new UserPrincipal(user, roles);
                })
                .orElseThrow(() -> new UsernameNotFoundException(email + " not found"));
    }

    public UserDto findById(Long id) {

        // find by id from repo
        return userRepository.findById(id)
                .map(user -> userMapper.map(user))
                .orElseThrow(() -> new ResourceNotFoundException("user not found"));
    }

    public void update(UserDto dto) {
        userRepository.findById(dto.getUserId())
                .map(user -> userMapper.update(user, dto))
                .map(updatedUser -> userRepository.save(updatedUser))
                .orElseThrow(() -> {
                    throw new ResourceNotFoundException("user not found");
                });
    }

    public void enable(Long id) {
        log.info("enable user {}", id);

        userRepository.findById(id)
                .map(foundUser -> {
                    foundUser.setEnabled(true);
                    return userRepository.save(foundUser);
                })
                .orElseThrow(() -> new ResourceNotFoundException("user not found"));
    }

    public void disable(Long id) {
        log.info("disable user {}", id);

        Role adminRole = roleRepository.findByType(RoleType.ADMIN)
                .orElseThrow(() -> new ResourceNotFoundException("role not found"));
        long enabledAdminsCount = userRepository.findAll().stream()
                .filter(user -> user.isEnabled())
                .filter(user -> user.getRoles().contains(adminRole))
                .count();
        if (enabledAdminsCount > 1) {
            userRepository.findById(id)
                    .map(foundUser -> {
                        foundUser.setEnabled(false);
                        return userRepository.save(foundUser);
                    })
                    .orElseThrow(() -> new ResourceNotFoundException("user not found"));

        } else {
            throw new RuntimeException("can't disable last admin");
        }
    }

    private User saveUser(UserDto userDto) {
        Role userRole = roleRepository.findByType(RoleType.USER)
                .orElseThrow(() -> new ResourceNotFoundException("role not found"));

        // convert user dto to user
        User user = userMapper.map(userDto);
        // encode password
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.addRole(userRole);
        return userRepository.save(user);
    }

    public void delete(Long id) {
        userRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("user not found" + id));
        userRepository.deleteById(id);
    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import ro.sda.finalproject.service.UserService;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // common
                .antMatchers("/", "/product-photos/**", "/index", "/about", "/contact", "/register/**", "/addToCart", "/login", "/search", "/shoppingCart").permitAll()

                // no authorization needed
                .antMatchers("/home", "/products/**").permitAll()

                // static resources
                .antMatchers("/static/favicon.ico", "/images/**", "/js/**", "/css/**").permitAll()

                // features and permissions
                // TODO: add all features before production
                .antMatchers().hasRole("ADMIN")
                .anyRequest().authenticated();

        // add custom login form
        http.formLogin(form -> form.loginPage("/login").permitAll());

        // login with email as username
        http.formLogin().usernameParameter("email");

        // after successful login go to page
        // TODO: find a way to load the correct page depending on role
        http.formLogin().defaultSuccessUrl("/home", true);

        // after logout go to login
        http.logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/home")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .permitAll();

        // add a custom access denied handler 404 unauthorized
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers("/resources/**", "/static/**", "/webjars/**");
    }

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

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider createDaoAuthentication() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userService);
        provider.setPasswordEncoder(passwordEncoder());

        return provider;
    }

    // notifies the session registry that the session is destroyed on logout
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }
}

I tried eliminating the dependency one after another without success


来源: stackexchange

问:
FullCalendar timeGridPlugin is not working after I add a styled wrapper from emotion/styled
I am using FullCalendar and wanted to modify some of the styles within the component. I'm implementing it in a react project, but once I added the styled wrapper that will overwrite the internal styles my calendar loses the timeGridPlugin and does not show any times.

I followed this StackOverflow post already: is it possible Customise FullCalendar with css in react?

A condensed version of my code:

```<code>import styled from "@emotion/styled";
import FullCalendar, { formatDate } from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
</code>```
```<code>export const StyleWrapper = styled.div`
  .fc-toolbar-title {
    color: red;
  }
`;
</code>```
```<code>render() {
    return (
      <div
        style={{
          height: "100vh",
          padding: "2em",
          fontFamily: `'Quicksand', sans-serif`,
        }}
        data-testid="FullCalender"
      >
        <StyleWrapper>
          <FullCalendar
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            headerToolbar={{
              start: "prev,next today",
              center: "title",
              end: "dayGridMonth,timeGridWeek,timeGridDay",
            }}
            initialView="timeGridWeek"
            editable={true}
            selectable={true}
            selectMirror={true}
            dayMaxEvents={true}
            weekends={true}
            select={this.handleSelectSlot}
            eventClick={this.handleSelectEvent}
            eventDrop={this.handleEventDrop}
            height={"90%"}
          />
        </StyleWrapper>
      </div>
    );
  }
</code>```

My question: How to add styling without affecting the timeGridPlugin?

When I comment out , then the timeGridPlugin works: (https://i.stack.imgur.com/UgdYX.png)

With StyleWrapper: (https://i.stack.imgur.com/imzWv.png)

ContentLicense: CC BY-SA 4.0

Body:
I am using FullCalendar and wanted to modify some of the styles within the component. I'm implementing it in a react project, but once I added the styled wrapper that will overwrite the internal styles my calendar loses the timeGridPlugin and does not show any times.

I followed this StackOverflow post already: is it possible Customise FullCalendar with css in react?

A condensed version of my code:

import styled from "@emotion/styled";
import FullCalendar, { formatDate } from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";

export const StyleWrapper = styled.div`
  .fc-toolbar-title {
    color: red;
  }
`;

render() {
    return (
      <div
        style={{
          height: "100vh",
          padding: "2em",
          fontFamily: `'Quicksand', sans-serif`,
        }}
        data-testid="FullCalender"
      >

    );
  }

My question: How to add styling without affecting the timeGridPlugin?

When I comment out , then the timeGridPlugin works: (https://i.stack.imgur.com/UgdYX.png)

With StyleWrapper: (https://i.stack.imgur.com/imzWv.png)


问:
Defining a closeEvent function with parameters in PyQt5
How do I put parameters in closeEvent function and then whenever the window is closed, the closeEvent function is called with a particular argument that I want to pass to it?</p>


问:
Get the initial scrollwidth of ref
I have an table and a search input which is searching data inside table.
I should have the tables data scrollWidth for creating tooltip (if the text is bigger than the space).
The ref.current.scrollWidth at first gives me the correct scrollWidth but after typing smth in input the scrollWidth is changing. The problem is that I need the initial ref scrollWidth when searching. How to save the first getting scrollWidth and do not allow update the value.

I tried to save some state and update only on useEffect but thats not helping

I'm using ref.current.scrollWidth

I tried to save the data inside useState like

```<code>    const [descRef, setDestref] = useState<number | undefined>();
</code>```

And using useEffect to add the data to descRef

```<code>   useEffect(() => {
    setDestref(elementRef.current?.scrollWidth);
   }, []);
</code>```

Title: Get the initial scrollwidth of ref

Body:
I have an table and a search input which is searching data inside table.
I should have the tables data scrollWidth for creating tooltip (if the text is bigger than the space).
The ref.current.scrollWidth at first gives me the correct scrollWidth but after typing smth in input the scrollWidth is changing. The problem is that I need the initial ref scrollWidth when searching. How to save the first getting scrollWidth and do not allow update the value.

I tried to save some state and update only on useEffect but thats not helping

I'm using ref.current.scrollWidth

I tried to save the data inside useState like

    const [descRef, setDestref] = useState<number | undefined>();

And using useEffect to add the data to descRef

   useEffect(() => {
    setDestref(elementRef.current?.scrollWidth);
   }, []);


问:
Dockerfile copy reference not working in Windows
I've got a Dockerfile that I'm using across Mac, Linux, and Windows. It works fine for Mac & Linux, but Windows 10 is throwing errors.

The Dockerfile:

```<code>FROM nginx:1.23.3
WORKDIR /
COPY /nginx-setup.sh /docker-entrypoint.d
RUN chmod +x /docker-entrypoint.d/nginx-setup.sh
</code>```

The file structure:

```<code>- project_root
    - docker-compose.yml
    - nginx
        - Dockerfile
        - nginx-setup.sh
</code>```

When I run docker compose up -d on Mac/Linux, everything works fine. When I run it on Windows, I get the error:

```<code>/docker-entrypoint.sh: 31: /docker-entrypoint.d/nginx-setup.sh: not found
</code>```

I've tried:

```<code>COPY /nginx-setup.sh /docker-entrypoint.d
COPY nginx-setup.sh /docker-entrypoint.d
COPY /nginx-setup.sh /docker-entrypoint.d/nginx-setup.sh
</code>```

The containers spin up, the other services work fine, but the Nginx one throws this error when looking for the setup script. I can't figure out what I'm missing.

All suggestions welcome. Thanks in advance!

Body:
I've got a Dockerfile that I'm using across Mac, Linux, and Windows. It works fine for Mac & Linux, but Windows 10 is throwing errors.

The Dockerfile:

FROM nginx:1.23.3
WORKDIR /
COPY /nginx-setup.sh /docker-entrypoint.d
RUN chmod +x /docker-entrypoint.d/nginx-setup.sh

The file structure:

- project_root
    - docker-compose.yml
    - nginx
        - Dockerfile
        - nginx-setup.sh

When I run docker compose up -d on Mac/Linux, everything works fine. When I run it on Windows, I get the error:

/docker-entrypoint.sh: 31: /docker-entrypoint.d/nginx-setup.sh: not found

I've tried:

COPY /nginx-setup.sh /docker-entrypoint.d
COPY nginx-setup.sh /docker-entrypoint.d
COPY /nginx-setup.sh /docker-entrypoint.d/nginx-setup.sh

The containers spin up, the other services work fine, but the Nginx one throws this error when looking for the setup script. I can't figure out what I'm missing.

All suggestions welcome. Thanks in advance!


问:
How to return only 3 posts in a Meta Box view?
I have a custom post type named event. At the moment it has about 20 posts.

On the main events page the included MB view below displays all of the posts, chronologically ordered by the start date of the events.

I would like to show only the first 3 event posts on the homepage, but limiting the posts_per_page to 3 shows no results. If I increase that value to 10, for example, I do get posts to display, but they aren't the next upcoming events.

Is it possible to only display the next (chronologically speaking) 3 upcoming events?

I can't use the posts' publication dates because that doesn't correlate with the event's actual start date.

This code is running in the Meta Box WordPress plugin and uses Twig.

```<code>{% set args = {  post_type: "event", posts_per_page: 3 } %}
{% set posts = mb.get_posts( args ) %}
{% for key, post in posts|sort((a, b) => a.bdr_event_start_date <=> b.bdr_event_start_date) %}
{% if post.bdr_event_start_date >= "now"|date("Y-m-d") or post.bdr_event_end_date >= "now"|date("Y-m-d") %}
    <div class="bxb-event-grid-item">
        <div>
            <img src="{{ post.thumbnail.large.url }}" alt="{{ post.thumbnail.large.alt }}" width="{{ post.thumbnail.large.width }}" height="{{ post.thumbnail.large.height }}">
            <a href="{{ post.url }}"><h2>{{ post.post_title}}</h2></a>
            <div class="bxb-event-date-range">
                {% if post.bdr_event_start_date == post.bdr_event_end_date %}
                    {{ post.bdr_event_start_date | date( 'F jS, Y' ) }}
                {% endif %}
                {% if post.bdr_event_start_date != post.bdr_event_end_date %}
                    {{ post.bdr_event_start_date | date( 'F jS' ) }}—{{ post.bdr_event_end_date | date( 'F jS, Y' ) }}
                {% endif %}
            </div>
        </div>
    </div>
{% endif %}
{% endfor %}
</code>```

Body:
I have a custom post type named event. At the moment it has about 20 posts.

On the main events page the included MB view below displays all of the posts, chronologically ordered by the start date of the events.

I would like to show only the first 3 event posts on the homepage, but limiting the posts_per_page to 3 shows no results. If I increase that value to 10, for example, I do get posts to display, but they aren't the next upcoming events.

Is it possible to only display the next (chronologically speaking) 3 upcoming events?

I can't use the posts' publication dates because that doesn't correlate with the event's actual start date.

This code is running in the Meta Box WordPress plugin and uses Twig.

{% set args = {  post_type: "event", posts_per_page: 3 } %}
{% set posts = mb.get_posts( args ) %}
{% for key, post in posts|sort((a, b) => a.bdr_event_start_date <=> b.bdr_event_start_date) %}
{% if post.bdr_event_start_date >= "now"|date("Y-m-d") or post.bdr_event_end_date >= "now"|date("Y-m-d") %}

{{ post.post_title}}

                {% if post.bdr_event_start_date == post.bdr_event_end_date %}
                    {{ post.bdr_event_start_date | date( 'F jS, Y' ) }}
                {% endif %}
                {% if post.bdr_event_start_date != post.bdr_event_end_date %}
                    {{ post.bdr_event_start_date | date( 'F jS' ) }}—{{ post.bdr_event_end_date | date( 'F jS, Y' ) }}
                {% endif %}

{% endif %}
{% endfor %}


问:
How to delete a image file from external storage automatically?
I'm trying to figure out a way to delete images from the external storage automatically.

In my app, the user takes photos for some purposes which are saved in a folder created by the app inside the Pictures folder. After some time, the photos taken are of no use anymore. Therefore, I'm trying to write some code that enables the app to delete these photos by itself.

Before you ask, I'm aware that is not normal for an app to delete files from the app without any command from the user. But my app is used inside the company, only by employees etc.

I'm using ctx.contentResolver.delete(uri, null, null) to delete the image file. I have a catch to recover the SecurityException like this:

```<code>   catch (e: SecurityException) {
      val intentSender = when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
            MediaStore.createDeleteR`your text`equest(ctx.contentResolver,         listOf(uri)).intentSender
        }
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
            val recoverableSecurityException = e as? RecoverableSecurityException
            recoverableSecurityException?.userAction?.actionIntent?.intentSender
        }
        else -> null
    }
    intentSender?.let { sender ->
        intentSenderLauncher.launch(
            IntentSenderRequest.Builder(sender).build()
        )
    }
}
</code>```

And everything seems to work fine at a first look as the intent to accept appears -- but no image is shown and nothing gets deleted.

Am I doing something wrong? What could be a way to delete these files?

Body:
I'm trying to figure out a way to delete images from the external storage automatically.

In my app, the user takes photos for some purposes which are saved in a folder created by the app inside the Pictures folder. After some time, the photos taken are of no use anymore. Therefore, I'm trying to write some code that enables the app to delete these photos by itself.

Before you ask, I'm aware that is not normal for an app to delete files from the app without any command from the user. But my app is used inside the company, only by employees etc.

I'm using ctx.contentResolver.delete(uri, null, null) to delete the image file. I have a catch to recover the SecurityException like this:

   catch (e: SecurityException) {
      val intentSender = when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
            MediaStore.createDeleteR`your text`equest(ctx.contentResolver,         listOf(uri)).intentSender
        }
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
            val recoverableSecurityException = e as? RecoverableSecurityException
            recoverableSecurityException?.userAction?.actionIntent?.intentSender
        }
        else -> null
    }
    intentSender?.let { sender ->
        intentSenderLauncher.launch(
            IntentSenderRequest.Builder(sender).build()
        )
    }
}

And everything seems to work fine at a first look as the intent to accept appears -- but no image is shown and nothing gets deleted.

Am I doing something wrong? What could be a way to delete these files?


问:
XML vs HTML? Scrapy downloads html files but not xml files?
EDIT: This is only scraping the XML links from the crawled pages, not actually following the links to the XML pages themselves, which have a slightly different URL.  I need to adjust the rules so I can crawl those pages as well.  I'll post a solution once I've got it working.

http://www.digitalhumanities.org/dhq/vol/12/4/000401/000401.xml
vs.
http://www.digitalhumanities.org/dhq/vol/12/4/000401.xml

This script scrapes all the links, and should save all the files, but only the html files are actually saved.  The xml files are added to the csv but not downloaded.  This is a relatively simple script so what is the difference between the two?

Here's the error I'm getting.

```<code>2022-12-22 12:33:30 [scrapy.pipelines.files] WARNING: File (code: 302): Error downloading file from <GET http://www.digitalhumanities.org/dhq/vol/12/4/000407.xml> referred in <None>
2022-12-22 12:33:30 [scrapy.core.engine] DEBUG: Crawled (302) <GET http://www.digitalhumanities.org/dhq/vol/12/4/000408.xml> (referer: None)
2022-12-22 12:33:30 [scrapy.pipelines.files] WARNING: File (code: 302): Error downloading file from <GET http://www.digitalhumanities.org/dhq/vol/12/4/000408.xml> referred in <None>
</code>```

And example of the output:  https://pastebin.com/pDHvYTxF

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class DhqSpider(CrawlSpider):
    name = 'dhqfiles'
    allowed_domains = ['digitalhumanities.org']
    start_urls = ['http://www.digitalhumanities.org/dhq/vol/16/3/index.html']

    rules = (
            Rule(LinkExtractor(allow = 'index.html')),
            Rule(LinkExtractor(allow = 'vol'), callback='parse_article'),
        )

    def parse_article(self, response):
        article = {
            'xmllink' : response.urljoin(response.xpath('(//div[@class="toolbar"]/a[contains(@href, ".xml")]/@href)[1]').get()),
        }
        yield {'file_urls':[article['xmllink']]}
```

Body:
EDIT: This is only scraping the XML links from the crawled pages, not actually following the links to the XML pages themselves, which have a slightly different URL.  I need to adjust the rules so I can crawl those pages as well.  I'll post a solution once I've got it working.

http://www.digitalhumanities.org/dhq/vol/12/4/000401/000401.xml
vs.
http://www.digitalhumanities.org/dhq/vol/12/4/000401.xml

This script scrapes all the links, and should save all the files, but only the html files are actually saved.  The xml files are added to the csv but not downloaded.  This is a relatively simple script so what is the difference between the two?

Here's the error I'm getting.

2022-12-22 12:33:30 [scrapy.pipelines.files] WARNING: File (code: 302): Error downloading file from <GET http://www.digitalhumanities.org/dhq/vol/12/4/000407.xml> referred in <None>
2022-12-22 12:33:30 [scrapy.core.engine] DEBUG: Crawled (302) <GET http://www.digitalhumanities.org/dhq/vol/12/4/000408.xml> (referer: None)
2022-12-22 12:33:30 [scrapy.pipelines.files] WARNING: File (code: 302): Error downloading file from <GET http://www.digitalhumanities.org/dhq/vol/12/4/000408.xml> referred in <None>

And example of the output:  https://pastebin.com/pDHvYTxF

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class DhqSpider(CrawlSpider):
    name = 'dhqfiles'
    allowed_domains = ['digitalhumanities.org']
    start_urls = ['http://www.digitalhumanities.org/dhq/vol/16/3/index.html']

    rules = (
            Rule(LinkExtractor(allow = 'index.html')),
            Rule(LinkExtractor(allow = 'vol'), callback='parse_article'),
        )

    def parse_article(self, response):
        article = {
            'xmllink' : response.urljoin(response.xpath('(//div[@class="toolbar"]/a[contains(@href, ".xml")]/@href)[1]').get()),
        }
        yield {'file_urls':[article['xmllink']]}


问:
socket.io not working once deployed on 000webhost
I read through other post with similar issue which I couldn't solve. I created a simple chat using socket.io, express. On the localhost its working but not on the 000webhost.  I'm probably missing a code somewhere.

Tried adding line of codes on the server file and the client side but still couldn't get it to run.

server side

```<code>const express = require("express");
const Socket = require("socket.io");

const app = express();

const server = require("http").createServer(app);

const io = Socket(server, {
    cors: {
        origin: "*",
        method: ["GET", "POST"]
    }
})

let PORT = 5000;

server.listen(PORT, () => {
    console.log("listening on port: ", PORT)
})

const users = [];

io.on("connection", (socket) => {

    console.log("connected to", socket.id)

    socket.on("adduser", (username)=>{
        socket.user = username;
        users.push(username);
        io.sockets.emit("users", users)
    })
    socket.on("message", (message)=>{

        io.sockets.emit("message_client", {
            message,
            user: socket.user
        })
    })

    socket.on("disconnect", () => {
        console.log("we are disconnecting...: ", socket.user)

        if (socket.user){
            users.splice(users.indexOf(socket.user), 1)

            io.sockets.emit("users", users);

            console.log('remaining users: ', users)
        }
    })
})
</code>```

Body:
I read through other post with similar issue which I couldn't solve. I created a simple chat using socket.io, express. On the localhost its working but not on the 000webhost.  I'm probably missing a code somewhere.

Tried adding line of codes on the server file and the client side but still couldn't get it to run.

server side

const express = require("express");
const Socket = require("socket.io");

const app = express();

const server = require("http").createServer(app);

const io = Socket(server, {
    cors: {
        origin: "*",
        method: ["GET", "POST"]
    }
})

let PORT = 5000;

server.listen(PORT, () => {
    console.log("listening on port: ", PORT)
})

const users = [];

io.on("connection", (socket) => {

    console.log("connected to", socket.id)

    socket.on("adduser", (username)=>{
        socket.user = username;
        users.push(username);
        io.sockets.emit("users", users)
    })
    socket.on("message", (message)=>{

        io.sockets.emit("message_client", {
            message,
            user: socket.user
        })
    })

    socket.on("disconnect", () => {
        console.log("we are disconnecting...: ", socket.user)

        if (socket.user){
            users.splice(users.indexOf(socket.user), 1)

            io.sockets.emit("users", users);

            console.log('remaining users: ', users)
        }
    })
})


问:
DropInfo in performDrop method doesn't contain my drag object in SwiftUI
I have these extensions to my NSObject, Codable class:

extension SavingsGoal: NSItemProviderWriting {
    public static let typeIdentifier = "com.AaronLBratcher.SavingsGoal.Drag"
    public static var writableTypeIdentifiersForItemProvider: [String] { [typeIdentifier] }

    public typealias DragHandler = (Data?, Error?) -> Void
    public func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping DragHandler) -> Progress? {
        do {
            print("^^^ encoding")
            let encoder = JSONEncoder()
            encoder.outputFormatting = .prettyPrinted
            completionHandler(try encoder.encode(self), nil)
        } catch {
            completionHandler(nil, error)
        }

        return nil
    }
}

extension SavingsGoal: NSItemProviderReading {
    public static var readableTypeIdentifiersForItemProvider: [String] { [typeIdentifier] }

    public static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> SavingsGoal {
        print("^^^ decoding")
        let decoder = JSONDecoder()
        return try decoder.decode(SavingsGoal.self, from: data)
    }
}
```
<p>and these <code>onDrag</code>, <code>onDrop</code> method calls on my Views:</p>
<pre class="lang-swift prettyprint-override"><code>.onDrag { NSItemProvider(object: goal) }

.onDrop(of: [SavingsGoal.typeIdentifier], delegate: viewModel)
</code>```

Visually the drag works, showing a plus when it hits the target View, however only the delegate's performDrop call is made. The loadData and object methods are not called in the extensions and the DropInfo doesn't contain my object.

I have carefully checked and rechecked the code against available examples and cannot find what I did wrong.

Full test project is here: https://github.com/AaronBratcher/DragTest

Body:
I have these extensions to my NSObject, Codable class:

extension SavingsGoal: NSItemProviderWriting {
    public static let typeIdentifier = "com.AaronLBratcher.SavingsGoal.Drag"
    public static var writableTypeIdentifiersForItemProvider: [String] { [typeIdentifier] }

    public typealias DragHandler = (Data?, Error?) -> Void
    public func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping DragHandler) -> Progress? {
        do {
            print("^^^ encoding")
            let encoder = JSONEncoder()
            encoder.outputFormatting = .prettyPrinted
            completionHandler(try encoder.encode(self), nil)
        } catch {
            completionHandler(nil, error)
        }

        return nil
    }
}

extension SavingsGoal: NSItemProviderReading {
    public static var readableTypeIdentifiersForItemProvider: [String] { [typeIdentifier] }

    public static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> SavingsGoal {
        print("^^^ decoding")
        let decoder = JSONDecoder()
        return try decoder.decode(SavingsGoal.self, from: data)
    }
}

and these onDrag, onDrop method calls on my Views:

.onDrag { NSItemProvider(object: goal) }

.onDrop(of: [SavingsGoal.typeIdentifier], delegate: viewModel)

Visually the drag works, showing a plus when it hits the target View, however only the delegate's performDrop call is made. The loadData and object methods are not called in the extensions and the DropInfo doesn't contain my object.

I have carefully checked and rechecked the code against available examples and cannot find what I did wrong.

Full test project is here: https://github.com/AaronBratcher/DragTest


问:
count and group values in column with condition in R
I would find a fast way to get a count of values in specific column that match some conditions and then produce a summary table for each condition.

Specifically, let's say this is my df:

```<code>df <- data.frame(X = sample(1:100))
</code>```

To know how many observations are less than 25, between 25 and 50 and greater than 50 I simply use count function:

```<code>count(df, df$X <25)
count(df, df$X >=25 & df$X <=50)
count(df, df$X > 50)
</code>```

I was just wondering, if there is a way to get the same results in a more efficient way, and maybe in table format, something like this:

```<code><25     24
25-50   26
>50     50
</code>```

Thanks in advance for any suggestion.

Body:
I would find a fast way to get a count of values in specific column that match some conditions and then produce a summary table for each condition.

Specifically, let's say this is my df:

df <- data.frame(X = sample(1:100))

To know how many observations are less than 25, between 25 and 50 and greater than 50 I simply use count function:

count(df, df$X <25)
count(df, df$X >=25 & df$X <=50)
count(df, df$X > 50)

I was just wondering, if there is a way to get the same results in a more efficient way, and maybe in table format, something like this:

<25     24
25-50   26
>50     50

Thanks in advance for any suggestion.


问:
EclipseCDT will not debug executable: Error creating process
I just installed EclipseCDT 2022-12, created the HelloWorld example app, compiled, but when I debug I get an error.  I have both current MSYS2 (MinGW64) and Cygwin64 installed, neither environment works and fails with the same error:

```<code>Error in final launch sequence:

Failed to execute MI command:
-exec-run
Error message from debugger back end:
Error creating process /cygdrive/c/Windows/system32/C:/Projects/cc3135/hello/C:/Projects/cc3135/hello/Debug/hello.exe, (error 2).
Failed to execute MI command:
-exec-run
Error message from debugger back end:
Error creating process /cygdrive/c/Windows/system32/C:/Projects/cc3135/hello/C:/Projects/cc3135/hello/Debug/hello.exe, (error 2).
Error creating process /cygdrive/c/Windows/system32/C:/Projects/cc3135/hello/C:/Projects/cc3135/hello/Debug/hello.exe, (error 2).
</code>```

Any suggestions?

P.S. The hello executable runs fine in cmd.exe and under gdb.

Body:
I just installed EclipseCDT 2022-12, created the HelloWorld example app, compiled, but when I debug I get an error.  I have both current MSYS2 (MinGW64) and Cygwin64 installed, neither environment works and fails with the same error:

Error in final launch sequence:

Failed to execute MI command:
-exec-run
Error message from debugger back end:
Error creating process /cygdrive/c/Windows/system32/C:/Projects/cc3135/hello/C:/Projects/cc3135/hello/Debug/hello.exe, (error 2).
Failed to execute MI command:
-exec-run
Error message from debugger back end:
Error creating process /cygdrive/c/Windows/system32/C:/Projects/cc3135/hello/C:/Projects/cc3135/hello/Debug/hello.exe, (error 2).
Error creating process /cygdrive/c/Windows/system32/C:/Projects/cc3135/hello/C:/Projects/cc3135/hello/Debug/hello.exe, (error 2).

Any suggestions?

P.S. The hello executable runs fine in cmd.exe and under gdb.


问:
Matplot plt.show() runs in infinite loop
When I call plt.show() at the end of my script to display the plot I have drawn using matplotlib, the script stays at plt.show() even when the window is closed.

I tried using break=False, but then the window immediately closes. I want the script to continue (or stop) after the window closes.

```<code>fig = plt.figure(figsize=plt.figaspect(0.5))
mappable_zmax = plt.cm.ScalarMappable(cmap=plt.cm.viridis)
mappable_zmax.set_array(Znew_max)
mappable_zmin = plt.cm.ScalarMappable(cmap=plt.cm.viridis)
mappable_zmin.set_array(Znew_min)

# =============
# First subplot
# =============
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(Xnew, Ynew, Znew_max, rstride=1, cstride=1, cmap=cm.viridis,
            linewidth=0, antialiased=True)
plt.xlabel('Frequency(Hz)')
plt.ylabel('Duty(%)')
plt.ticklabel_format(style='sci', axis='x', scilimits=(3,3))
plt.title()

# ==============
# Second subplot
# ==============
fig2 = fig.add_subplot(122)
plt.pcolor(Xnew, Ynew, Znew_max, shading='auto')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Duty(%)')
plt.colorbar(mappable_zmax)
plt.show()
</code>```

Body:
When I call plt.show() at the end of my script to display the plot I have drawn using matplotlib, the script stays at plt.show() even when the window is closed.

I tried using break=False, but then the window immediately closes. I want the script to continue (or stop) after the window closes.

fig = plt.figure(figsize=plt.figaspect(0.5))
mappable_zmax = plt.cm.ScalarMappable(cmap=plt.cm.viridis)
mappable_zmax.set_array(Znew_max)
mappable_zmin = plt.cm.ScalarMappable(cmap=plt.cm.viridis)
mappable_zmin.set_array(Znew_min)

# =============
# First subplot
# =============
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(Xnew, Ynew, Znew_max, rstride=1, cstride=1, cmap=cm.viridis,
            linewidth=0, antialiased=True)
plt.xlabel('Frequency(Hz)')
plt.ylabel('Duty(%)')
plt.ticklabel_format(style='sci', axis='x', scilimits=(3,3))
plt.title()

# ==============
# Second subplot
# ==============
fig2 = fig.add_subplot(122)
plt.pcolor(Xnew, Ynew, Znew_max, shading='auto')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Duty(%)')
plt.colorbar(mappable_zmax)
plt.show()


问:
Dropdown does not load data from the database into the modal window
I am using Chosen(Jquery) and in a Dropdown I am loading the data from the Database(SQL) the Dropdown is in a modal window, but when I open the modal window in full screen it does not load the data in the Dropdown but if I make the screen small(change the resolution) it shows the result in the Dropdown but it does not show the list of options and it also loses the styles of the library,
maybe the library code is in conflict with Bootstrap?

enter image description here
enter image description here

HTML

```<code> <div class="row">

            <div class="col-md-6 col-sm-3 col-lg-5 form-group">
              <label class="col-form-label col-md-4 col-sm-2 label-align mr-n1" for="codix">De <i class="fa fa-user"></i></label>
              <datalist id="nombresb">
                @@BENEF@@
              </datalist>
              <input type="text" id="buscab2"  class="form-control" placeholder="" list="nombresb">
            </div>

            <div class="col-md-6 col-sm-6 col-lg-5 form-group">
              <label class="col-form-label col-md-4 col-sm-2 label-align" for="descx">Para <i class="fa fa-users"></i></label>
              <select name="acompanantes" id="acompanantes2" multiple class="locales" data-placeholder="Para">
                <option value=""></option>
                {{empleado}}
              </select>

            </div>
        </div>

</code>```

PHP

```<code>function buscaMemoPorID(){

  $soloID = $_POST["idMemo"];

  $query = " SELECT TB_Memo.ID_Memo, TB_Memo.Fecha_Creacion, a.Nombres +' '+ a.Apellidos as Destinatarios, b.Nombres + ' ' + b.Apellidos as Remitente, TB_Memo.Asunto, TB_Memo.Contenido, TB_Memo.ID_TipoMemo, TB_Memo.ID_EstadoMemo, TB_Memo.Fecha_Envio, c.Descripcion, TB_Memo.ID_Memorandum, TB_Destinatario.ID_Empleado as Para
  from TB_Memo
  inner join TB_Destinatario on TB_Memo.ID_Memo = TB_Destinatario.ID_Memo
  inner join TB_Remitente on TB_Memo.ID_Memo = TB_Remitente.ID_Memo
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] a on TB_Destinatario.ID_Empleado = a.ID_Empleado
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] b on TB_Remitente.ID_Empleado = b.ID_Empleado
  left outer join [IHTT_MEMORANDUM].[dbo].[TB_EstadoDestinatario] c on TB_Memo.ID_EstadoDestinatario = c.ID_EstadoDestinatario
  Where TB_Memo.ID_Memo = $soloID";

  $p = array();
  $data = $this->select($query, $p );

  $datos[1]=count($data);
  $datos[0]=array();
  for($i=0; $i<count($data); $i++){
    $datos[0][$i] = array("ult" =>1, "num" =>$data[$i]["ID_Memo"], "nome"=>$data[$i]["ID_Memorandum"],"tipoMe" =>$data[$i]["ID_TipoMemo"], "estaMe" =>$data[$i]["ID_EstadoMemo"], "asunto" =>$data[$i]["Asunto"], "contenido" =>$data[$i]["Contenido"], "fechEn" =>$data[$i]["Fecha_Envio"], "fechCre" =>$data[$i]["Fecha_Creacion"], "De" =>$data[$i]["Remitente"], "Para" =>$data[$i]["Para"], "estado"=>$data[$i]["Descripcion"], "Destinatarios"=>$data[$i]["Destinatarios"]);
  }

  echo json_encode($datos);

}
</code>```

PHP

```<code>function empleado()
{
  $q = "SELECT [ID_Empleado]
  ,[Nombres]
  ,[Apellidos]
FROM [IHTT_RRHH].[dbo].[TB_Empleados]
WHERE ID_Estado = 1";
  $datos = $this->select($q, array());
  $opcion = "";
  for ($i = 0; $i < count($datos); $i++) {
    $opcion .= "<option  value='" .$datos[$i]["ID_Empleado"]. "'>" . utf8_encode($datos[$i]["Nombres"]) . " " . utf8_encode($datos[$i]["Apellidos"]) ."</option>
         ";

  }
  return $opcion;
}
</code>```

JS

```<code>function cargaMemoEspecifico(idmemo){
  var cant = $("#mostrar").val();
  var form_data = new FormData();
  form_data.append("action","buscaMemoPorID");
  form_data.append("idMemo",idmemo);
  $.ajax({
      url: 'api_con.php',
      dataType: 'json',
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'post',
      success: function(data){
          var area = data[0];

          if(data[1]>0  ){

              var detalle='';
              var cantidad=80;
              var total=0;
              var num=1;

              $("#acompanantes2").html("");
              for(i=0; i<area.length; i++){

                let datos = tinymce.get("mensaje2").setContent(area[i].contenido);

               $("#modalconsulta2").modal("show");
                $("#buscab2").val(area[i].De);
                $("#acompanantes2").append("<option value='" + area[i].Para + "'>" + area[i].Destinatarios + "</option>");

                $("#modal-asunto").val(area[i].asunto);
                $("#modal-fecha").val(area[i].fechCre);
                $("#mensaje2").val(area[i].contenido);
                $("#idMemo").val(area[i].num);

   }

   $("#acompanantes2").trigger("chosen:updated");

          } else {
              detalle +='<tr><td colspan="8">NO HAY DATOS EN ESTE MOMENTO.........</td></tr>';
          }

      }
   }).error(function(r){
      console.log("Error-->",r.responseText);
   });
}

</code>```

Body:
I am using Chosen(Jquery) and in a Dropdown I am loading the data from the Database(SQL) the Dropdown is in a modal window, but when I open the modal window in full screen it does not load the data in the Dropdown but if I make the screen small(change the resolution) it shows the result in the Dropdown but it does not show the list of options and it also loses the styles of the library,
maybe the library code is in conflict with Bootstrap?

enter image description here
enter image description here

HTML

              De
              <datalist id="nombresb">
                @@BENEF@@
              </datalist>
              <input type="text" id="buscab2"  class="form-control" placeholder="" list="nombresb">

              Para
              <select name="acompanantes" id="acompanantes2" multiple class="locales" data-placeholder="Para">
                <option value=""></option>
                {{empleado}}
              </select>

PHP

function buscaMemoPorID(){

  $soloID = $_POST["idMemo"];

  $query = " SELECT TB_Memo.ID_Memo, TB_Memo.Fecha_Creacion, a.Nombres +' '+ a.Apellidos as Destinatarios, b.Nombres + ' ' + b.Apellidos as Remitente, TB_Memo.Asunto, TB_Memo.Contenido, TB_Memo.ID_TipoMemo, TB_Memo.ID_EstadoMemo, TB_Memo.Fecha_Envio, c.Descripcion, TB_Memo.ID_Memorandum, TB_Destinatario.ID_Empleado as Para
  from TB_Memo
  inner join TB_Destinatario on TB_Memo.ID_Memo = TB_Destinatario.ID_Memo
  inner join TB_Remitente on TB_Memo.ID_Memo = TB_Remitente.ID_Memo
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] a on TB_Destinatario.ID_Empleado = a.ID_Empleado
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] b on TB_Remitente.ID_Empleado = b.ID_Empleado
  left outer join [IHTT_MEMORANDUM].[dbo].[TB_EstadoDestinatario] c on TB_Memo.ID_EstadoDestinatario = c.ID_EstadoDestinatario
  Where TB_Memo.ID_Memo = $soloID";

  $p = array();
  $data = $this->select($query, $p );

  $datos[1]=count($data);
  $datos[0]=array();
  for($i=0; $i<count($data); $i++){
    $datos[0][$i] = array("ult" =>1, "num" =>$data[$i]["ID_Memo"], "nome"=>$data[$i]["ID_Memorandum"],"tipoMe" =>$data[$i]["ID_TipoMemo"], "estaMe" =>$data[$i]["ID_EstadoMemo"], "asunto" =>$data[$i]["Asunto"], "contenido" =>$data[$i]["Contenido"], "fechEn" =>$data[$i]["Fecha_Envio"], "fechCre" =>$data[$i]["Fecha_Creacion"], "De" =>$data[$i]["Remitente"], "Para" =>$data[$i]["Para"], "estado"=>$data[$i]["Descripcion"], "Destinatarios"=>$data[$i]["Destinatarios"]);
  }

  echo json_encode($datos);

}

PHP

function empleado()
{
  $q = "SELECT [ID_Empleado]
  ,[Nombres]
  ,[Apellidos]
FROM [IHTT_RRHH].[dbo].[TB_Empleados]
WHERE ID_Estado = 1";
  $datos = $this->select($q, array());
  $opcion = "";
  for ($i = 0; $i < count($datos); $i++) {
    $opcion .= "<option  value='" .$datos[$i]["ID_Empleado"]. "'>" . utf8_encode($datos[$i]["Nombres"]) . " " . utf8_encode($datos[$i]["Apellidos"]) ."</option>
         ";

  }
  return $opcion;
}

JS

function cargaMemoEspecifico(idmemo){
  var cant = $("#mostrar").val();
  var form_data = new FormData();
  form_data.append("action","buscaMemoPorID");
  form_data.append("idMemo",idmemo);
  $.ajax({
      url: 'api_con.php',
      dataType: 'json',
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'post',
      success: function(data){
          var area = data[0];

          if(data[1]>0  ){

              var detalle='';
              var cantidad=80;
              var total=0;
              var num=1;

              $("#acompanantes2").html("");
              for(i=0; i<area.length; i++){

                let datos = tinymce.get("mensaje2").setContent(area[i].contenido);

               $("#modalconsulta2").modal("show");
                $("#buscab2").val(area[i].De);
                $("#acompanantes2").append("<option value='" + area[i].Para + "'>" + area[i].Destinatarios + "</option>");

                $("#modal-asunto").val(area[i].asunto);
                $("#modal-fecha").val(area[i].fechCre);
                $("#mensaje2").val(area[i].contenido);
                $("#idMemo").val(area[i].num);

   }

   $("#acompanantes2").trigger("chosen:updated");

          } else {
              detalle +='
NO HAY DATOS EN ESTE MOMENTO.........
';
          }

      }
   }).error(function(r){
      console.log("Error-->",r.responseText);
   });
}


问:
How to run a gradle task mulitple times with different parameters
I have multiple sub-directories against which I would like to run the same set of tests.
I am thinking that one task could fetch the sub-directories to run the tests against.
The second task would use the output of the first task and run the tests against all these versions.</p>


问:
Can't find RemoteSpringApplication on Intellij for live reload on Docker
I'm currently trying to run a Docker SpringBoot Project with live reload using SpringBoot Devtools and following this documentation

I made the changes in my POM.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.1</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>br.com.myproject.teste</groupId>
   <artifactId>hello</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>hello</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>11</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>build</scope>
         <optional>false</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
      </dependency>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludeDevtools>false</excludeDevtools>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>

</code>```

And added the secret configuration on my application.properties

```<code>spring.devtools.remote.secret=${SPRING_REMOTE_SECRET:secret}

</code>```

When I try to create de Intellij configurarion to use the RemoteSpringApplication as main class
it cannot find the class, in fact it does not find the org.springframework.boot.devtools whole package.

The application is running in Docker container created from this Dockerfile

```<code>FROM openjdk:11
WORKDIR /app
COPY target/hello-0.0.1-SNAPSHOT.jar /app/hello-ms-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar", "/app/hello-0.0.1-SNAPSHOT.jar"]
</code>```

And except for the live reload functionality, it is working. Am I missing something?

Edit 1: There was a problem with the scope of the devtools plugin. (thanks @xerx593)

Edit 2: THe live reload and devtools seems to be working fine and if I run the application locally with mvn spring-boot:run, it reloads when changes are made in the project. The problem is running the project via SpringRemoteApplication that IntelliJ can't find so I can configure it as main class

Body:
I'm currently trying to run a Docker SpringBoot Project with live reload using SpringBoot Devtools and following this documentation

I made the changes in my POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.1</version>
      <relativePath/>
   </parent>
   <groupId>br.com.myproject.teste</groupId>
   <artifactId>hello</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>hello</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>11</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>build</scope>
         <optional>false</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
      </dependency>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludeDevtools>false</excludeDevtools>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>

And added the secret configuration on my application.properties

spring.devtools.remote.secret=${SPRING_REMOTE_SECRET:secret}

When I try to create de Intellij configurarion to use the RemoteSpringApplication as main class
it cannot find the class, in fact it does not find the org.springframework.boot.devtools whole package.

The application is running in Docker container created from this Dockerfile

FROM openjdk:11
WORKDIR /app
COPY target/hello-0.0.1-SNAPSHOT.jar /app/hello-ms-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar", "/app/hello-0.0.1-SNAPSHOT.jar"]

And except for the live reload functionality, it is working. Am I missing something?

Edit 1: There was a problem with the scope of the devtools plugin. (thanks @xerx593)

Edit 2: THe live reload and devtools seems to be working fine and if I run the application locally with mvn spring-boot:run, it reloads when changes are made in the project. The problem is running the project via SpringRemoteApplication that IntelliJ can't find so I can configure it as main class


问:
AWS CODEBUILD ERROR: pip's dependency resolver does not currently take into account all the packages
I'm trying to run a Glue Job, but it's not working. The error message says:

```<code>ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
aws-sam-cli 1.58.0 requires typing-extensions==3.10.0.0, but you have typing-extensions 4.4.0 which is incompatible.
</code>```

But even with this ERROR, the job continues to run, until:

```<code>Traceback (most recent call last):

  File "/root/.pyenv/versions/3.7.13/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/codebuild/output/src560/src/s3/00/glue/main.py", line 4, in <module>
    from glue.steps.deploy.deploy import Deploy
  File "/codebuild/output/src560/src/s3/00/glue/steps/deploy/deploy.py", line 10, in <module>
    from glue.steps.deploy.aws_client import AWSClient
  File "/codebuild/output/src560/src/s3/00/glue/steps/deploy/aws_client.py", line 6, in <module>
    from mypy_boto3_cloudformation import Client as CloudformationClient
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/__init__.py", line 67, in <module>
    from .client import CloudFormationClient
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/client.py", line 42, in <module>
    from .paginator import (
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/paginator.py", line 61, in <module>
    from .type_defs import (
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/type_defs.py", line 18, in <module>
    from literals import TemplateStageType
ModuleNotFoundError: No module named 'literals'

[Container] 2022/12/22 16:18:03 Command did not exit successfully python -m glue.main --app_path $CODEBUILD_SRC_DIR_App --environment "prd" --account $ProdAccount --version $CODEBUILD_RESOLVED_SOURCE_VERSION --feature-name $FeatureName --microservice-name $MicroServiceName --deploy; exit status 1
[Container] 2022/12/22 16:18:03 Phase complete: BUILD State: FAILED
[Container] 2022/12/22 16:18:03 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: python -m glue.main --app_path $CODEBUILD_SRC_DIR_App --environment "prd" --account $ProdAccount --version $CODEBUILD_RESOLVED_SOURCE_VERSION --feature-name $FeatureName --microservice-name $MicroServiceName --deploy;. Reason: exit status 1
[Container] 2022/12/22 16:18:03 Entering phase POST_BUILD
[Container] 2022/12/22 16:18:03 Phase complete: POST_BUILD State: SUCCEEDED
[Container] 2022/12/22 16:18:03 Phase context status code:  Message:
</code>```

I have tried using "from mypy_boto3_cloudformation.literals import TemplateStageType" to solve the problem, but it didnt work. Could you guys help me?

Body:
I'm trying to run a Glue Job, but it's not working. The error message says:

ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
aws-sam-cli 1.58.0 requires typing-extensions==3.10.0.0, but you have typing-extensions 4.4.0 which is incompatible.

But even with this ERROR, the job continues to run, until:

Traceback (most recent call last):

  File "/root/.pyenv/versions/3.7.13/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/codebuild/output/src560/src/s3/00/glue/main.py", line 4, in <module>
    from glue.steps.deploy.deploy import Deploy
  File "/codebuild/output/src560/src/s3/00/glue/steps/deploy/deploy.py", line 10, in <module>
    from glue.steps.deploy.aws_client import AWSClient
  File "/codebuild/output/src560/src/s3/00/glue/steps/deploy/aws_client.py", line 6, in <module>
    from mypy_boto3_cloudformation import Client as CloudformationClient
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/__init__.py", line 67, in <module>
    from .client import CloudFormationClient
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/client.py", line 42, in <module>
    from .paginator import (
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/paginator.py", line 61, in <module>
    from .type_defs import (
  File "/root/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mypy_boto3_cloudformation/type_defs.py", line 18, in <module>
    from literals import TemplateStageType
ModuleNotFoundError: No module named 'literals'

[Container] 2022/12/22 16:18:03 Command did not exit successfully python -m glue.main --app_path $CODEBUILD_SRC_DIR_App --environment "prd" --account $ProdAccount --version $CODEBUILD_RESOLVED_SOURCE_VERSION --feature-name $FeatureName --microservice-name $MicroServiceName --deploy; exit status 1
[Container] 2022/12/22 16:18:03 Phase complete: BUILD State: FAILED
[Container] 2022/12/22 16:18:03 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: python -m glue.main --app_path $CODEBUILD_SRC_DIR_App --environment "prd" --account $ProdAccount --version $CODEBUILD_RESOLVED_SOURCE_VERSION --feature-name $FeatureName --microservice-name $MicroServiceName --deploy;. Reason: exit status 1
[Container] 2022/12/22 16:18:03 Entering phase POST_BUILD
[Container] 2022/12/22 16:18:03 Phase complete: POST_BUILD State: SUCCEEDED
[Container] 2022/12/22 16:18:03 Phase context status code:  Message:

I have tried using "from mypy_boto3_cloudformation.literals import TemplateStageType" to solve the problem, but it didnt work. Could you guys help me?


问:
OnDeviceChange fires every time it's registered on browser start in Chrome and Edge
In Google Chrome 108.0.5359.125 (Official Build) (64-bit) and in MS Edge 108.0.1462.54 (Official build) (64-bit) I'm observing following behavior:

Every time I start the browser (not refresh, no other windows open) and my app registers ondevicechange event then it's fired immediately. I don't observe this behavior neither in latest firefox nor in opera. Opening the same code in the new tab doesn't cause this behavior.

Is this behavior by design or is it a bug?
If it's not a bug, is there a way to detect and discard this first call? I don't think writing the logic which detects the browser and skips the first call maintaining the state is a good option. The event object doesn't seem to contain any useful properties to distinguish that.

```<code>navigator.mediaDevices.ondevicechange = (event) => {
    alert('ON_DEVICE_CHANGE');
};
</code>```

Code to reproduce https://jsfiddle.net/p53utyme/

This behavior was reported by my Frontend developer on his windows 11. It is reproducable every time on my windows 10 computer. Please make sure you have no other instances of chrome or edge running so to reproduce it you need to
a) close all instances of chrome / edge before trying
b) open new instance of chrome / edge with no other tabs
c) open jsfiddle and you should see the alert immediately

It's also reproducable in Chrome on Mac.

Body:
In Google Chrome 108.0.5359.125 (Official Build) (64-bit) and in MS Edge 108.0.1462.54 (Official build) (64-bit) I'm observing following behavior:

Every time I start the browser (not refresh, no other windows open) and my app registers ondevicechange event then it's fired immediately. I don't observe this behavior neither in latest firefox nor in opera. Opening the same code in the new tab doesn't cause this behavior.

Is this behavior by design or is it a bug?
If it's not a bug, is there a way to detect and discard this first call? I don't think writing the logic which detects the browser and skips the first call maintaining the state is a good option. The event object doesn't seem to contain any useful properties to distinguish that.

navigator.mediaDevices.ondevicechange = (event) => {
    alert('ON_DEVICE_CHANGE');
};

Code to reproduce https://jsfiddle.net/p53utyme/

This behavior was reported by my Frontend developer on his windows 11. It is reproducable every time on my windows 10 computer. Please make sure you have no other instances of chrome or edge running so to reproduce it you need to
a) close all instances of chrome / edge before trying
b) open new instance of chrome / edge with no other tabs
c) open jsfiddle and you should see the alert immediately

It's also reproducable in Chrome on Mac.


问:
Trouble publishing .NET MAUI application to Microsoft App store
Help! Hello everybody, I am attempting to publish my .NET MAUI app to the Microsoft app store in preparation for an interview I have coming up in a few weeks.

I am having an issue where:

the exe installed by the msix file fails to run unless stored in a directory containing all of its associated dll files and other dependencies such as images.

I cannot pack this into an msix upload for the Microsoft store because the Microsoft store won't permit me to upload any msixupload file that contains more than 16 files. I'm quite sure there are several hundred files at the moment, but without all of them, my.exe program won't run.

Any solutions for packaging the .dlls and exe into one file for publication to the Microsoft app store, or workarounds to produce a publishable .msix/msixupload file?

Sidenote, when I try to publish directly to the Microsoft store using Visual Studio, I get the error shown at the bottom of this post.

Alternatively I am currently publishing this using sideloading. The .exe DOES successfully run upon being installed by the msix, but again, only when all associated dependency files are present.

Tried many different things. Packaging applications, YouTube, publishing directly with Visual Studio. Cannot figure out a solution. Or how to use some of this packaging software.

View Publishing Details:

Package is being submitted to the Microsoft Store. Getting application information...

Error submitting to Microsoft Store. Please check your submission in Windows Dev Center.

Microsoft.VisualStudio.ContinuousPublishing.HttpRequestFailedException:{"code":"Unauthorized","message":"A valid account could not be found with given authorization token. Correlationid=da339ee3-b0da-42a8-9c92-5ca249c84c79"}

at Microsoft.VisualStudio.ContinuousPublishing.IngestionClient.d_14'1.MoveNext()....


问:
What's the most efficient way to filter/query a list of data?
I have a list of objects, each of which has common integer fields like type and timestamp. That list is sorted by timestamps. I want to create a way to filter/query specific objects from that list depending on their fields. For example: select objects with timestamp >= 100, timestamp <= 300 and type == 3.

The way I do that right now is that I loop through each element of the list and then loop through the conditions. If the object passes all of them I add it to a new list and then return it. This approach works but it's really inefficient on large lists.

I think I can improve my algorithm by replacing linear search with binary search for timestamps so I can start/stop iterating through the list right from the place a condition starts/ends. But what can I do to improve the search by other non sorted fields? Should I store multiple copies of the list sorted by different fields to be able to apply binary search for every field?

I want to understand the general approach of how these things are done and how one can optimise them. (Note: I didn't provide any concrete code because I'm not interested in the language specific implementations as much as I'm interested in the general idea of how this should be done)


问:
method to install uvloop for windows for Rasa
Is there a Windows supported version of uvloop that I could install? I need it for Rasa installation.

I have tried installing the uvloop through the tar as well. I am trying to use the tar file but that doesn't seem to work either. I want to download uvloop==0.14.0.


问:
How to resize and overlay, in C#, 2 images using some points as reference
I have 2 Bitmap (bmpA and bmpB) and in each I drawn a Line between 2 Points.
These lines have different length.

First:
I want to scale bmpB so that the line drawn in it have to be the same of the length drawn in the bmpA.

Second:
I want to overlay the two Bitmap and I want that exactly the points on the line in the bmpA overlap exactly the line in the bmpB.

I hope it's clear this explanation.


问:
jest doesn’t work with istanbul’s “html-spa” reporter
Jest (29.3.1) is supposed to work with all istanbul reporters:
https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib

But when I set the reporter to html-spa I get the error:

```<code>Error: Could not resolve a module for a custom reporter.
  Module name: html-spa
</code>```

What am I missing?

SOLVED: Just a stilly mistake - I was using the reporter config key, instead of coverageReporter

Body:
Jest (29.3.1) is supposed to work with all istanbul reporters:
https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib

But when I set the reporter to html-spa I get the error:

Error: Could not resolve a module for a custom reporter.
  Module name: html-spa

What am I missing?

SOLVED: Just a stilly mistake - I was using the reporter config key, instead of coverageReporter


问:
Node/Express app works on server but via proxy, express created 404 error
I have a one file node/express app with 2 post routes being handled. On the server the app and its routes work when accessed via the ip address. However when nginx proxy is pointed to it, by our proxy guy, then we are getting 404 errors which are created by express.

So this leads me to believe that the app is being reached but none of routes are matching with the request I am making, although they do match when accessing via ip address.

Would anybody know what is happening there, and how to correct it?

I would be very grateful for any clues.


问:
Spring MVC Binding Request Parameters to Interface (vs Abstract Class)
I'd like Spring (Spring Boot 2.7.2) to bind request parameters to a model attribute referenced as an interface.  But binding to the interface does not work (automatically). However, using an abstract class does.  Why?

We have this interface:

```<code>public interface FormSpec<T extends Form> extends Specification<T> {
  boolean isFiltered();
  String getLastName();
  void setLastName(String lastName);
  ...
}
</code>```

Here's how the controller prepares a specific (Spring Data JPA) Specification implementing this interface:

```<code>@ModelAttribute
public <T extends Form> FormSpec<T> prepareFormSpec(@ModelAttribute FormType formType) {
  return (FormSpec<T>) formType.getSpecClass().map(ReflectionUtils::newInstance).orElseThrow();
}
</code>```

But none of the request parameters are bound to the spec as expected.  Here's how it's later used in the same controller:

```<code>@GetMapping("/*Form/search")
public <T extends Form> String getFormReport(@ModelAttribute FormType formType, @ModelAttribute FormSpec<T> spec, Model m) {
  JpaSpecificationExecutor<T> specExe = getSpecExecutor(formType);
  Page<T> page = specExe.findAll(spec);
  m.addAttribute("page", page);
  m.addAttribute("spec", spec);
  return FormViewType.SEARCH.forward(formType);
}
</code>```

There is no filtering applied to the returned page of results because the binding failed on the spec.  This can work if we "manually" perform the bind by including this @ModelAttribute method:

```<code>@ModelAttribute
public <T extends Form> void bindParameters(@ModelAttribute FormSpec<T> spec, HttpServletRequest req) {
  new WebDataBinder(spec).bind(new ServletRequestParameterPropertyValues(req));
}
</code>```

But this is smelly.

What I've found also works is if instead of using a FormSpec interface as our model attribute, we use an AbstractFormSpec, binding works!

```<code>public abstract class AbstractFormSpec<T extends Form> implements FormSpec<T> {
  protected String lastName;
  ...
}
</code>```

Working example:

```<code>@ModelAttribute
public <T extends Form> AbstractFormSpec<T> prepareFormSpec(@ModelAttribute FormType formType) {
  return (AbstractFormSpec<T>) formType.getSpecClass().map(ReflectionUtils::newInstance).orElseThrow();
}

@GetMapping("/*Form/search")
public <T extends Form> String getFormReport(@ModelAttribute FormType formType, @ModelAttribute AbstractFormSpec<T> spec, Model m) {
  JpaSpecificationExecutor<T> specExe = getSpecExecutor(formType);
  Page<T> page = specExe.findAll(spec);
  m.addAttribute("page", page);
  m.addAttribute("spec", spec);
  return FormViewType.SEARCH.forward(formType);
}
</code>```

Is there some documented limitation in Spring MVC where binding to an interface is disallowed (or for technical reasons does not work), whereas an abstract class is fine?

Body:
I'd like Spring (Spring Boot 2.7.2) to bind request parameters to a model attribute referenced as an interface.  But binding to the interface does not work (automatically). However, using an abstract class does.  Why?

We have this interface:

public interface FormSpec<T extends Form> extends Specification<T> {
  boolean isFiltered();
  String getLastName();
  void setLastName(String lastName);
  ...
}

Here's how the controller prepares a specific (Spring Data JPA) Specification implementing this interface:

@ModelAttribute
public <T extends Form> FormSpec<T> prepareFormSpec(@ModelAttribute FormType formType) {
  return (FormSpec<T>) formType.getSpecClass().map(ReflectionUtils::newInstance).orElseThrow();
}

But none of the request parameters are bound to the spec as expected.  Here's how it's later used in the same controller:

@GetMapping("/*Form/search")
public <T extends Form> String getFormReport(@ModelAttribute FormType formType, @ModelAttribute FormSpec<T> spec, Model m) {
  JpaSpecificationExecutor<T> specExe = getSpecExecutor(formType);
  Page<T> page = specExe.findAll(spec);
  m.addAttribute("page", page);
  m.addAttribute("spec", spec);
  return FormViewType.SEARCH.forward(formType);
}

There is no filtering applied to the returned page of results because the binding failed on the spec.  This can work if we "manually" perform the bind by including this @ModelAttribute method:

@ModelAttribute
public <T extends Form> void bindParameters(@ModelAttribute FormSpec<T> spec, HttpServletRequest req) {
  new WebDataBinder(spec).bind(new ServletRequestParameterPropertyValues(req));
}

But this is smelly.

What I've found also works is if instead of using a FormSpec interface as our model attribute, we use an AbstractFormSpec, binding works!

public abstract class AbstractFormSpec<T extends Form> implements FormSpec<T> {
  protected String lastName;
  ...
}

Working example:

@ModelAttribute
public <T extends Form> AbstractFormSpec<T> prepareFormSpec(@ModelAttribute FormType formType) {
  return (AbstractFormSpec<T>) formType.getSpecClass().map(ReflectionUtils::newInstance).orElseThrow();
}

@GetMapping("/*Form/search")
public <T extends Form> String getFormReport(@ModelAttribute FormType formType, @ModelAttribute AbstractFormSpec<T> spec, Model m) {
  JpaSpecificationExecutor<T> specExe = getSpecExecutor(formType);
  Page<T> page = specExe.findAll(spec);
  m.addAttribute("page", page);
  m.addAttribute("spec", spec);
  return FormViewType.SEARCH.forward(formType);
}

Is there some documented limitation in Spring MVC where binding to an interface is disallowed (or for technical reasons does not work), whereas an abstract class is fine?


问:
How to configure STUNNEL client to see the web page?
I am using stunnel in Windows so that I change HOST file and stunnel.conf configuration file and usually it works. But I would like to open in a browser the web     https://clienttest.ssllabs.com:8443/ssltest/viewMyClient.html

No success so far. Is it possible? How the configuration should look like?

For instance, wikipedia web pages works with this configuration:

```<code>[en.wikipedia.org]
client = yes
accept = 127.0.2.1:80
connect = 91.198.174.192:443

[commons.wikimedia.org]
client = yes
accept = 127.0.2.3:80
connect = 91.198.174.192:443

[upload.wikimedia.org]
client = yes
accept = 127.0.2.4:80
connect = 91.198.174.208:443
</code>```

But this approach does not work with the ssllabs.com . Does anybody know how the configuration should look like?

Body:
I am using stunnel in Windows so that I change HOST file and stunnel.conf configuration file and usually it works. But I would like to open in a browser the web     https://clienttest.ssllabs.com:8443/ssltest/viewMyClient.html

No success so far. Is it possible? How the configuration should look like?

For instance, wikipedia web pages works with this configuration:

[en.wikipedia.org]
client = yes
accept = 127.0.2.1:80
connect = 91.198.174.192:443

[commons.wikimedia.org]
client = yes
accept = 127.0.2.3:80
connect = 91.198.174.192:443

[upload.wikimedia.org]
client = yes
accept = 127.0.2.4:80
connect = 91.198.174.208:443

But this approach does not work with the ssllabs.com . Does anybody know how the configuration should look like?


问:
How do I customise a keras model's `fit` to modify the training data?
I'm trying to do this because I want to use the previous prediction as an input feature for the next training sample.

At the beginning of each epoch the last 9 columns of the feature vector is initialised with zeroes (which I haven't implemented the reset yet), which will be used to represent the one hot encoding of one of my 9 possible output labels. Here's the code I currently have

class CustomSequentialModel(keras.models.Sequential):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # previous prediction represented as the index of 1 in the one hot encoding
        self.previous_y_pred = np.where(one_hot_label_encoder.categories_[0]=='O')[0][0]
        self.num_labels = len(one_hot_label_encoder.categories_[0])
        # self.previous_y_pred = one_hot_label_encoder.transform(np.array(['O']).reshape(-1, 1))
        self.current_sample_num = 0

    def train_step(self, data):
        """
        Function called for every batch of data, need to set batch_size=1 when fitting
        in order to get last prediction
        Override training step code with modifications from \cite{customizing fit}
        """
        # what is x? the entire dataset?
        x, y = data
        # print(y)
        # with tf.compat.v1.Session() as sess:
        #     rows = sess.run(y)
        #     print(rows)
        tag_index = [self.current_sample_num, x.shape[1]-(self.num_labels-1)+self.previous_y_pred]
        st_to_add = tf.sparse.SparseTensor(indices=[tag_index],
                        values=[1.0],
                        dense_shape=[219554, x.shape[1]])
        x = tf.sparse.add(x, st_to_add)

        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)  # Forward pass
            # Compute the loss value
            # (the loss function is configured in `compile()`)
            loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)

            # self.previous_y_pred = y_pred.index(1)
            self.previous_y_pred = tf.where(y_pred)[0]
            self.current_sample_num = (self.current_sample_num + 1) % x.shape[0]

        # Compute gradients
        trainable_vars = self.trainable_variables
        gradients = tape.gradient(loss, trainable_vars)
        # Update weights
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))
        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, y_pred)
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}
```

Which gives an error on line st_to_add =  with ValueError: Shapes must be equal rank, but are 0 and 1, I am not sure about the structure of the data inside x, whether it represents the entire dataset of just a single sample, it's shape just returns <None, (num_features)>, but it is of type tensorflow.python.framework.sparse_tensor.SparseTensor.

Body:
I'm trying to do this because I want to use the previous prediction as an input feature for the next training sample.

At the beginning of each epoch the last 9 columns of the feature vector is initialised with zeroes (which I haven't implemented the reset yet), which will be used to represent the one hot encoding of one of my 9 possible output labels. Here's the code I currently have

class CustomSequentialModel(keras.models.Sequential):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # previous prediction represented as the index of 1 in the one hot encoding
        self.previous_y_pred = np.where(one_hot_label_encoder.categories_[0]=='O')[0][0]
        self.num_labels = len(one_hot_label_encoder.categories_[0])
        # self.previous_y_pred = one_hot_label_encoder.transform(np.array(['O']).reshape(-1, 1))
        self.current_sample_num = 0

    def train_step(self, data):
        """
        Function called for every batch of data, need to set batch_size=1 when fitting
        in order to get last prediction
        Override training step code with modifications from \cite{customizing fit}
        """
        # what is x? the entire dataset?
        x, y = data
        # print(y)
        # with tf.compat.v1.Session() as sess:
        #     rows = sess.run(y)
        #     print(rows)
        tag_index = [self.current_sample_num, x.shape[1]-(self.num_labels-1)+self.previous_y_pred]
        st_to_add = tf.sparse.SparseTensor(indices=[tag_index],
                        values=[1.0],
                        dense_shape=[219554, x.shape[1]])
        x = tf.sparse.add(x, st_to_add)

        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)  # Forward pass
            # Compute the loss value
            # (the loss function is configured in `compile()`)
            loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)

            # self.previous_y_pred = y_pred.index(1)
            self.previous_y_pred = tf.where(y_pred)[0]
            self.current_sample_num = (self.current_sample_num + 1) % x.shape[0]

        # Compute gradients
        trainable_vars = self.trainable_variables
        gradients = tape.gradient(loss, trainable_vars)
        # Update weights
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))
        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, y_pred)
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}

Which gives an error on line st_to_add =  with ValueError: Shapes must be equal rank, but are 0 and 1, I am not sure about the structure of the data inside x, whether it represents the entire dataset of just a single sample, it's shape just returns <None, (num_features)>, but it is of type tensorflow.python.framework.sparse_tensor.SparseTensor.


问:
how to change the url which is having parameter with htacccess
I am passing and id with the PHP file name and I want to hide the URL.

news-event-listing.php in this page I am passing some id to my next page

```<code><div class="date-wrap">

             <label><?php echo $res['publisheddate'] ?></label>
           <a href="news-inner.php?id=<?php echo $res['id'] ?>" class="read-more-btn">Read More <i class="ms-2 bi bi-arrow-right"></i></a>
                    </div>
</code>```

For the URL like http://localhost/glc_css/news-inner.php?id=6, I want to hide this news-inner.php?id=6   to something else, like:

```<code>localhost/glc_css/news-inner.php?id=6 => localhost/glc_css/service/6
</code>```

What I have tried in my htaccess file

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#RewriteRule ^ABOUT  about.php [NC,L]
#RewriteRule ^CONTACT  contact.php [NC,L]
#RewriteRule ^PRODUCT  product.php [NC,L]
RewriteRule ^service/([^/\.]+)?$ /news-inner.php?id=$1 [L]
</code>```

Body:
I am passing and id with the PHP file name and I want to hide the URL.

news-event-listing.php in this page I am passing some id to my next page

             <?php echo $res['publisheddate'] ?>
           <a href="news-inner.php?id=<?php echo $res['id'] ?>" class="read-more-btn">Read More

For the URL like http://localhost/glc_css/news-inner.php?id=6, I want to hide this news-inner.php?id=6   to something else, like:

localhost/glc_css/news-inner.php?id=6 => localhost/glc_css/service/6

What I have tried in my htaccess file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#RewriteRule ^ABOUT  about.php [NC,L]
#RewriteRule ^CONTACT  contact.php [NC,L]
#RewriteRule ^PRODUCT  product.php [NC,L]
RewriteRule ^service/([^/\.]+)?$ /news-inner.php?id=$1 [L]


问:
Discrepancy in Cloud Watch Agent Metrics from AWS EC2 Instances - CPU and Processes
So I have below set of CW Agent Metrics Collected from an AWS EC2 Instance for CPU.

```<code>time_active, time_guest, time_guest_nice, time_idle, time_iowait, time_irq, time_nice,time_softirq, time_steal, time_system, time_user, usage_active, usage_guest, usage_guest_nice, usage_idle, usage_iowait, usage_irq, usage_nice, usage_softirq, usage_steal, usage_system, and usage_user.
</code>```

Looking at the metrics definition here I am considering usage_active  as CPU Utilization % and usage_idle  as the Idle CPU time %. However, for an instance when I am validating the CPU Utilization % with respect to the AWS/EC2 namespace metrics, I am getting a different value. [ The  CWAgent namespace has usage_active as 100% where as the AWS/EC2 namespace says its 10.35% ]. Am I considering the wrong CPU Metric from CWAgent for CPU Utilization ?

Similarly, the Total Processes metrics (processes_total) is not adding up with Running Processes and Sleeping Processes. Also I am getting the Running Processes as 0.02. 0.03 etc. Why it is a fraction ?

Body:
So I have below set of CW Agent Metrics Collected from an AWS EC2 Instance for CPU.

time_active, time_guest, time_guest_nice, time_idle, time_iowait, time_irq, time_nice,time_softirq, time_steal, time_system, time_user, usage_active, usage_guest, usage_guest_nice, usage_idle, usage_iowait, usage_irq, usage_nice, usage_softirq, usage_steal, usage_system, and usage_user.

Looking at the metrics definition here I am considering usage_active  as CPU Utilization % and usage_idle  as the Idle CPU time %. However, for an instance when I am validating the CPU Utilization % with respect to the AWS/EC2 namespace metrics, I am getting a different value. [ The  CWAgent namespace has usage_active as 100% where as the AWS/EC2 namespace says its 10.35% ]. Am I considering the wrong CPU Metric from CWAgent for CPU Utilization ?

Similarly, the Total Processes metrics (processes_total) is not adding up with Running Processes and Sleeping Processes. Also I am getting the Running Processes as 0.02. 0.03 etc. Why it is a fraction ?