问:
Angular AutoComplete needs pass its object value and displays its object label
```<code><input
                                        #autoInput
                                        type="text"
                                        aria-label="Number"
                                        matInput
                                        [matAutocomplete]="auto"
                                        [formControlName]="field.model"
                                        [id]="field.model"
                                    />
                                    <mat-autocomplete
                                        #auto="matAutocomplete"
                                        (optionSelected)="onUpdate(field)"
                                        [displayWith]="displayFn"
                                    >
                                        <mat-option
                                            *ngFor="
                                                let option of getFiltered(
                                                    options[field.model],
                                                    autoInput
                                                )
                                            "
                                            [value]="option.value || option"
                                        >
                                            {{ option?.label || option }}
                                        </mat-option>
                                    </mat-autocomplete>
</code>```

My requirement was to show the selected label in the Input Box and get the Selected value to the .ts file. but if I selected anything from the option instead of the label its 'value' is displaying on the autocomplete input box. passing by entire object by '[value]="option"' '[displayWith]="displayFn"' I can solve the Displaying issue but on .ts file the entire object is receiving. I dont need that. in .ts file 'option.value' must reach. how can I solve the issue

Body:
<input
                                        #autoInput
                                        type="text"
                                        aria-label="Number"
                                        matInput
                                        [matAutocomplete]="auto"
                                        [formControlName]="field.model"
                                        [id]="field.model"
                                    />
                                    <mat-autocomplete
                                        #auto="matAutocomplete"
                                        (optionSelected)="onUpdate(field)"
                                        [displayWith]="displayFn"
                                    >
                                        <mat-option
                                            *ngFor="
                                                let option of getFiltered(
                                                    options[field.model],
                                                    autoInput
                                                )
                                            "
                                            [value]="option.value || option"
                                        >
                                            {{ option?.label || option }}
                                        </mat-option>
                                    </mat-autocomplete>

My requirement was to show the selected label in the Input Box and get the Selected value to the .ts file. but if I selected anything from the option instead of the label its 'value' is displaying on the autocomplete input box. passing by entire object by '[value]="option"' '[displayWith]="displayFn"' I can solve the Displaying issue but on .ts file the entire object is receiving. I dont need that. in .ts file 'option.value' must reach. how can I solve the issue


来源: stackexchange

问:
extend Mui Typescript breakpoints in typescript
Getting a typescript error when trying to use custom names for breakpoint values:

```<code>Type '{ mobile: number; tablet: number; desktop: number;}' is not assignable to type '{ xs: number; sm: number; md: number; lg: number; xl: number; }'.
  Object literal may only specify known properties, and 'mobile' does not exist in type '{ xs: number; sm: number; md: number; lg: number; xl: number; }'.
</code>```

Here is my ThemProvider

```<code>import { ThemeProvider, createTheme } from "@mui/material/styles";

<ThemeProvider
  theme={createTheme({
    breakpoints: {
      values: {
        mobile: 480,
        tablet: 750,
        desktop: 1076,
      },
    },
  })}
</code>```

I tried adding a declaration file but then I got the error on import saying
Module '"@mui/material/styles"' has no exported member 'ThemeProvider'.
Module '"@mui/material/styles"' has no exported member 'createTheme'.

```<code>declare module "@mui/material/styles" {
  interface BreakpointOverrides {
    xs: false; // removes the `xs` breakpoint
    sm: false;
    md: false;
    lg: false;
    xl: false;
    mobile: true; // adds the `mobile` breakpoint
    tablet: true;
    laptop: true;
    desktop: true;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Getting a typescript error when trying to use custom names for breakpoint values:

Type '{ mobile: number; tablet: number; desktop: number;}' is not assignable to type '{ xs: number; sm: number; md: number; lg: number; xl: number; }'.
  Object literal may only specify known properties, and 'mobile' does not exist in type '{ xs: number; sm: number; md: number; lg: number; xl: number; }'.

Here is my ThemProvider

import { ThemeProvider, createTheme } from "@mui/material/styles";

<ThemeProvider
  theme={createTheme({
    breakpoints: {
      values: {
        mobile: 480,
        tablet: 750,
        desktop: 1076,
      },
    },
  })}

I tried adding a declaration file but then I got the error on import saying
Module '"@mui/material/styles"' has no exported member 'ThemeProvider'.
Module '"@mui/material/styles"' has no exported member 'createTheme'.

declare module "@mui/material/styles" {
  interface BreakpointOverrides {
    xs: false; // removes the `xs` breakpoint
    sm: false;
    md: false;
    lg: false;
    xl: false;
    mobile: true; // adds the `mobile` breakpoint
    tablet: true;
    laptop: true;
    desktop: true;
  }
}


问:
Can't fetch right data on the button click from fireStore
I am doing my first bigger react project, where I am biulding web app for barbershop.
Idea is this. When I want to make reservation, I need to choose service type (regular haircut, beard trim or both) and then I need to choose barber. Depending which barber I choosed I fetch data from firestore. Barbers name is actually firebase collection name of the barber where is his schedule when there is free apointment.

Problem is this. When I choose service and then choose barber John, nothing happens, but if I then click on barber Carl I get John's schedule.

In the picture there is my component and how it is set up.

Here is the code of my function which is not working right.
I tried many things, it is not working even with timeOut.

```<code> useEffect(() => {
    if (!service || !barber) {
      return;
    }
    if (fetching) {
      setTimeout(async () => {
        try {
          const barbers_name = barber;
          const freeTimeRef = collection(db, `${barbers_name}`);
          const q = query(freeTimeRef);
          const querySnap = await getDocs(q);
          let freeTimeArr = [];
          querySnap.forEach((doc) => {
            freeTimeArr.push(doc.data().radno_vrijeme);
            return freeTimeArr;
          });
          setSchedule(freeTimeArr);
        } catch (error) {
          toast.error(error);
        } finally {
          setLoading(false);
          setFetching(false);
        }
      }, 100); // delay the call by 100 milliseconds
    }
  }, [fetching, barber]);
</code>```

setFetching is being used in this function, and this function changes state of the button from the picture, to the barbers name or service type.

```<code>const HandleChangeBarber = (e) => {
    setBarber(e.currentTarget.textContent);
    setFetching(true);
  };
</code>```

Body:
I am doing my first bigger react project, where I am biulding web app for barbershop.
Idea is this. When I want to make reservation, I need to choose service type (regular haircut, beard trim or both) and then I need to choose barber. Depending which barber I choosed I fetch data from firestore. Barbers name is actually firebase collection name of the barber where is his schedule when there is free apointment.

Problem is this. When I choose service and then choose barber John, nothing happens, but if I then click on barber Carl I get John's schedule.

In the picture there is my component and how it is set up.

Here is the code of my function which is not working right.
I tried many things, it is not working even with timeOut.

 useEffect(() => {
    if (!service || !barber) {
      return;
    }
    if (fetching) {
      setTimeout(async () => {
        try {
          const barbers_name = barber;
          const freeTimeRef = collection(db, `${barbers_name}`);
          const q = query(freeTimeRef);
          const querySnap = await getDocs(q);
          let freeTimeArr = [];
          querySnap.forEach((doc) => {
            freeTimeArr.push(doc.data().radno_vrijeme);
            return freeTimeArr;
          });
          setSchedule(freeTimeArr);
        } catch (error) {
          toast.error(error);
        } finally {
          setLoading(false);
          setFetching(false);
        }
      }, 100); // delay the call by 100 milliseconds
    }
  }, [fetching, barber]);

setFetching is being used in this function, and this function changes state of the button from the picture, to the barbers name or service type.

const HandleChangeBarber = (e) => {
    setBarber(e.currentTarget.textContent);
    setFetching(true);
  };


问:
how to use horizontal over-flow in css
please i'm trying to use horizontal overflow using css , if i use just images i get the horizontal scroll this how i use it with images

```<code> <div class="d-flex overflow-hidden overflow-scroll-x ">
          <img
            class="max-width-200 "
            src="../../../../assets/images/Creditrd.svg"
          />
          <img
            class="max-width-200 "
            src="../../../../assets/images/Creditard.svg"
          />
 </div>
</code>```

if i use background images i dont get anything here's how i do it

```<code><div class="d-flex  overflow-hidden overflow-scroll-x">

          <div class="account-wallet-imag  max-width-200  border-radius-16">
            heheh
          </div>
          <div class="account-wallet-imag max-width-200   border-radius-16">
            eheehhh
          </div>

        </div>
</code>```

this is my css

```<code>
.account-wallet-imag {
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
  width: 100%;
  height: 100%;
  background-image: url("@/assets/images/card.png");
}
</code>```

please how can i go about this

Title: how to use horizontal over-flow in css

Body:
please i'm trying to use horizontal overflow using css , if i use just images i get the horizontal scroll this how i use it with images

if i use background images i dont get anything here's how i do it

            heheh

            eheehhh

this is my css

.account-wallet-imag {
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
  width: 100%;
  height: 100%;
  background-image: url("@/assets/images/card.png");
}

please how can i go about this


问:
session.setFlushMode(FlushModeType.COMMIT) not working properly in Hibernate
In Hibernate setting FlushModeType.COMMIT on session object should flush the persistence context only when we explicitly commit the transaction right?

Here I have set FlushModeType.COMMIT on session object and both query objects as well, so when I persist the new Student("newStudent","newAddress") it should be flushed after both the select queries are executed, but instead here first the insert query for the persist statement was executed and then both the select queries were executed.
Can anyone please explain why is it happening like this?

please feel free to correct me, if my understanding of the flushing topic is wrong.

Entity Classes.

```<code>import javax.persistence.*;

@Entity
@Table(name="employee")
public class Employee {

    public Employee(){

    }
    public Employee(String EmployeeName, String EmployeeAddress){
        this.EmployeeName =EmployeeName;
        this.EmployeeAddress =EmployeeAddress;
    }

    @Column(name="employee_name")
    String EmployeeName;

    @Column(name="employee_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int EmployeeId;

    @Column(name="employee_address")
    String EmployeeAddress;
    // all getter and setter methods and toString method.
}

import javax.persistence.*;

@Entity
@Table(name="student")
public class Student {

    public Student(){

    }
    public Student(String studentName, String studentAddress){
        this.studentName=studentName;
        this.studentAddress=studentAddress;
    }

    @Column(name="student_name")
    String studentName;

    @Column(name="student_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int studentId;

    @Column(name="student_address")
    String studentAddress;
    // all getter and setter methods and toString method.
}
</code>```

Hibernate Configuration.

```<code>import Entities.Employee;
import Entities.Student;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class Configs {

    @Bean(name = "factory")
    public SessionFactory getSessionFactory(){

        org.hibernate.cfg.Configuration configuration=new org.hibernate.cfg.Configuration();
        StandardServiceRegistryBuilder builder=new StandardServiceRegistryBuilder();

        Properties properties=new Properties();
        properties.put(Environment.URL,"jdbc:mysql://localhost:3306/practiceHibernate");
        properties.put(Environment.DRIVER,"com.mysql.cj.jdbc.Driver");
        properties.put(Environment.PASS,"root");
        properties.put(Environment.USER,"root");
        properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS,"thread");
        properties.put(Environment.SHOW_SQL,true);
        properties.put(Environment.DIALECT,"org.hibernate.dialect.MySQL8Dialect");

        configuration.addAnnotatedClass(Student.class).addAnnotatedClass(Employee.class);
        configuration.addProperties(properties);
        ServiceRegistry service=builder.applySettings(properties).build();

        SessionFactory sessionFactory= configuration.buildSessionFactory(service);

        return sessionFactory;

    }

}
</code>```

Main code.

```<code>import Entities.Employee;
import Entities.Student;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.persistence.FlushModeType;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        ApplicationContext context=new AnnotationConfigApplicationContext(Configs.class);
        SessionFactory factory=context.getBean("factory",SessionFactory.class);

        Session session=factory.openSession();

        session.setFlushMode(FlushModeType.COMMIT);
        session.beginTransaction();

        session.persist(new Student("newStudent","newAddress"));

        Query<Employee> q=session.createQuery("select o from Employee o where o.EmployeeId>=1", Employee.class);

        q.setFlushMode(FlushModeType.COMMIT);
        List<Employee> list= q.getResultList();

        for(Employee o:list){
            System.out.println(o);
        }
        System.out.println("------------------------------------------------------------------------------");

        Query<Student> q1=session.createQuery("select s from Student s where s.studentId>=15",Student.class);

        q1.setFlushMode(FlushModeType.COMMIT);
        List<Student> list1= q1.getResultList();

        for(Student o:list1){
            System.out.println(o);
        }

        session.getTransaction().commit();
        factory.close();

    }
}
</code>```

output:

Hibernate: insert into student (student_address, student_name) values (?, ?)
Hibernate: select employee0_.employee_id as employee1_0_, employee0_.employee_address as employee2_0_, employee0_.employee_name as employee3_0_ from employee employee0_ where
employee0_.employee_id>=1
Employee{EmployeeName='employee1', EmployeeId=1, EmployeeAddress='employee1Address'}
Employee{EmployeeName='employee2', EmployeeId=2, EmployeeAddress='employee2Address'}

Hibernate: select student0_.student_id as student_1_1_, student0_.student_address as student_2_1_, student0_.student_name as student_3_1_ from student student0_ where student0_.student_id>=15
Student{studentName='student1', studentId=39, studentAddress='student1Address'}
Student{studentName='student2', studentId=40, studentAddress='student2Address'}
Student{studentName='newStudent', studentId=42, studentAddress='newAddress'}

Body:
In Hibernate setting FlushModeType.COMMIT on session object should flush the persistence context only when we explicitly commit the transaction right?

Here I have set FlushModeType.COMMIT on session object and both query objects as well, so when I persist the new Student("newStudent","newAddress") it should be flushed after both the select queries are executed, but instead here first the insert query for the persist statement was executed and then both the select queries were executed.
Can anyone please explain why is it happening like this?

please feel free to correct me, if my understanding of the flushing topic is wrong.

Entity Classes.

import javax.persistence.*;

@Entity
@Table(name="employee")
public class Employee {

    public Employee(){

    }
    public Employee(String EmployeeName, String EmployeeAddress){
        this.EmployeeName =EmployeeName;
        this.EmployeeAddress =EmployeeAddress;
    }

    @Column(name="employee_name")
    String EmployeeName;

    @Column(name="employee_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int EmployeeId;

    @Column(name="employee_address")
    String EmployeeAddress;
    // all getter and setter methods and toString method.
}

import javax.persistence.*;

@Entity
@Table(name="student")
public class Student {

    public Student(){

    }
    public Student(String studentName, String studentAddress){
        this.studentName=studentName;
        this.studentAddress=studentAddress;
    }

    @Column(name="student_name")
    String studentName;

    @Column(name="student_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int studentId;

    @Column(name="student_address")
    String studentAddress;
    // all getter and setter methods and toString method.
}

Hibernate Configuration.

import Entities.Employee;
import Entities.Student;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class Configs {

    @Bean(name = "factory")
    public SessionFactory getSessionFactory(){

        org.hibernate.cfg.Configuration configuration=new org.hibernate.cfg.Configuration();
        StandardServiceRegistryBuilder builder=new StandardServiceRegistryBuilder();

        Properties properties=new Properties();
        properties.put(Environment.URL,"jdbc:mysql://localhost:3306/practiceHibernate");
        properties.put(Environment.DRIVER,"com.mysql.cj.jdbc.Driver");
        properties.put(Environment.PASS,"root");
        properties.put(Environment.USER,"root");
        properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS,"thread");
        properties.put(Environment.SHOW_SQL,true);
        properties.put(Environment.DIALECT,"org.hibernate.dialect.MySQL8Dialect");

        configuration.addAnnotatedClass(Student.class).addAnnotatedClass(Employee.class);
        configuration.addProperties(properties);
        ServiceRegistry service=builder.applySettings(properties).build();

        SessionFactory sessionFactory= configuration.buildSessionFactory(service);

        return sessionFactory;

    }

}

Main code.

import Entities.Employee;
import Entities.Student;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.persistence.FlushModeType;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        ApplicationContext context=new AnnotationConfigApplicationContext(Configs.class);
        SessionFactory factory=context.getBean("factory",SessionFactory.class);

        Session session=factory.openSession();

        session.setFlushMode(FlushModeType.COMMIT);
        session.beginTransaction();

        session.persist(new Student("newStudent","newAddress"));

        Query<Employee> q=session.createQuery("select o from Employee o where o.EmployeeId>=1", Employee.class);

        q.setFlushMode(FlushModeType.COMMIT);
        List<Employee> list= q.getResultList();

        for(Employee o:list){
            System.out.println(o);
        }
        System.out.println("------------------------------------------------------------------------------");

        Query<Student> q1=session.createQuery("select s from Student s where s.studentId>=15",Student.class);

        q1.setFlushMode(FlushModeType.COMMIT);
        List<Student> list1= q1.getResultList();

        for(Student o:list1){
            System.out.println(o);
        }

        session.getTransaction().commit();
        factory.close();

    }
}

output:

Hibernate: insert into student (student_address, student_name) values (?, ?)
Hibernate: select employee0_.employee_id as employee1_0_, employee0_.employee_address as employee2_0_, employee0_.employee_name as employee3_0_ from employee employee0_ where
employee0_.employee_id>=1
Employee{EmployeeName='employee1', EmployeeId=1, EmployeeAddress='employee1Address'}
Employee{EmployeeName='employee2', EmployeeId=2, EmployeeAddress='employee2Address'}

Hibernate: select student0_.student_id as student_1_1_, student0_.student_address as student_2_1_, student0_.student_name as student_3_1_ from student student0_ where student0_.student_id>=15
Student{studentName='student1', studentId=39, studentAddress='student1Address'}
Student{studentName='student2', studentId=40, studentAddress='student2Address'}
Student{studentName='newStudent', studentId=42, studentAddress='newAddress'}


问:
Is there any way to listen or intercept an reportValidity call?
Currently I'm working on a React combobox component, wiling to add some custom validation behaviour.

My intention is to listen if reportvalidity or checkValidity has been called to run my validation and call setCustomValidity when needed. I want this behaviour to live in my component so I can reuse it in other pages or projects

Is there any way it can be achieved?


问:
how to pass variable from store to apollo query
I'm trying to pass a variable in store into an apollo query but I can't find the proper way to do it. the variable I'm trying to use is  user.username and if I do {{ user.username }} in the template section it prints but within the script section user outputs as a weird Json type thing.
so ideally I want my query to work something like so:

```<code>export default {
  setup() {
    ...

    const query = gql`
        query ($username: String) {
            ...
        }
    `;

    const variables = ref({
      username: /* user.username */,
    })

    const {result, loading, error} = useQuery(query, variables);

    return {
      user,
      result,
      loading
    }
  }
</code>```

I tried using computed() or Json.stringify and about a dozen other random things but nothing is working. There isn't any issues with the query itself since if I use a string like username: "username" the query works fine.

Hope I did a decent job at explaining things. thanks in advance

edit:
weird JSON thing:
home.vue:

```<code><template>
  {{ user }}
</template>

<script>
import {useStore} from "vuex";
import {auth} from "@/firebaseConfig";
import {computed} from "vue";

export default {
  setup() {
    const store = useStore()

    auth.onAuthStateChanged(user => {
      store.dispatch("fetchUser", user);
    });

    const user = computed(() => {
      return store.getters.user;
    });

   console.log(user)

    return {
      user
    }
  }
}
</script>
</code>```

output (console.log)

```<code>Object { _setter: setter(), dep: undefined, __v_isRef: true, __v_isReadonly: true, _dirty: true, effect: {…}, _cacheable: true }

__v_isReadonly: true

__v_isRef: true

_cacheable: true

_dirty: false

_setter: function setter()

Object { _setter: setter(), dep: undefined, __v_isRef: true, __v_isReadonly: true, _dirty: true, effect: {…}, _cacheable: true }

__v_isReadonly: true

__v_isRef: true

_cacheable: true

_dirty: false

_setter: function setter()

_value: Proxy { <target>: {…}, <handler>: {…} }

<target>: Object { loggedIn: true, data: {…} }

data: Object { Username: "dxbh0517", … }

Username: "dxbh0517"

uid: "2JlznrpQk"

<prototype>: Object { … }

loggedIn: true

<prototype>: Object { … }

<handler>: Object { get: get2(target, key, receiver), set: set2(target, key, value, receiver), deleteProperty: deleteProperty(target, key), … }

dep: Set [ {…} ]

effect: Object { fn: user(), scheduler: effect(), active: true, … }

<prototype>: Object { … }
Challenge.vue:30:12

dep: Set [ {…} ]

effect: Object { fn: user(), scheduler: effect(), active: true, … }

<prototype>: Object { … }
</code>```

output ({{ user }}):

```<code>{ "loggedIn": true, "data": { "Username": "username", "uid": "2JlznrpQk" } }
</code>```

Body:
I'm trying to pass a variable in store into an apollo query but I can't find the proper way to do it. the variable I'm trying to use is  user.username and if I do {{ user.username }} in the template section it prints but within the script section user outputs as a weird Json type thing.
so ideally I want my query to work something like so:

export default {
  setup() {
    ...

    const query = gql`
        query ($username: String) {
            ...
        }
    `;

    const variables = ref({
      username: /* user.username */,
    })

    const {result, loading, error} = useQuery(query, variables);

    return {
      user,
      result,
      loading
    }
  }

I tried using computed() or Json.stringify and about a dozen other random things but nothing is working. There isn't any issues with the query itself since if I use a string like username: "username" the query works fine.

Hope I did a decent job at explaining things. thanks in advance

edit:
weird JSON thing:
home.vue:

<template>
  {{ user }}
</template>

output (console.log)

Object { _setter: setter(), dep: undefined, __v_isRef: true, __v_isReadonly: true, _dirty: true, effect: {…}, _cacheable: true }

__v_isReadonly: true

__v_isRef: true

_cacheable: true

_dirty: false

_setter: function setter()

Object { _setter: setter(), dep: undefined, __v_isRef: true, __v_isReadonly: true, _dirty: true, effect: {…}, _cacheable: true }

__v_isReadonly: true

__v_isRef: true

_cacheable: true

_dirty: false

_setter: function setter()

_value: Proxy { <target>: {…}, <handler>: {…} }

<target>: Object { loggedIn: true, data: {…} }

data: Object { Username: "dxbh0517", … }

Username: "dxbh0517"

uid: "2JlznrpQk"

<prototype>: Object { … }

loggedIn: true

<prototype>: Object { … }

<handler>: Object { get: get2(target, key, receiver), set: set2(target, key, value, receiver), deleteProperty: deleteProperty(target, key), … }

dep: Set [ {…} ]

effect: Object { fn: user(), scheduler: effect(), active: true, … }

<prototype>: Object { … }
Challenge.vue:30:12

dep: Set [ {…} ]

effect: Object { fn: user(), scheduler: effect(), active: true, … }

<prototype>: Object { … }

output ({{ user }}):

{ "loggedIn": true, "data": { "Username": "username", "uid": "2JlznrpQk" } }


问:
Hide console window with Popen() and python.exe -c
I'm on Windows, using Python 3.11.1.  I have Python script that does some things and then self-deletes the entire folder/directory it is contained in.  But I also want to eliminate the console window briefly appearing when Popen() executes.

Working code but it briefly opens a console window:

import os
from pathlib import Path

# Get the path of this script file's parent directory
pathDirParent = Path(__file__).parent
# Change the working directory
os.chdir(Path("c:\\"))

# Command passed to a new spawn of python.exe to delete entire contents
# of parent directory of this script file
STR_CMD = fr""" C:\python\python.exe -c "import shutil; shutil.rmtree(r\"{pathDirParent}\");" """

subprocess.Popen(STR_CMD, shell=True)
```
<p>Also, I've experiment with <code>subprocess.STARTUPINFO()</code> as well, by adding this code to the mix:</p>
<pre class="lang-py prettyprint-override"><code>startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE

subprocess.Popen(STR_CMD, startupinfo=startupinfo, shell=True)
</code>```

In addition I have used both creationflags=subprocess.CREATE_NO_WINDOW and creationflags=subprocess.DETACHED_PROCESS with the above code.  Finally, with all the code combinations above, I have even tried calling pythonw.exe with Popen().  Unfortunately, the console window still appears briefly.

NOTE: If I remove shell=True, then the command doesn't work.

Is it possible to completely hide the console window appearing at all?

Body:
I'm on Windows, using Python 3.11.1.  I have Python script that does some things and then self-deletes the entire folder/directory it is contained in.  But I also want to eliminate the console window briefly appearing when Popen() executes.

Working code but it briefly opens a console window:

import os
from pathlib import Path

# Get the path of this script file's parent directory
pathDirParent = Path(__file__).parent
# Change the working directory
os.chdir(Path("c:\\"))

# Command passed to a new spawn of python.exe to delete entire contents
# of parent directory of this script file
STR_CMD = fr""" C:\python\python.exe -c "import shutil; shutil.rmtree(r\"{pathDirParent}\");" """

subprocess.Popen(STR_CMD, shell=True)

Also, I've experiment with subprocess.STARTUPINFO() as well, by adding this code to the mix:

startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE

subprocess.Popen(STR_CMD, startupinfo=startupinfo, shell=True)

In addition I have used both creationflags=subprocess.CREATE_NO_WINDOW and creationflags=subprocess.DETACHED_PROCESS with the above code.  Finally, with all the code combinations above, I have even tried calling pythonw.exe with Popen().  Unfortunately, the console window still appears briefly.

NOTE: If I remove shell=True, then the command doesn't work.

Is it possible to completely hide the console window appearing at all?


问:
package.config dependencies hell
I have to work on a legacy code base that uses packages.config to maintain NuGet dependencies. I implemented a feature that auto rotates a passwords for a service account. I need to install a NuGet package for it to function, 'companyName.PrivilegedAccessManagement'. The problem is whenever I try to add this package, I receive the error message:

One or more unresolved package dependency constraint detected in  the existing packages.config file. All dependency constraint must be resolved to add or update packages. If these packages are being updated this message may be ignored, if not the following errors may be blocking the current package operation:

MongoDB.Driver.Core2.13.2 constraint: System.ValueTuple(>=4.5.0), .CommonSecurity.Authentication3.70.30705 constraint Schwab.Logging 3.10.0

How to get this new package installed in the project? I can't migrate the project to ProjectReference format. The senior engineers/ organisation is not agreeing with that.

Edit: I've tried adding the packages through NuGet package manager console, adding the package name in packages.config file and csproj file. None of these things seem to have any affect. I also tried to added the dependencies before installing the actual package, it still doesn't work, just the error message changes.

The contents of the pakages.config file are listed below

```<code><package id=AutoMapper version=4.2.1 targetFramework=net451>
<package id=CommonLogging version=2.1.2 targetFramework=net451>
<package id=Crc32C.NET version=1.0.5.0 targetFramework=net462>
<package id=DnsClient version=1.4.0 targetFramework=net462>
<package id=Microsoft.AspNet.WebApi.Client version=5.2.7 targetFramework=net462>
<package id=Microsoft.AspNet.WebApi.Core version=5.2.7 targetFramework=net462>
<package id=MongoDB.Bson version=2.13.2 targetFramework=net462>
<package id=MongoDB.Driver version=2.13.2 targetFramework=net462>
<package id=MongoDB.Driver.Core version=2.13.2 targetFramework=net462>
<package id=MongoDB.Libmongocrypt version=1.2.2 targetFramework=net462>
<package id=Newtonsoft.Json version=9.0.1 targetFramework=net451>
<package id=CommonSecurity.Authentication version=3.70.30705 targetFramework=net451>
<package id=Logging version=3.10.2 targetFramework=net451>
<package id=One.Crypto version=1.0.10 targetFramework=net462>
<package id=Practices.Clients.Core version=2.2.4 targetFramework=net462>
<package id=Practices.Clients.Enterprise version=2.2.4 targetFramework=net451>
<package id=Practices.Clients.Rest version=2.2.4 targetFramework=net462>
<package id=Practices.Core version=2.2.4 targetFramework=net451>
<package id=Practices.Logging.Core version=2.2.4 targetFramework=net451>
<package id=Practices.Logging.Enterprise version=2.2.4 targetFramework=net451>
<package id=Practices.Logging.Event version=2.2.4 targetFramework=net451>
<package id=Wcfim version=3.2.16129 targetFramework=net451>
</code>```

Title: package.config dependencies hell

Body:
I have to work on a legacy code base that uses packages.config to maintain NuGet dependencies. I implemented a feature that auto rotates a passwords for a service account. I need to install a NuGet package for it to function, 'companyName.PrivilegedAccessManagement'. The problem is whenever I try to add this package, I receive the error message:

One or more unresolved package dependency constraint detected in  the existing packages.config file. All dependency constraint must be resolved to add or update packages. If these packages are being updated this message may be ignored, if not the following errors may be blocking the current package operation:

MongoDB.Driver.Core2.13.2 constraint: System.ValueTuple(>=4.5.0), .CommonSecurity.Authentication3.70.30705 constraint Schwab.Logging 3.10.0

How to get this new package installed in the project? I can't migrate the project to ProjectReference format. The senior engineers/ organisation is not agreeing with that.

Edit: I've tried adding the packages through NuGet package manager console, adding the package name in packages.config file and csproj file. None of these things seem to have any affect. I also tried to added the dependencies before installing the actual package, it still doesn't work, just the error message changes.

The contents of the pakages.config file are listed below

<package id=AutoMapper version=4.2.1 targetFramework=net451>
<package id=CommonLogging version=2.1.2 targetFramework=net451>
<package id=Crc32C.NET version=1.0.5.0 targetFramework=net462>
<package id=DnsClient version=1.4.0 targetFramework=net462>
<package id=Microsoft.AspNet.WebApi.Client version=5.2.7 targetFramework=net462>
<package id=Microsoft.AspNet.WebApi.Core version=5.2.7 targetFramework=net462>
<package id=MongoDB.Bson version=2.13.2 targetFramework=net462>
<package id=MongoDB.Driver version=2.13.2 targetFramework=net462>
<package id=MongoDB.Driver.Core version=2.13.2 targetFramework=net462>
<package id=MongoDB.Libmongocrypt version=1.2.2 targetFramework=net462>
<package id=Newtonsoft.Json version=9.0.1 targetFramework=net451>
<package id=CommonSecurity.Authentication version=3.70.30705 targetFramework=net451>
<package id=Logging version=3.10.2 targetFramework=net451>
<package id=One.Crypto version=1.0.10 targetFramework=net462>
<package id=Practices.Clients.Core version=2.2.4 targetFramework=net462>
<package id=Practices.Clients.Enterprise version=2.2.4 targetFramework=net451>
<package id=Practices.Clients.Rest version=2.2.4 targetFramework=net462>
<package id=Practices.Core version=2.2.4 targetFramework=net451>
<package id=Practices.Logging.Core version=2.2.4 targetFramework=net451>
<package id=Practices.Logging.Enterprise version=2.2.4 targetFramework=net451>
<package id=Practices.Logging.Event version=2.2.4 targetFramework=net451>
<package id=Wcfim version=3.2.16129 targetFramework=net451>


问:
GORM thread-safe connection
I have simple code on golang which is executed while receive request and update a value on database.

```<code>res := db.Where(ExampleStructforDB{Id: Id}).FirstOrCreate(&ls)
    if res.Error != nil {
        log.Error(res.Error)
        return res.Error
    }
ls.count += 1

err = Db.Save(&ls).Error
if err != nil {
    log.Error(err)
    return err
}
</code>```

Sometimes I see that there is a race condition.Time-to-time some of the requests gets same value from database for updating.But in fact that, every request is increase or decrease count on db.

As far as I understand, GORM says that it should be use Session.
https://gorm.io/docs/session.html

Is it right approach for it ?

Title: GORM thread-safe connection

Body:
I have simple code on golang which is executed while receive request and update a value on database.

res := db.Where(ExampleStructforDB{Id: Id}).FirstOrCreate(&ls)
    if res.Error != nil {
        log.Error(res.Error)
        return res.Error
    }
ls.count += 1

err = Db.Save(&ls).Error
if err != nil {
    log.Error(err)
    return err
}

Sometimes I see that there is a race condition.Time-to-time some of the requests gets same value from database for updating.But in fact that, every request is increase or decrease count on db.

As far as I understand, GORM says that it should be use Session.
https://gorm.io/docs/session.html

Is it right approach for it ?


问:
No operator "+=" matches these operands

So I am making physics engine and I have written my own math.h file and it is giving me error when I use few operators between vectors and floats..

It should just apply force on entities from list but it is giving error.

Here is my math.h file

```<code>#ifndef MATH_H
#define MATH_H

struct vec2
{
    float x, y;
};

inline
vec2 operator-(vec2 &a)
{
    vec2 c = {};

    c.x = -a.x;
    c.y = -a.y;

    return c;
}

inline
vec2 operator+(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x + b.x;
    c.y = a.y + b.y;

    return c;
}

inline
vec2 operator-(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x - b.x;
    c.y = a.y - b.y;

    return c;
}

inline
vec2 operator*(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x * b.x;
    c.y = a.y * b.y;

    return c;
}

inline
vec2 operator*(float &a, vec2 &b)
{
    vec2 c = {};

    c.x = a * b.x;
    c.y = a * b.y;

    return c;
}

inline
vec2 operator*(vec2 &a, float &b)
{
    vec2 c = {};

    c.x = a.x * b;
    c.y = a.y * b;

    return c;
}

inline
vec2 operator/(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x / b.x;
    c.y = a.y / b.y;

    return c;
}

inline
vec2 operator/(vec2 &a, float &b)
{
    vec2 c = {};

    c.x = a.x / b;
    c.y = a.y / b;

    return c;
}

inline
vec2 operator/(float &a, vec2 &b)
{
    vec2 c = {};

    c.x = b.x / a;
    c.y = b.y / a;

    return c;
}

inline
vec2 operator+=(vec2& a, vec2& b)
{
    vec2 c = {};
    a.x += b.x;
    a.y += b.y;

    return c;
}

inline
vec2 operator+=(float a, vec2& b)
{
    vec2 c = {};
    a += b.x;
    a += b.y;

    return c;
}

inline
vec2 operator+=(vec2& a, float b)
{
    vec2 c = {};
    a.x += b;
    a.y += b;

    return c;
}

#endif
</code>```

Here is my entity struct :

```<code>struct Entity
{
    vec2 Position, Velocity, Force;
    float Mass;
};
</code>```

Here is my loop where I get bug :

```<code>
for (int i = 0; i < entites.size(); i++)
    {
        entites[i].Force += entites[i].Mass * Gravity;

    }
</code>```

I thought it would apply force to objects but it is giving me bug..

Title: No operator "+=" matches these operands

Body:
So I am making physics engine and I have written my own math.h file and it is giving me error when I use few operators between vectors and floats..

It should just apply force on entities from list but it is giving error.

Here is my math.h file

#ifndef MATH_H
#define MATH_H

struct vec2
{
    float x, y;
};

inline
vec2 operator-(vec2 &a)
{
    vec2 c = {};

    c.x = -a.x;
    c.y = -a.y;

    return c;
}

inline
vec2 operator+(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x + b.x;
    c.y = a.y + b.y;

    return c;
}

inline
vec2 operator-(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x - b.x;
    c.y = a.y - b.y;

    return c;
}

inline
vec2 operator*(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x * b.x;
    c.y = a.y * b.y;

    return c;
}

inline
vec2 operator*(float &a, vec2 &b)
{
    vec2 c = {};

    c.x = a * b.x;
    c.y = a * b.y;

    return c;
}

inline
vec2 operator*(vec2 &a, float &b)
{
    vec2 c = {};

    c.x = a.x * b;
    c.y = a.y * b;

    return c;
}

inline
vec2 operator/(vec2 &a, vec2 &b)
{
    vec2 c = {};

    c.x = a.x / b.x;
    c.y = a.y / b.y;

    return c;
}

inline
vec2 operator/(vec2 &a, float &b)
{
    vec2 c = {};

    c.x = a.x / b;
    c.y = a.y / b;

    return c;
}

inline
vec2 operator/(float &a, vec2 &b)
{
    vec2 c = {};

    c.x = b.x / a;
    c.y = b.y / a;

    return c;
}

inline
vec2 operator+=(vec2& a, vec2& b)
{
    vec2 c = {};
    a.x += b.x;
    a.y += b.y;

    return c;
}

inline
vec2 operator+=(float a, vec2& b)
{
    vec2 c = {};
    a += b.x;
    a += b.y;

    return c;
}

inline
vec2 operator+=(vec2& a, float b)
{
    vec2 c = {};
    a.x += b;
    a.y += b;

    return c;
}

#endif

Here is my entity struct :

struct Entity
{
    vec2 Position, Velocity, Force;
    float Mass;
};

Here is my loop where I get bug :

for (int i = 0; i < entites.size(); i++)
    {
        entites[i].Force += entites[i].Mass * Gravity;

    }

I thought it would apply force to objects but it is giving me bug..


问:
Why do I get an empty plot?
I'm doing a topic model and I'm using matplotlib to visualize the results. I would like to plot word counts and the weights of keywords in one chart. The dataframe has the data, but the plot is empty. Could anybody help me, what is wrong with the code?

```<code>from collections import Counter
topics = final_model.show_topics(formatted=False)
data_flat = [w for w_list in Tweet_df.tokens for w in w_list]
counter = Counter(data_flat)

out = []
for i, topic in topics:
   for word, weight in topic:
       out.append([word, i , weight, counter[word]])

df = pd.DataFrame(out, columns=['word', 'topic_id', 'importance', 'word_count'])

print(df)

# Plot Word Count and Weights of Topic Keywords
fig, axes = plt.subplots(2, 2, figsize=(16,10), sharey=True, dpi=160)
cols = [color for name, color in mcolors.TABLEAU_COLORS.items()]
for i, ax in enumerate(axes.flatten()):
   ax.bar(x='word', height="word_count", data=df.loc[df.topic_id==i, :], color=cols[i], width=0.5, alpha=0.3, label='Word Count')
   ax_twin = ax.twinx()
   ax_twin.bar(x='word', height="importance", data=df.loc[df.topic_id==i, :], color=cols[i], width=0.2, label='Weights')
   ax.set_ylabel('Word Count', color=cols[i])
   ax_twin.set_ylim(0, 0.030); ax.set_ylim(0, 3500)
   ax.set_title('Topic: ' + str(i), color=cols[i], fontsize=16)
   ax.tick_params(axis='y', left=False)
   ax.set_xticklabels(df.loc[df.topic_id==i, 'word'], rotation=30, horizontalalignment= 'right')
   ax.legend(loc='upper left'); ax_twin.legend(loc='upper right')

fig.tight_layout(w_pad=2)
fig.suptitle('Word Count and Importance of Topic Keywords', fontsize=22, y=1.05)
plt.show()
</code>```

Thank you for your help!!

Title: Why do I get an empty plot?

Body:
I'm doing a topic model and I'm using matplotlib to visualize the results. I would like to plot word counts and the weights of keywords in one chart. The dataframe has the data, but the plot is empty. Could anybody help me, what is wrong with the code?

from collections import Counter
topics = final_model.show_topics(formatted=False)
data_flat = [w for w_list in Tweet_df.tokens for w in w_list]
counter = Counter(data_flat)

out = []
for i, topic in topics:
   for word, weight in topic:
       out.append([word, i , weight, counter[word]])

df = pd.DataFrame(out, columns=['word', 'topic_id', 'importance', 'word_count'])

print(df)

# Plot Word Count and Weights of Topic Keywords
fig, axes = plt.subplots(2, 2, figsize=(16,10), sharey=True, dpi=160)
cols = [color for name, color in mcolors.TABLEAU_COLORS.items()]
for i, ax in enumerate(axes.flatten()):
   ax.bar(x='word', height="word_count", data=df.loc[df.topic_id==i, :], color=cols[i], width=0.5, alpha=0.3, label='Word Count')
   ax_twin = ax.twinx()
   ax_twin.bar(x='word', height="importance", data=df.loc[df.topic_id==i, :], color=cols[i], width=0.2, label='Weights')
   ax.set_ylabel('Word Count', color=cols[i])
   ax_twin.set_ylim(0, 0.030); ax.set_ylim(0, 3500)
   ax.set_title('Topic: ' + str(i), color=cols[i], fontsize=16)
   ax.tick_params(axis='y', left=False)
   ax.set_xticklabels(df.loc[df.topic_id==i, 'word'], rotation=30, horizontalalignment= 'right')
   ax.legend(loc='upper left'); ax_twin.legend(loc='upper right')

fig.tight_layout(w_pad=2)
fig.suptitle('Word Count and Importance of Topic Keywords', fontsize=22, y=1.05)
plt.show()

Thank you for your help!!


问:
issue with updating player level by loading scene
I'm having trouble saving and loading a scene. I have this code:

```<code>public void LoadData(Data data)
{
    this.sceneName = data.sceneName;
    SceneManager.LoadScene(sceneName);
    this.level = data.level;
}

public void SaveData(ref Data data)
{
    data.sceneName = SceneManager.GetActiveScene().name;
    data.level = this.level;
}
</code>```

and when I have a line in my code that contains "SceneManager.LoadScene(sceneName);" is the player's level, which he writes at the beginning of the code as follows `public int level = 1;
public int health = 100; I'm signing up incorrectly. The Player level object changes, but when I want to get it using player.level; it shows me level "1" even though it is equal to 2

All I know is that the problem occurs by loading the scene. When I remove the line
SceneManager.LoadScene(sceneName);
level updates normally

Body:
I'm having trouble saving and loading a scene. I have this code:

public void LoadData(Data data)
{
    this.sceneName = data.sceneName;
    SceneManager.LoadScene(sceneName);
    this.level = data.level;
}

public void SaveData(ref Data data)
{
    data.sceneName = SceneManager.GetActiveScene().name;
    data.level = this.level;
}

and when I have a line in my code that contains "SceneManager.LoadScene(sceneName);" is the player's level, which he writes at the beginning of the code as follows `public int level = 1;
public int health = 100; I'm signing up incorrectly. The Player level object changes, but when I want to get it using player.level; it shows me level "1" even though it is equal to 2

All I know is that the problem occurs by loading the scene. When I remove the line
SceneManager.LoadScene(sceneName);
level updates normally


问:
How to feed Images of different size being into the CNN
The problem being solved is a binary classification using CNN. Here I have images of different size. I am scaled down the images to 20% and normalizing them to the range (0,1) and obviously they still have different sizes. I am using x_train = tf.ragged.constant(normalized_train) to pass them into the CNN but I get an error as mentioned below -

ValueError: The channel dimension of the inputs should be defined. Found None.

Can anyone help?

Also, please suggest if I can use padding around the images to bring everything into same size without distorting the images.

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Dropout, MaxPooling2D, Flatten, Dense

model = Sequential()

model.add(Conv2D(filters=32, kernel_size=3, activation="relu"))

model.add(Conv2D(filters=64, kernel_size=3, activation="relu"))

model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Dropout(rate=0.2))

model.add(Flatten())

model.add(Dense(128, activation="relu"))

model.add(Dense(1, activation="sigmoid"))

**X_train = tf.ragged.constant(normalized_train)** # allows to pass different size objects
y_train = tf.convert_to_tensor(y_train) # converting list type to tensor
**X_test = tf.ragged.constant(normalized_test)**
y_test = tf.convert_to_tensor(y_test) # converting list type to tensor

model.compile(loss="binary_crossentropy", metrics=\["accuracy"\], optimizer="adam")

model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs = 3)
</code>```

Detailed error is:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-aa60c2e9ae0d> in <module>
      1 model.compile(loss="binary_crossentropy", metrics=["accuracy"], optimizer="adam")
      2 # model.fit(normalized_train, y_train, validation_data=(normalized_test,y_test), epochs = 3)
----> 3 model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs = 3)

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1182                 _r=1):
   1183               callbacks.on_train_batch_begin(step)
-> 1184               tmp_logs = self.train_function(iterator)
   1185               if data_handler.should_sync:
   1186                 context.async_wait()

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    883
    884       with OptionalXlaContext(self._jit_compile):
--> 885         result = self._call(*args, **kwds)
    886
    887       new_tracing_count = self.experimental_get_tracing_count()

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    931       # This is the first call of __call__, so we have to initialize.
    932       initializers = []
--> 933       self._initialize(args, kwds, add_initializers_to=initializers)
    934     finally:
    935       # At this point we know that the initialization is complete (or less

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    758     self._concrete_stateful_fn = (
    759         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 760             *args, **kwds))
    761
    762     def invalid_creator_scope(*unused_args, **unused_kwds):

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   3064       args, kwargs = None, None
   3065     with self._lock:
-> 3066       graph_function, _ = self._maybe_define_function(args, kwargs)
   3067     return graph_function
   3068

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3461
   3462           self._function_cache.missed.add(call_context_key)
-> 3463           graph_function = self._create_graph_function(args, kwargs)
   3464           self._function_cache.primary[cache_key] = graph_function
   3465

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3306             arg_names=arg_names,
   3307             override_flat_arg_shapes=override_flat_arg_shapes,
-> 3308             capture_by_value=self._capture_by_value),
   3309         self._function_attributes,
   3310         function_spec=self.function_spec,

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes, acd_record_initial_resource_uses)
   1005         _, original_func = tf_decorator.unwrap(python_func)
   1006
-> 1007       func_outputs = python_func(*func_args, **func_kwargs)
   1008
   1009       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    666         # the function a weak reference to itself to avoid a reference cycle.
    667         with OptionalXlaContext(compile_with_xla):
--> 668           out = weak_wrapped_fn().__wrapped__(*args, **kwds)
    669         return out
    670

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    992           except Exception as e:  # pylint:disable=broad-except
    993             if hasattr(e, "ag_error_metadata"):
--> 994               raise e.ag_error_metadata.to_exception(e)
    995             else:
    996               raise

ValueError: in user code:

    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:842 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:1286 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2849 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:3632 _call_for_each_replica
        return fn(*args, **kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:835 run_step  **
        outputs = model.train_step(data)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:787 train_step
        y_pred = self(x, training=True)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py:1037 __call__
        outputs = call_fn(inputs, *args, **kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/sequential.py:383 call
        outputs = layer(inputs, **kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py:1030 __call__
        self._maybe_build(inputs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py:2659 _maybe_build
        self.build(input_shapes)  # pylint:disable=not-callable
    /opt/anaconda3/lib/python3.7/site-packages/keras/layers/convolutional.py:187 build
        input_channel = self._get_input_channel(input_shape)
    /opt/anaconda3/lib/python3.7/site-packages/keras/layers/convolutional.py:366 _get_input_channel
        raise ValueError('The channel dimension of the inputs '

    ValueError: The channel dimension of the inputs should be defined. Found `None`.
</code>```

Body:
The problem being solved is a binary classification using CNN. Here I have images of different size. I am scaled down the images to 20% and normalizing them to the range (0,1) and obviously they still have different sizes. I am using x_train = tf.ragged.constant(normalized_train) to pass them into the CNN but I get an error as mentioned below -

ValueError: The channel dimension of the inputs should be defined. Found None.

Can anyone help?

Also, please suggest if I can use padding around the images to bring everything into same size without distorting the images.

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Dropout, MaxPooling2D, Flatten, Dense

model = Sequential()

model.add(Conv2D(filters=32, kernel_size=3, activation="relu"))

model.add(Conv2D(filters=64, kernel_size=3, activation="relu"))

model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Dropout(rate=0.2))

model.add(Flatten())

model.add(Dense(128, activation="relu"))

model.add(Dense(1, activation="sigmoid"))

**X_train = tf.ragged.constant(normalized_train)** # allows to pass different size objects
y_train = tf.convert_to_tensor(y_train) # converting list type to tensor
**X_test = tf.ragged.constant(normalized_test)**
y_test = tf.convert_to_tensor(y_test) # converting list type to tensor

model.compile(loss="binary_crossentropy", metrics=\["accuracy"\], optimizer="adam")

model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs = 3)

Detailed error is:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-aa60c2e9ae0d> in <module>
      1 model.compile(loss="binary_crossentropy", metrics=["accuracy"], optimizer="adam")
      2 # model.fit(normalized_train, y_train, validation_data=(normalized_test,y_test), epochs = 3)
----> 3 model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs = 3)

/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1182                 _r=1):
   1183               callbacks.on_train_batch_begin(step)
-> 1184               tmp_logs = self.train_function(iterator)
   1185               if data_handler.should_sync:
   1186                 context.async_wait()

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    883
    884       with OptionalXlaContext(self._jit_compile):
--> 885         result = self._call(*args, **kwds)
    886
    887       new_tracing_count = self.experimental_get_tracing_count()

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    931       # This is the first call of __call__, so we have to initialize.
    932       initializers = []
--> 933       self._initialize(args, kwds, add_initializers_to=initializers)
    934     finally:
    935       # At this point we know that the initialization is complete (or less

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    758     self._concrete_stateful_fn = (
    759         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 760             *args, **kwds))
    761
    762     def invalid_creator_scope(*unused_args, **unused_kwds):

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   3064       args, kwargs = None, None
   3065     with self._lock:
-> 3066       graph_function, _ = self._maybe_define_function(args, kwargs)
   3067     return graph_function
   3068

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3461
   3462           self._function_cache.missed.add(call_context_key)
-> 3463           graph_function = self._create_graph_function(args, kwargs)
   3464           self._function_cache.primary[cache_key] = graph_function
   3465

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3306             arg_names=arg_names,
   3307             override_flat_arg_shapes=override_flat_arg_shapes,
-> 3308             capture_by_value=self._capture_by_value),
   3309         self._function_attributes,
   3310         function_spec=self.function_spec,

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes, acd_record_initial_resource_uses)
   1005         _, original_func = tf_decorator.unwrap(python_func)
   1006
-> 1007       func_outputs = python_func(*func_args, **func_kwargs)
   1008
   1009       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    666         # the function a weak reference to itself to avoid a reference cycle.
    667         with OptionalXlaContext(compile_with_xla):
--> 668           out = weak_wrapped_fn().__wrapped__(*args, **kwds)
    669         return out
    670

/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    992           except Exception as e:  # pylint:disable=broad-except
    993             if hasattr(e, "ag_error_metadata"):
--> 994               raise e.ag_error_metadata.to_exception(e)
    995             else:
    996               raise

ValueError: in user code:

    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:842 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:1286 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2849 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:3632 _call_for_each_replica
        return fn(*args, **kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:835 run_step  **
        outputs = model.train_step(data)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py:787 train_step
        y_pred = self(x, training=True)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py:1037 __call__
        outputs = call_fn(inputs, *args, **kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/sequential.py:383 call
        outputs = layer(inputs, **kwargs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py:1030 __call__
        self._maybe_build(inputs)
    /opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py:2659 _maybe_build
        self.build(input_shapes)  # pylint:disable=not-callable
    /opt/anaconda3/lib/python3.7/site-packages/keras/layers/convolutional.py:187 build
        input_channel = self._get_input_channel(input_shape)
    /opt/anaconda3/lib/python3.7/site-packages/keras/layers/convolutional.py:366 _get_input_channel
        raise ValueError('The channel dimension of the inputs '

    ValueError: The channel dimension of the inputs should be defined. Found `None`.


问:
How do I serialize/deserialize &[f64] using serde in Rust?
This compiles successfully:

```<code>#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    value: f64
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let perspn = Person { name: "me".into(), value: 30_f64};
    let serialized = serde_json::to_string(&perspn).unwrap();
    println!("{:?}", serialized);
    Ok(())
}
</code>```

But on changing a member of the struct to &[f64], then compilation fails

```<code>#[derive(Serialize, Deserialize)]
struct Person<'a> {
    name: String,
    value: &'a[f64]
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let perspn = Person { name: "me".into(), value: &[30_f64]};
    let serialized = serde_json::to_string(&perspn).unwrap();
    println!("{:?}", serialized);
    Ok(())
}
</code>```

fails with error:

```<code>error[E0277]: the trait bound `&[f64]: Deserialize<'_>` is not satisfied
   --> src/main.rs:168:5
    |
168 |     value: &'a[f64]
    |     ^^^^^ the trait `Deserialize<'_>` is not implemented for `&[f64]`
    |
    = help: the following other types implement trait `Deserialize<'de>`:
              &'a [u8]
              [T; 0]
              [T; 10]
              [T; 11]
              [T; 12]
              [T; 13]
              [T; 14]
              [T; 15]
            and 26 others

</code>```

Why is this? Why does serde have a default deserialiser for f64 but not for &[f64]?

Looking at the error it looks like it is only [u8] that serde can handle by default. Why is this?

Now the question is, how do I deserialize &[f64]? I know I will need to write a custom deserializer for it, but given that a custom one was not given, I am wondering if there are edge case in the implementation that made that the case and which I need to be aware of?

Body:
This compiles successfully:

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    value: f64
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let perspn = Person { name: "me".into(), value: 30_f64};
    let serialized = serde_json::to_string(&perspn).unwrap();
    println!("{:?}", serialized);
    Ok(())
}

But on changing a member of the struct to &[f64], then compilation fails

#[derive(Serialize, Deserialize)]
struct Person<'a> {
    name: String,
    value: &'a[f64]
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let perspn = Person { name: "me".into(), value: &[30_f64]};
    let serialized = serde_json::to_string(&perspn).unwrap();
    println!("{:?}", serialized);
    Ok(())
}

fails with error:

error[E0277]: the trait bound `&[f64]: Deserialize<'_>` is not satisfied
   --> src/main.rs:168:5
    |
168 |     value: &'a[f64]
    |     ^^^^^ the trait `Deserialize<'_>` is not implemented for `&[f64]`
    |
    = help: the following other types implement trait `Deserialize<'de>`:
              &'a [u8]
              [T; 0]
              [T; 10]
              [T; 11]
              [T; 12]
              [T; 13]
              [T; 14]
              [T; 15]
            and 26 others

Why is this? Why does serde have a default deserialiser for f64 but not for &[f64]?

Looking at the error it looks like it is only [u8] that serde can handle by default. Why is this?

Now the question is, how do I deserialize &[f64]? I know I will need to write a custom deserializer for it, but given that a custom one was not given, I am wondering if there are edge case in the implementation that made that the case and which I need to be aware of?


问:
How can I Render Data To Main Template In Other Extended View From Main Template?
First of all, hello everyone. I apologize to everyone for my bad English, I will try my best. I am making a video site, in this site there are three main views, they are single-video-view, index-view and main-view. All other views extends from main-view (%extends 'base/main.html' %). There is a sidebar that should appear on all pages. In this sidebar, the categories of pre-loaded videos should be listed.

My urls.py:

```<code>urlpatterns = [
    path('',views.index,name="index"),
    path('main/',views.main,name="main"),
    path('video/<slug:slug>/',views.video,name="video"),
    #path('test/',views.category,name="setcategory"),
    path('apivideo/',views.apivideo,name="apivideo"),
    ]
</code>```

If I visit main.html directly working fine
Single video view, categories not listing
Index view, categories not listing

View.py:

```<code>
def index(request):

    # q = request.GET.get('q')
    # if request.GET.get('q') != None:
    if 'q' in request.GET and request.GET['q']:
        page = request.GET.get('page', 1)
        q = request.GET['q']
        videos = Video.objects.filter(
            Q(video_title__icontains=q) | Q(video_tags__icontains=q))
        paginator = Paginator(videos, 24)
        videos = paginator.page(page)
        return render(request, 'base/index.html', {'videos': videos, 'q': q})

    else:
        main(request)
        videos = Video.objects.all().order_by("-id")
        paginator = Paginator(videos, 24)
        page_number = request.GET.get('page')
        videos = paginator.get_page(page_number)
        return render(request, 'base/index.html', {'videos': videos})

def main(request):

    setcategory = []
    category = Video.objects.values_list('video_tags', flat=True)

    for i in range(0, len(category)):
        for x in range(0, len(category[i])):
            categorycount = Video.objects.filter(Q(video_title__icontains=str(
                category[i][x]).lower()) | Q(video_tags__icontains=str(category[i][x]).lower())).count()
            if (categorycount >= 10):
                print("if: " + str(categorycount))
                setcategory.append(str(category[i][x]).lower())
            else:
                print("else: " + str(categorycount))
                break
    setcategory = sorted([*set(setcategory)])
    return render(request, 'base/main.html', {'setcategory': setcategory})

def video(request, slug):
    eachvideo = Video.objects.get(video_slug=slug)
    randomVideo = list(Video.objects.all())
    randomVideo = random.sample(randomVideo, 20)

    return render(request, 'base/video.html', {'eachvideo': eachvideo, 'randomVideo': randomVideo})
</code>```

Main.html:

```<code>Some HTML..
  <ul class="sidebar navbar-nav toggled">
            {% if setcategory %}
            {% for category in setcategory %}
            <li class="nav-item active">
               <a class="nav-link" href="{% url 'index' %}?q={{category}}">
               <i class="fas fa-fw fa-home"></i>
               <span>{{category|title}}</span>
               </a>
            </li>
            {% endfor %}
            {% endif %}
         </ul>
Some HTML..
</code>```

The code I wrote for this works fine, but it only works when I add a redirect to the main-view specifically in the url .py file and go to the main view page. What I want is for these categories to appear in the sidebar when the user browses the index or other pages.

Body:
First of all, hello everyone. I apologize to everyone for my bad English, I will try my best. I am making a video site, in this site there are three main views, they are single-video-view, index-view and main-view. All other views extends from main-view (%extends 'base/main.html' %). There is a sidebar that should appear on all pages. In this sidebar, the categories of pre-loaded videos should be listed.

My urls.py:

urlpatterns = [
    path('',views.index,name="index"),
    path('main/',views.main,name="main"),
    path('video/<slug:slug>/',views.video,name="video"),
    #path('test/',views.category,name="setcategory"),
    path('apivideo/',views.apivideo,name="apivideo"),
    ]

If I visit main.html directly working fine
Single video view, categories not listing
Index view, categories not listing

View.py:

def index(request):

    # q = request.GET.get('q')
    # if request.GET.get('q') != None:
    if 'q' in request.GET and request.GET['q']:
        page = request.GET.get('page', 1)
        q = request.GET['q']
        videos = Video.objects.filter(
            Q(video_title__icontains=q) | Q(video_tags__icontains=q))
        paginator = Paginator(videos, 24)
        videos = paginator.page(page)
        return render(request, 'base/index.html', {'videos': videos, 'q': q})

    else:
        main(request)
        videos = Video.objects.all().order_by("-id")
        paginator = Paginator(videos, 24)
        page_number = request.GET.get('page')
        videos = paginator.get_page(page_number)
        return render(request, 'base/index.html', {'videos': videos})

def main(request):

    setcategory = []
    category = Video.objects.values_list('video_tags', flat=True)

    for i in range(0, len(category)):
        for x in range(0, len(category[i])):
            categorycount = Video.objects.filter(Q(video_title__icontains=str(
                category[i][x]).lower()) | Q(video_tags__icontains=str(category[i][x]).lower())).count()
            if (categorycount >= 10):
                print("if: " + str(categorycount))
                setcategory.append(str(category[i][x]).lower())
            else:
                print("else: " + str(categorycount))
                break
    setcategory = sorted([*set(setcategory)])
    return render(request, 'base/main.html', {'setcategory': setcategory})

def video(request, slug):
    eachvideo = Video.objects.get(video_slug=slug)
    randomVideo = list(Video.objects.all())
    randomVideo = random.sample(randomVideo, 20)

    return render(request, 'base/video.html', {'eachvideo': eachvideo, 'randomVideo': randomVideo})

Main.html:

Some HTML..

            {% if setcategory %}
            {% for category in setcategory %}

               {{category|title}}

            {% endfor %}
            {% endif %}

Some HTML..

The code I wrote for this works fine, but it only works when I add a redirect to the main-view specifically in the url .py file and go to the main view page. What I want is for these categories to appear in the sidebar when the user browses the index or other pages.


问:
TypeError: String indices mismatch when generating Queen rule
I'm trying to generate a Moran's I score from a geodataframe. I'm using libpysal.weights.Queen to generate it. One of the parameters asks for "geom_col" and so I give it the "Geometry" column of my Geodataframe. The problem is that a error is returned: string indices must be integers. I have no idea what this means and how I'm supposed to address, especially in the context of libpysal.weights.Queen.

w_queen = Queen.from_dataframe("shapefile", geom_col="geometry")

TypeError: string indices must be integers


问:
Problems with formatting when pasting into excel
I am encountering strange behavior when setting the clipboard in JavaScript and pasting in excel. When I copy and paste directly into excel I get this first format where the cell is expanded vertically and the content is wrapped however when I paste into a text editor first, copy the exact thing that was pasted, and then paste into excel, I get the second format where it either cuts off the part that overflows the cell or expands into empty cells. What determines the format of pasted text in excel? is there a way I can force achieve the second format straight from the copied text from JS?

I am not sure if this will help in solving the problem but I copying the data from a table generated with the Handsontable library using a custom function to overwrite the copy data with the beforeCopy hook.

Nothing looks different in the copied text that I can tell, Here are the two different strings that result in different formatted outputs:

This is a test of copying and pasting text from JavaScript.

This is a test of copying and pasting text from JavaScript.

They look identical to me so I am not sure where the format difference is coming from.

Thanks.


问:
How would I turn a phase transition chart into a 2D array in C#?
I am trying to make a C# program that will take input for temperature(double) and pressure(also double) and output the phase the material is in(string) via a 2D array, but it is impossible to write every pressure and temperature combination in a 2D array, while still being precise. ex:

0K
0.01k

0 atm
SOLID
SOLID

0.01 atm
SOLID
SOLID

Another, perhaps simpler, example is getting the color of an image based on coordinates. here is some pseudocode.

public string getColor(int x, int y)
{
    return (x, y).color of the image;
}
```
<p>Other than using a super complicated 2D array, i have no clue how to do this.
Is there a way to automate the
array being created, or a better way to do this?</p>
<pre class="lang-cs prettyprint-override"><code>public string getState(double temperature, double pressure){
    return the string at (temperature, pressure) on the phase diagram;
}
</code>```

If I need to be more clear, please tell me.

Body:
I am trying to make a C# program that will take input for temperature(double) and pressure(also double) and output the phase the material is in(string) via a 2D array, but it is impossible to write every pressure and temperature combination in a 2D array, while still being precise. ex:

0K
0.01k

0 atm
SOLID
SOLID

0.01 atm
SOLID
SOLID

Another, perhaps simpler, example is getting the color of an image based on coordinates. here is some pseudocode.

public string getColor(int x, int y)
{
    return (x, y).color of the image;
}

Other than using a super complicated 2D array, i have no clue how to do this.
Is there a way to automate the
array being created, or a better way to do this?

public string getState(double temperature, double pressure){
    return the string at (temperature, pressure) on the phase diagram;
}

If I need to be more clear, please tell me.


问:
How to filter an array using ion-slides
I'm using an ion-select to do some dynamic filtering in an array:

```<code><div *ngIf="events!=undefined">
<form #regForm="ngForm">
  <ion-item>
    <ion-label>Select Sport</ion-label>
    <ion-select type="text" name="pref" [(ngModel)]="pref" value="pref" (ionChange)="preference(pref)" placeholder="Select One">
      <ion-select-option value="Soccer">Soccer</ion-select-option>
      <ion-select-option value="Tennis">Tennis</ion-select-option>
      <ion-select-option value="Basketball">Basketball</ion-select-option>
      <ion-select-option value="All">Show All</ion-select-option>
    </ion-select>
  </ion-item>
</form>
</code>```

So depending on the value, it will display only that category:

```<code><ion-list *ngIf="itemsPage!=undefined">
<h6>Events Available</h6>
 <ion-card *ngFor="let evt of itemsPage" padding style="background: url('../../../assets/img/gameon-tennis-bg.jpg') no-repeat center center / cover;">
  <ion-row>
    <ion-col>
      <ion-card-subtitle>{{ evt.date | date:'dd/MM/yyyy' }}, at {{ evt.date | date:'h:mm a'}}</ion-card-subtitle>
      <ion-card-title>{{ evt.type }}</ion-card-title>
      <ion-card-subtitle>{{ evt.title }}</ion-card-subtitle>
      <ion-card-subtitle><ion-icon name="pin"></ion-icon>{{ evt.location }}</ion-card-subtitle>
      <ion-card-subtitle>Participants: <span class="numPart"> {{ evt.part.length }}</span> / <span class="numPlayers">{{ evt.players }}</span></ion-card-subtitle>
    </ion-col>
    <ion-col>
      <ion-button small expand="block" fill="outline" (click)="viewEvent(evt)">View Event</ion-button>
      <ion-button small expand="block" fill="outline" (click)="addMeToEvent(evt)">Join Event</ion-button>
    </ion-col>
  </ion-row>
 </ion-card>
</code>```

However, I also wanted to manipulate that list with an ion-slider (to work similarly to the ion-select, for example, if the user clicks on the "Soccer" slide, it will filter the list like it does if they click on the ion-select "Soccer"

```<code>  <ion-slides [options]="catSlideOptions">
    <ion-slide><img src="assets/img/cat-soccer.jpg"></ion-slide>
    <ion-slide><img src="assets/img/cat-basketball.jpg"></ion-slide>
    <ion-slide><img src="assets/img/cat-tennis.jpg"></ion-slide>
    <ion-slide><img src="assets/img/cat-gym.jpg"></ion-slide>
    <ion-slide><img src="assets/img/cat-running.jpg"></ion-slide>
  </ion-slides>
</code>```

I'm not sure how to accomplish this, so any ideas would be much appreciated!

Title: How to filter an array using ion-slides

Body:
I'm using an ion-select to do some dynamic filtering in an array:

<form #regForm="ngForm">
  <ion-item>
    <ion-label>Select Sport</ion-label>
    <ion-select type="text" name="pref" [(ngModel)]="pref" value="pref" (ionChange)="preference(pref)" placeholder="Select One">
      <ion-select-option value="Soccer">Soccer</ion-select-option>
      <ion-select-option value="Tennis">Tennis</ion-select-option>
      <ion-select-option value="Basketball">Basketball</ion-select-option>
      <ion-select-option value="All">Show All</ion-select-option>
    </ion-select>
  </ion-item>
</form>

So depending on the value, it will display only that category:

<ion-list *ngIf="itemsPage!=undefined">

Events Available

 <ion-card *ngFor="let evt of itemsPage" padding style="background: url('../../../assets/img/gameon-tennis-bg.jpg') no-repeat center center / cover;">
  <ion-row>
    <ion-col>
      <ion-card-subtitle>{{ evt.date | date:'dd/MM/yyyy' }}, at {{ evt.date | date:'h:mm a'}}</ion-card-subtitle>
      <ion-card-title>{{ evt.type }}</ion-card-title>
      <ion-card-subtitle>{{ evt.title }}</ion-card-subtitle>
      <ion-card-subtitle><ion-icon name="pin"></ion-icon>{{ evt.location }}</ion-card-subtitle>
      <ion-card-subtitle>Participants:  {{ evt.part.length }} / {{ evt.players }}</ion-card-subtitle>
    </ion-col>
    <ion-col>
      <ion-button small expand="block" fill="outline" (click)="viewEvent(evt)">View Event</ion-button>
      <ion-button small expand="block" fill="outline" (click)="addMeToEvent(evt)">Join Event</ion-button>
    </ion-col>
  </ion-row>
 </ion-card>

However, I also wanted to manipulate that list with an ion-slider (to work similarly to the ion-select, for example, if the user clicks on the "Soccer" slide, it will filter the list like it does if they click on the ion-select "Soccer"

  <ion-slides [options]="catSlideOptions">
    <ion-slide></ion-slide>
    <ion-slide></ion-slide>
    <ion-slide></ion-slide>
    <ion-slide></ion-slide>
    <ion-slide></ion-slide>
  </ion-slides>

I'm not sure how to accomplish this, so any ideas would be much appreciated!


问:
postcss-convert-px-to-vw Plugin doesn't work on REACT app
I've been using this plugin postcss-px-to-viewport-vite-plugin for years on Vuejs projects.
In summary it coverts all 'px' to 'vw' using Postcss. After runtime, on Chrome debug mode, you can  see tha all 'px' are translated to 'vw' correctly.  The only thing I must do to set the configuration up is install the Plugin and create postcsss config file.
I've been trying to set the same configuration on React, but no way!

After the app is up and running, I still see all px !

My postcss.config.js on vuejs project :

```<code>module.exports = {
  plugins: [
    {
      "postcss-px-to-viewport": {
        options: {
          unitToConvert: "px",
          viewportWidth: 1900,
          unitPrecision: 5,
          propList: ["*"],
          viewportUnit: "vw",
          fontViewportUnit: "vw",
          selectorBlackList: [],
          minPixelValue: 1,
          mediaQuery: false,
          replace: true,
          exclude: undefined,
          include: undefined,
          landscape: false,
          landscapeUnit: "vw",
          landscapeWidth: 568,
        },
      },
    },
  ],
};
</code>```

Body:
I've been using this plugin postcss-px-to-viewport-vite-plugin for years on Vuejs projects.
In summary it coverts all 'px' to 'vw' using Postcss. After runtime, on Chrome debug mode, you can  see tha all 'px' are translated to 'vw' correctly.  The only thing I must do to set the configuration up is install the Plugin and create postcsss config file.
I've been trying to set the same configuration on React, but no way!

After the app is up and running, I still see all px !

My postcss.config.js on vuejs project :

module.exports = {
  plugins: [
    {
      "postcss-px-to-viewport": {
        options: {
          unitToConvert: "px",
          viewportWidth: 1900,
          unitPrecision: 5,
          propList: ["*"],
          viewportUnit: "vw",
          fontViewportUnit: "vw",
          selectorBlackList: [],
          minPixelValue: 1,
          mediaQuery: false,
          replace: true,
          exclude: undefined,
          include: undefined,
          landscape: false,
          landscapeUnit: "vw",
          landscapeWidth: 568,
        },
      },
    },
  ],
};


问:
block is not expanding horizontally to the edges of the screen, css
I'm writing css for a practice website. I wanted the header section to be a block on the top of the screen that would stretch to the edges of the screen like this But instead my header looks like that.

My code in html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="header.css">
</head>
<body>
    <header>title</header>
</body>
</html>
</code>```

Code in css:

```<code>body {
    background-color: aliceblue;
}

header {
    background-color: aquamarine;
    display: block;
    text-align: center;
    padding: 10px;
}
</code>```

What should I do?

Body:
I'm writing css for a practice website. I wanted the header section to be a block on the top of the screen that would stretch to the edges of the screen like this But instead my header looks like that.

My code in html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="header.css">

    title

Code in css:

body {
    background-color: aliceblue;
}

header {
    background-color: aquamarine;
    display: block;
    text-align: center;
    padding: 10px;
}

What should I do?


问:
Graphql typescript mutation structure/input types seem to quickly get too cumbersome?
I have a simple, or what I had thought was simple, graphql api set up with mongoose for the DB everything using typescript. However, getting everything typed correctly has probably cost me 2x the time fixing any typing bugs would have caused. Also, I'm still unsure how to structure the mutations as checking nullable fields and setting parameters based off of them is still something I cant seem to figure out with typescript. Am I using input types correctly here? Also, how can you assign fields to update on a model only if they are not null?

Action + input type

```<code>type action {
        _id: ID!
        name: String!
        action: String!
        target: Int
        unit: String!
}

input create_action {
        user_id: ID!
        name: String!
        action: String!
        target: Int
        unit: String
}

type Mutation{
    create_action(input: create_action): action!
}
</code>```

Resolver

```<code>async create_action(_: any, {input: {user_id, name, action, target, unit}}:
            {input:{user_id: number, name: String, action: String, target: number, unit: String}}){

            const res = await action_serv.create_action({input: {user_id, name, action, target, unit}})
            return res
        }
</code>```

Service

```<code>
export class action_service {
    async create_action({input: {user_id, name, action, target, unit}}:
        {input:{user_id: number, name: String, action: String, target: number, unit: String}}){

        const new_action = new action_model({
        user_id: user_id,
        name: name,
        action: action,
        target: target,
        unit: unit
    })

    const res = await new_action.save()
    return res
    }
}
</code>```

It seems like a lot of repeated lines and with several mutations for every type im going to have most of which with more complicated fields than the action model the code seems super bloated this way. Also one other ts related problem is when I have an object which has been verified to not be unidentified, I still cant write something like

```<code>if(action_step !== null && action_step !== undefined){
                if(!action_id) action_id = action_step.action
</code>```

Am I missing something here or is this just typescript as intended with graphql, if so is it even worth it?

The error I keep getting is:
Type '{ prototype?: ObjectId | undefined; cacheHexString?: unknown; generate?: {} | undefined; createFromTime?: {} | undefined; createFromHexString?: {} | undefined; isValid?: {} | undefined; }' is not assignable to type 'ObjectId'.

when trying to extract the action_id field from the object returned by Model.findOne(). How am I supposed to get a usable object from mongoose while also using typescript? Can really find anything on it

Body:
I have a simple, or what I had thought was simple, graphql api set up with mongoose for the DB everything using typescript. However, getting everything typed correctly has probably cost me 2x the time fixing any typing bugs would have caused. Also, I'm still unsure how to structure the mutations as checking nullable fields and setting parameters based off of them is still something I cant seem to figure out with typescript. Am I using input types correctly here? Also, how can you assign fields to update on a model only if they are not null?

Action + input type

type action {
        _id: ID!
        name: String!
        action: String!
        target: Int
        unit: String!
}

input create_action {
        user_id: ID!
        name: String!
        action: String!
        target: Int
        unit: String
}

type Mutation{
    create_action(input: create_action): action!
}

Resolver

async create_action(_: any, {input: {user_id, name, action, target, unit}}:
            {input:{user_id: number, name: String, action: String, target: number, unit: String}}){

            const res = await action_serv.create_action({input: {user_id, name, action, target, unit}})
            return res
        }

Service

export class action_service {
    async create_action({input: {user_id, name, action, target, unit}}:
        {input:{user_id: number, name: String, action: String, target: number, unit: String}}){

        const new_action = new action_model({
        user_id: user_id,
        name: name,
        action: action,
        target: target,
        unit: unit
    })

    const res = await new_action.save()
    return res
    }
}

It seems like a lot of repeated lines and with several mutations for every type im going to have most of which with more complicated fields than the action model the code seems super bloated this way. Also one other ts related problem is when I have an object which has been verified to not be unidentified, I still cant write something like

if(action_step !== null && action_step !== undefined){
                if(!action_id) action_id = action_step.action

Am I missing something here or is this just typescript as intended with graphql, if so is it even worth it?

The error I keep getting is:
Type '{ prototype?: ObjectId | undefined; cacheHexString?: unknown; generate?: {} | undefined; createFromTime?: {} | undefined; createFromHexString?: {} | undefined; isValid?: {} | undefined; }' is not assignable to type 'ObjectId'.

when trying to extract the action_id field from the object returned by Model.findOne(). How am I supposed to get a usable object from mongoose while also using typescript? Can really find anything on it


问:
Is there a way to return a readablestream as a response in sveltekit
In my app (downloads user generated sounds from youtube and plays them) I'm using ytdl to download the sounds to the client and play them. i am unable to return the readablestream from ytdl as a response.

this is my current code

    const readstream = await (await youtube(id)).read()
    console.log(readstream) // logs null
    return readstream
```
<p><code>youtube</code> function</p>
<pre class="lang-js prettyprint-override"><code>import { downloadFromInfo, getInfo, validateID } from 'ytdl-core'

async function youtube(url: string) {
    if(!validateID(id)) throw new Error("URL not valid")
    return downloadFromInfo(await getInfo(`https://youtu.be/${id}`))
}
</code>```

but i get this error:

```<code>Invalid response from route /api/source/yt/[redacted].mp3: handler should return a Response object
Error: Invalid response from route /api/source/yt/[redacted].mp3: handler should return a Response object
    at render_endpoint ([redacted]/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js:47:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async resolve ([redacted]/node_modules/@sveltejs/kit/src/runtime/server/index.js:354:17)
    at async respond ([redacted]/node_modules/@sveltejs/kit/src/runtime/server/index.js:229:20)
    at async [redacted]/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:444:22
</code>```

Body:
In my app (downloads user generated sounds from youtube and plays them) I'm using ytdl to download the sounds to the client and play them. i am unable to return the readablestream from ytdl as a response.

this is my current code

    const readstream = await (await youtube(id)).read()
    console.log(readstream) // logs null
    return readstream

youtube function

import { downloadFromInfo, getInfo, validateID } from 'ytdl-core'

async function youtube(url: string) {
    if(!validateID(id)) throw new Error("URL not valid")
    return downloadFromInfo(await getInfo(`https://youtu.be/${id}`))
}

but i get this error:

Invalid response from route /api/source/yt/[redacted].mp3: handler should return a Response object
Error: Invalid response from route /api/source/yt/[redacted].mp3: handler should return a Response object
    at render_endpoint ([redacted]/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js:47:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async resolve ([redacted]/node_modules/@sveltejs/kit/src/runtime/server/index.js:354:17)
    at async respond ([redacted]/node_modules/@sveltejs/kit/src/runtime/server/index.js:229:20)
    at async [redacted]/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:444:22


问:
How can I create a circle filled with an image in pygame?
Here's the context:

I want to code a corona runner, basically a chrome dino imitation in pygame.

For that I want the player to have a circular hitbox.

The image I'm using is square-shaped, but has a transparent background.

So there are 2 possible solutions, that I don't know how to code though:

Create a circle, fill the circle with the image, remove the transparent background

Create a square, remove the transparent background and make only the non-transparent part of the image be able to collide.

Besides not knowing how to code any of these three, I have the problem that every time I insert the image with the transparent background, the transparent background turns black instead of non-visible.

I tried to add the image and hoped, that the transparent background would disappear automatically, which it didn't.

I tried to turn any of the 2 possible solutions mentioned above into code, but I didn't know how to.


问:
When using MEF 2 System.Composition, can you specify a class without annotating it?
Using System.Composition, I can successfully import parts using .WithAssembly and .WithPart to specify classes individually.   However, these classes still require them to be annotated with [Export] attribute, etc., as usual.

If I want to import a class that's in a third-party library, and it's not annotated with MEF attributes, then I can instantiate the part manually and use the new .WithExport method introduced in MEF 7.  In this way the class doesn't have to be annotated.   But what if I want to treat the class as if it had the [ImportingConstructor] attribute without it being present.  That would be very convenient.

What I'm looking for is a way to communicate all the information MEF needs about a part without actually modifying the part, i.e. imports and exports.

Does anyone know of a way to get MEF to do that?

Also there seems to be very little information about the new features in MEF 7, including on their github site.  There's almost no info on the .WithExport method, any discussions around it, what things were considered, etc.

So any info about that would also be helpful.