问:
How to validate schema at object level in mongoose?
I want to validate an object in mongoose schema, i.e here is my schema -

```<code>logs = new Schema({
    user_id: String,
    reminder_cat: String,
    activityNote: String,
    sent_email: Number,
    added_date: Date
})
</code>```

I want to validate if reminder_cat === "Renewal" then sent_email should not be more than 2 how do I achieve this at schema level. I understand there are validate function at attribute level which can be custom or provided from mongoose. But that doesn't contain the whole object so validating a dependent field is not possible. Any help or pointer will be appreciated.

Body:
I want to validate an object in mongoose schema, i.e here is my schema -

logs = new Schema({
    user_id: String,
    reminder_cat: String,
    activityNote: String,
    sent_email: Number,
    added_date: Date
})

I want to validate if reminder_cat === "Renewal" then sent_email should not be more than 2 how do I achieve this at schema level. I understand there are validate function at attribute level which can be custom or provided from mongoose. But that doesn't contain the whole object so validating a dependent field is not possible. Any help or pointer will be appreciated.


来源: stackexchange

问:
MongoDB error trying to 'docker build' my Spring Boot application
Model:

```<code>@Document("users")
public class User {
...
}
</code>```

Repository:

```<code>public interface UserRepository extends CrudRepository<User, ObjectId> {
}
</code>```

Controller:

```<code>@RestController
public class UserController {

    @Autowired
    UserRepository repository;

    ...

}
</code>```

When I run my application from IDE with the following application.properties:

```<code>spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=...
spring.data.mongodb.password=...
spring.data.mongodb.database=mydb
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
</code>```

everything works.

However, my goal is to deploy my app and MongoDB with Docker/Kubernetes, so I use the following application.properties:

```<code>spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=${MONGO_INITDB_ROOT_USERNAME}
spring.data.mongodb.password=${MONGO_INITDB_ROOT_PASSWORD}
spring.data.mongodb.database=${MONGO_INITDB_DATABASE}
spring.data.mongodb.port=27017
spring.data.mongodb.host=${MONGODB_HOSTNAME}
</code>```

where the variables starting with $ are the values that I set in Kubernetes YAML files.
But when I call docker build -t user-service:v1 ./user-service I get many errors.
Before MongoDB integration in my app, the docker build command worked.

These are the errors I got after docker build command:

```<code>2022-12-17T13:11:00.018Z  WARN 72 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'userRepository' defined in com.ecommerceapp.userservice.repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'
2022-12-17T13:11:00.034Z  INFO 72 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger :

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2022-12-17T13:11:00.058Z ERROR 72 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'userRepository' defined in com.ecommerceapp.userservice.repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:712) ~[spring-beans-6.0.2.jar:6.0.2]

    ...

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.ecommerceapp.userservice.repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:377) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:135) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1663) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1412) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1405) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:709) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 92 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception with message: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:793) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:543) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1161) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:365) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 105 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception with message: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:652) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:640) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1161) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1405) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:880) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:784) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 115 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception with message: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:648) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 129 common frames omitted
Caused by: java.lang.IllegalArgumentException: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.util.Assert.isTrue(Assert.java:122) ~[spring-core-6.0.2.jar:6.0.2]
    at org.springframework.data.mongodb.core.MongoDatabaseFactorySupport.<init>(MongoDatabaseFactorySupport.java:69) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
    at org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory.<init>(SimpleMongoClientDatabaseFactory.java:75) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
    at org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory.<init>(SimpleMongoClientDatabaseFactory.java:64) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
    at org.springframework.boot.autoconfigure.data.mongo.MongoDatabaseFactoryConfiguration.mongoDatabaseFactory(MongoDatabaseFactoryConfiguration.java:43) ~[spring-boot-autoconfigure-3.0.0.jar:3.0.0]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 130 common frames omitted
</code>```

YAML files:

service-db-configmap

```<code>apiVersion: v1
data:
  MONGO_INITDB_DATABASE: admin
kind: ConfigMap
metadata:
  name: user-service-db-env-file
</code>```

service-db-secret-file

```<code>apiVersion: v1
stringData:
  MONGO_INITDB_ROOT_USERNAME: pippo
  MONGO_INITDB_ROOT_PASSWORD: palla
kind: Secret
metadata:
  name: db-secret-file
type: Opaque
</code>```

db-service

```<code>apiVersion: v1
kind: Service
metadata:
  name: user-service-db
spec:
  ports:
    - port: 27017
  selector:
    app: user-service-db
</code>```

db-deployment

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service-db
spec:
  selector:
    matchLabels:
      app: user-service-db
  template:
    metadata:
      labels:
        app: user-service-db
    spec:
      containers:
        - name: user-service-db
          image: mongo:latest
          ports:
            - containerPort: 27017
          envFrom:
            - configMapRef:
                name: user-service-db-env-file
            - secretRef:
                name: db-secret-file
          volumeMounts:
            - mountPath: /data/db
              name: user-service-db-volume
      volumes:
        - name: user-service-db-volume
          hostPath:
            path: /user-service-db-volume
            type: DirectoryOrCreate
</code>```

service-configmap

```<code>apiVersion: v1
data:
  MONGODB_HOSTNAME: user-service-db
  MONGODB_PORT: "27017"
kind: ConfigMap
metadata:
  name: user-service-env-file
</code>```

service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: user-service
spec:
  ports:
    - port: 8080
  selector:
    app: user-service
</code>```

deployment:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service
spec:
  selector:
    matchLabels:
      app: user-service
  template:
    metadata:
      labels:
        app: user-service
      annotations:
    spec:
      containers:
        - name: user-service
          image: user-service:v1
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: user-service-db-env-file
            - configMapRef:
                name: user-service-env-file
            - secretRef:
                name: db-secret-file
</code>```

ingress:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
    nginx.ingress.kubernetes.io/cors-allow-headers: "Content-Type"
    nginx.ingress.kubernetes.io/rewrite-target: "/$2"
spec:
  rules:
  - host: airline-management-system.app.loc
    http:
      paths:
      - path: /users(/|$)(.*)
        pathType: ImplementationSpecific
        backend:
          service:
            name: user-service
            port:
              number: 8080
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Model:

@Document("users")
public class User {
...
}

Repository:

public interface UserRepository extends CrudRepository<User, ObjectId> {
}

Controller:

@RestController
public class UserController {

    @Autowired
    UserRepository repository;

    ...

}

When I run my application from IDE with the following application.properties:

spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=...
spring.data.mongodb.password=...
spring.data.mongodb.database=mydb
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

everything works.

However, my goal is to deploy my app and MongoDB with Docker/Kubernetes, so I use the following application.properties:

spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=${MONGO_INITDB_ROOT_USERNAME}
spring.data.mongodb.password=${MONGO_INITDB_ROOT_PASSWORD}
spring.data.mongodb.database=${MONGO_INITDB_DATABASE}
spring.data.mongodb.port=27017
spring.data.mongodb.host=${MONGODB_HOSTNAME}

where the variables starting with $ are the values that I set in Kubernetes YAML files.
But when I call docker build -t user-service:v1 ./user-service I get many errors.
Before MongoDB integration in my app, the docker build command worked.

These are the errors I got after docker build command:

2022-12-17T13:11:00.018Z  WARN 72 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'userRepository' defined in com.ecommerceapp.userservice.repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'
2022-12-17T13:11:00.034Z  INFO 72 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger :

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2022-12-17T13:11:00.058Z ERROR 72 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'userRepository' defined in com.ecommerceapp.userservice.repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:712) ~[spring-beans-6.0.2.jar:6.0.2]

    ...

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.ecommerceapp.userservice.repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:377) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:135) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1663) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1412) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1405) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:709) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 92 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception with message: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:793) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:543) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1161) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:365) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 105 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception with message: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:652) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:640) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1161) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1405) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:880) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:784) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 115 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception with message: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.0.2.jar:6.0.2]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:648) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 129 common frames omitted
Caused by: java.lang.IllegalArgumentException: Database name must not contain slashes, dots, spaces, quotes, or dollar signs
    at org.springframework.util.Assert.isTrue(Assert.java:122) ~[spring-core-6.0.2.jar:6.0.2]
    at org.springframework.data.mongodb.core.MongoDatabaseFactorySupport.<init>(MongoDatabaseFactorySupport.java:69) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
    at org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory.<init>(SimpleMongoClientDatabaseFactory.java:75) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
    at org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory.<init>(SimpleMongoClientDatabaseFactory.java:64) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
    at org.springframework.boot.autoconfigure.data.mongo.MongoDatabaseFactoryConfiguration.mongoDatabaseFactory(MongoDatabaseFactoryConfiguration.java:43) ~[spring-boot-autoconfigure-3.0.0.jar:3.0.0]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139) ~[spring-beans-6.0.2.jar:6.0.2]
    ... 130 common frames omitted

YAML files:

service-db-configmap

apiVersion: v1
data:
  MONGO_INITDB_DATABASE: admin
kind: ConfigMap
metadata:
  name: user-service-db-env-file

service-db-secret-file

apiVersion: v1
stringData:
  MONGO_INITDB_ROOT_USERNAME: pippo
  MONGO_INITDB_ROOT_PASSWORD: palla
kind: Secret
metadata:
  name: db-secret-file
type: Opaque

db-service

apiVersion: v1
kind: Service
metadata:
  name: user-service-db
spec:
  ports:
    - port: 27017
  selector:
    app: user-service-db

db-deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service-db
spec:
  selector:
    matchLabels:
      app: user-service-db
  template:
    metadata:
      labels:
        app: user-service-db
    spec:
      containers:
        - name: user-service-db
          image: mongo:latest
          ports:
            - containerPort: 27017
          envFrom:
            - configMapRef:
                name: user-service-db-env-file
            - secretRef:
                name: db-secret-file
          volumeMounts:
            - mountPath: /data/db
              name: user-service-db-volume
      volumes:
        - name: user-service-db-volume
          hostPath:
            path: /user-service-db-volume
            type: DirectoryOrCreate

service-configmap

apiVersion: v1
data:
  MONGODB_HOSTNAME: user-service-db
  MONGODB_PORT: "27017"
kind: ConfigMap
metadata:
  name: user-service-env-file

service:

apiVersion: v1
kind: Service
metadata:
  name: user-service
spec:
  ports:
    - port: 8080
  selector:
    app: user-service

deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service
spec:
  selector:
    matchLabels:
      app: user-service
  template:
    metadata:
      labels:
        app: user-service
      annotations:
    spec:
      containers:
        - name: user-service
          image: user-service:v1
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: user-service-db-env-file
            - configMapRef:
                name: user-service-env-file
            - secretRef:
                name: db-secret-file

ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
    nginx.ingress.kubernetes.io/cors-allow-headers: "Content-Type"
    nginx.ingress.kubernetes.io/rewrite-target: "/$2"
spec:
  rules:
  - host: airline-management-system.app.loc
    http:
      paths:
      - path: /users(/|$)(.*)
        pathType: ImplementationSpecific
        backend:
          service:
            name: user-service
            port:
              number: 8080


问:
Mongoose Schema properties validation with Typescript NextJS
i am trying to save new document to mongo db, the Schema validation is not working for me, i am trying ti make required true, but i still can add new document without the required field.

this is my schema:

```<code>// lib/models/test.model.ts
import { Model, Schema } from 'mongoose';
import createModel from '../createModel';

interface ITest {
  first_name: string;
  last_name: string;
}

type TestModel = Model<ITest, {}>;

const testSchema = new Schema<ITest, TestModel>({
  first_name: {
    type: String,
    required: [true, 'Required first name'],
  },
  last_name: {
    type: String,
    required: true,
  },
});

const Test = createModel<ITest, TestModel>('tests', testSchema);
module.exports = Test;

</code>```

this is createModel:

```<code>// lib/createModel.ts
import { Model, model, Schema } from 'mongoose';

// Simple Generic Function for reusability
// Feel free to modify however you like
export default function createModel<T, TModel = Model<T>>(
  modelName: string,
  schema: Schema<T>
): TModel {
  let createdModel: TModel;
  if (process.env.NODE_ENV === 'development') {
    // In development mode, use a global variable so that the value
    // is preserved across module reloads caused by HMR (Hot Module Replacement).
    // @ts-ignore
    if (!global[modelName]) {
      createdModel = model<T, TModel>(modelName, schema);
      // @ts-ignore
      global[modelName] = createdModel;
    }
    // @ts-ignore
    createdModel = global[modelName];
  } else {
    // In production mode, it's best to not use a global variable.
    createdModel = model<T, TModel>(modelName, schema);
  }
  return createdModel;
}

</code>```

and this is my tests file:

```<code>import { connection } from 'mongoose';
import type { NextApiRequest, NextApiResponse } from 'next';
const Test = require('../../../lib/models/test.model');
import { connect } from '../../../lib/dbConnect';
const ObjectId = require('mongodb').ObjectId;

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  switch (req.method) {

    case 'POST': {
      return addPost(req, res);
    }
  }
}
async function addPost(req: NextApiRequest, res: NextApiResponse) {
  try {
    connect();

    // const { first_name, last_name } = req.body;
    const test = new Test({
      first_name: req.body.first_name,
      last_name: req.body.last_name,
    });
    let post = await test.save();
    // return the posts
    return res.json({
      message: JSON.parse(JSON.stringify(post)),
      success: true,
    });

    // Erase test data after use
    //connection.db.dropCollection(testModel.collection.collectionName);
  } catch (err) {
    //res.status(400).json(err);
    res.status(400).json({
      message: err,
      success: false,
    });
  }
}

</code>```

in the Postman, i send a request body without the required field (first_name) and i still can add it.

any help?

Body:
i am trying to save new document to mongo db, the Schema validation is not working for me, i am trying ti make required true, but i still can add new document without the required field.

this is my schema:

// lib/models/test.model.ts
import { Model, Schema } from 'mongoose';
import createModel from '../createModel';

interface ITest {
  first_name: string;
  last_name: string;
}

type TestModel = Model<ITest, {}>;

const testSchema = new Schema<ITest, TestModel>({
  first_name: {
    type: String,
    required: [true, 'Required first name'],
  },
  last_name: {
    type: String,
    required: true,
  },
});

const Test = createModel<ITest, TestModel>('tests', testSchema);
module.exports = Test;

this is createModel:

// lib/createModel.ts
import { Model, model, Schema } from 'mongoose';

// Simple Generic Function for reusability
// Feel free to modify however you like
export default function createModel<T, TModel = Model<T>>(
  modelName: string,
  schema: Schema<T>
): TModel {
  let createdModel: TModel;
  if (process.env.NODE_ENV === 'development') {
    // In development mode, use a global variable so that the value
    // is preserved across module reloads caused by HMR (Hot Module Replacement).
    // @ts-ignore
    if (!global[modelName]) {
      createdModel = model<T, TModel>(modelName, schema);
      // @ts-ignore
      global[modelName] = createdModel;
    }
    // @ts-ignore
    createdModel = global[modelName];
  } else {
    // In production mode, it's best to not use a global variable.
    createdModel = model<T, TModel>(modelName, schema);
  }
  return createdModel;
}

and this is my tests file:

import { connection } from 'mongoose';
import type { NextApiRequest, NextApiResponse } from 'next';
const Test = require('../../../lib/models/test.model');
import { connect } from '../../../lib/dbConnect';
const ObjectId = require('mongodb').ObjectId;

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  switch (req.method) {

    case 'POST': {
      return addPost(req, res);
    }
  }
}
async function addPost(req: NextApiRequest, res: NextApiResponse) {
  try {
    connect();

    // const { first_name, last_name } = req.body;
    const test = new Test({
      first_name: req.body.first_name,
      last_name: req.body.last_name,
    });
    let post = await test.save();
    // return the posts
    return res.json({
      message: JSON.parse(JSON.stringify(post)),
      success: true,
    });

    // Erase test data after use
    //connection.db.dropCollection(testModel.collection.collectionName);
  } catch (err) {
    //res.status(400).json(err);
    res.status(400).json({
      message: err,
      success: false,
    });
  }
}

in the Postman, i send a request body without the required field (first_name) and i still can add it.

any help?


问:
Thread detach : memory leak or any associated problems
I'm developing a software in C++ to communicate over MQTT. I'm using paho-mqtt.
If I am using synchronous client I am creating a separate thread in which I publish messages, so not to block my primary thread.

```<code>std::thread(&MqttClient::transmit_message, this).detach(); //Call in a separate thread.

void MqttClient::transmit_message(void)
{
    try
    {
        std::string data;
        {
            std::lock_guard<std::mutex> lock{ this->transmit_queue_mutex };
            if (this->transmit_queue.empty())
                return;
            data = this->transmit_queue.front();
        }
        mqtt::message_ptr msg = mqtt::make_message(this->topic_out, data.data(), data.length(), MqttClient::qos, false);
        this->transmit_in_progress.store(true);
        this->client->publish(msg);
    }
    catch (const std::exception& ex)
    {
        LOG_ERROR << ex.what();
    }
}
</code>```

I wish to know will this cause memory leaks or any problems or this is regarded as bad practice.

Body:
I'm developing a software in C++ to communicate over MQTT. I'm using paho-mqtt.
If I am using synchronous client I am creating a separate thread in which I publish messages, so not to block my primary thread.

std::thread(&MqttClient::transmit_message, this).detach(); //Call in a separate thread.

void MqttClient::transmit_message(void)
{
    try
    {
        std::string data;
        {
            std::lock_guard<std::mutex> lock{ this->transmit_queue_mutex };
            if (this->transmit_queue.empty())
                return;
            data = this->transmit_queue.front();
        }
        mqtt::message_ptr msg = mqtt::make_message(this->topic_out, data.data(), data.length(), MqttClient::qos, false);
        this->transmit_in_progress.store(true);
        this->client->publish(msg);
    }
    catch (const std::exception& ex)
    {
        LOG_ERROR << ex.what();
    }
}

I wish to know will this cause memory leaks or any problems or this is regarded as bad practice.


问:
How can I solve my error problem when compiling the program?
I'm trying to write a car register with different function, in different files, lib.c, lib.h and main.c.  However when I try to compile the program it shows this error with my car "unknown type name ‘Car’
34 | void addCar(Car* car)":

In my 'lib.c' file, this is my progress so far:

```<code>#include "lib.h"

void printMeny() {

 //meny
printf("Meny\n");
printf("1. Lägg till ett fordon\n");
printf("2. Ta bort ett fordon\n");
printf("3. Sortera efter bilmärka\n");
printf("4. Information om ett fordon\n");
printf("5. Skriv ut hela registret\n");
printf("0. Avsluta programmet\n");
}

int getNumber()  {
char buffer[10] = {0};
int number = 0;
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer, "%d", &number);

  return number;
}

void getString(char* buf, size_t len) {

if(fgets(buf,len,stdin)) {
    char* p;
    if((p = strchr(buf, '\n')) != NULL)
    {
        *p = '\0';
    }
 }
 }
 void addCar(Car* car) {

printf("Namn:\n");
getString(car->owner.name, sizeof(car->owner.name));

printf("Ålder:\n");
car->owner.age = getNumber();

printf("Märke:\n");
getString(car->car_brand, sizeof(car->car_brand));

printf("Modell:\n");
getString(car->car_model, sizeof(car->car_model));

printf("Registreringsnummer:\n");
getString(car->plate_num, sizeof(car->plate_num));
}
</code>```

Then in my lib.h:

```<code> //#pragma once
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

  #define CAR_MAX 10

   typedef struct {
   char name[40];
   int age;

   } Person;

   typedef struct {
   Person owner;
   char car_brand[20];
   char car_model[20];
   char plate_num[20];
   } Car;

      void printMeny();
     int getNumber();
    void addCar(Car* car);
    void getString(char* buffer, size_t len);
</code>```

And finally in main.c;

```<code> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib.h"
int main() {
int val = 0;
Car cars[CAR_MAX] = {0};
int numberOfCars = 0;

printMeny();
val = getNumber();

switch(val) {
    case 0:
        break;
    case 1:
    addCar(&cars[numberOfCars]);
        numberOfCars++;
</code>```

Body:
I'm trying to write a car register with different function, in different files, lib.c, lib.h and main.c.  However when I try to compile the program it shows this error with my car "unknown type name ‘Car’
34 | void addCar(Car* car)":

In my 'lib.c' file, this is my progress so far:

#include "lib.h"

void printMeny() {

 //meny
printf("Meny\n");
printf("1. Lägg till ett fordon\n");
printf("2. Ta bort ett fordon\n");
printf("3. Sortera efter bilmärka\n");
printf("4. Information om ett fordon\n");
printf("5. Skriv ut hela registret\n");
printf("0. Avsluta programmet\n");
}

int getNumber()  {
char buffer[10] = {0};
int number = 0;
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer, "%d", &number);

  return number;
}

void getString(char* buf, size_t len) {

if(fgets(buf,len,stdin)) {
    char* p;
    if((p = strchr(buf, '\n')) != NULL)
    {
        *p = '\0';
    }
 }
 }
 void addCar(Car* car) {

printf("Namn:\n");
getString(car->owner.name, sizeof(car->owner.name));

printf("Ålder:\n");
car->owner.age = getNumber();

printf("Märke:\n");
getString(car->car_brand, sizeof(car->car_brand));

printf("Modell:\n");
getString(car->car_model, sizeof(car->car_model));

printf("Registreringsnummer:\n");
getString(car->plate_num, sizeof(car->plate_num));
}

Then in my lib.h:

 //#pragma once
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

  #define CAR_MAX 10

   typedef struct {
   char name[40];
   int age;

   } Person;

   typedef struct {
   Person owner;
   char car_brand[20];
   char car_model[20];
   char plate_num[20];
   } Car;

      void printMeny();
     int getNumber();
    void addCar(Car* car);
    void getString(char* buffer, size_t len);

And finally in main.c;

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib.h"
int main() {
int val = 0;
Car cars[CAR_MAX] = {0};
int numberOfCars = 0;

printMeny();
val = getNumber();

switch(val) {
    case 0:
        break;
    case 1:
    addCar(&cars[numberOfCars]);
        numberOfCars++;


问:
How to overflow some child elements out of a overflow scroll parent
I have a scrollabe parent inside which many child elements . I need to make some of them to make visible out of it's parent which property is overflow:scroll;

 ....

It's not exact which child to overflow out of the parent container .

I have tried to wrap some of the children into another container and make them positioned based on the position in the original parent container .


问:
How do I send a socket username and a socket message then sending it to discord using webhooks
I've been trying to send username and message data to a discord webhook but have been getting back this

```<code><main.ChatServer object at 0x00000245274EB760>: <socket.socket fd=1068, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10319), raddr=('127.0.0.1', 51363)>.
</code>```

Here is the code:

#imports
import socket
import threading
from discord_webhook import DiscordWebhook

class ChatServer:

    clients_list = []

    last_received_message = ""

    def __init__(self):
        self.server_socket = None
        self.create_listening_server()
    #listen for incoming connection
    def create_listening_server(self):

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create a socket using TCP port and ipv4
        local_ip = '127.0.0.1'
        local_port = 10319
        # this will allow you to immediately restart a TCP server
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # this makes the server listen to requests coming from other computers on the network
        self.server_socket.bind((local_ip, local_port))
        print("Listening for incoming messages..")
        self.server_socket.listen(5) #listen for incoming connections / max 5 clients
        self.receive_messages_in_a_new_thread()
    #fun to receive new msgs
    def receive_messages(self, so):
        while True:
            incoming_buffer = so.recv(256) #initialize the buffer
            if not incoming_buffer:
                break
            self.last_received_message = incoming_buffer.decode('utf-8')
            self.broadcast_to_all_clients(so)  # send to all clients
            webhook = DiscordWebhook(url='https://discord.com/api/webhooks/1053657076607496192/DXuj0B7fcJwe8nGEQwkxOqFxObB_hTdSfjzct3WoyPX94OFjJ91dM-2f6M93EshcYgn2', content={
  "username": f"{self}",
  "content": f"{so}"
})
            response = webhook.execute()
        so.close()
    #broadcast the message to all clients
    def broadcast_to_all_clients(self, senders_socket):
        for client in self.clients_list:
            socket, (ip, port) = client
            if socket is not senders_socket:
                socket.sendall(self.last_received_message.encode('utf-8'))

    def receive_messages_in_a_new_thread(self):
        while True:
            client = so, (ip, port) = self.server_socket.accept()
            self.add_to_clients_list(client)
            print('Connected to ', ip, ':', str(port))
            t = threading.Thread(target=self.receive_messages, args=(so,))
            t.start()
    #add a new client
    def add_to_clients_list(self, client):
        if client not in self.clients_list:
            self.clients_list.append(client)

if __name__ == "__main__":
    ChatServer()
```

Body:
I've been trying to send username and message data to a discord webhook but have been getting back this

: <socket.socket fd=1068, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10319), raddr=('127.0.0.1', 51363)>.

Here is the code:

#imports
import socket
import threading
from discord_webhook import DiscordWebhook

class ChatServer:

    clients_list = []

    last_received_message = ""

    def __init__(self):
        self.server_socket = None
        self.create_listening_server()
    #listen for incoming connection
    def create_listening_server(self):

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create a socket using TCP port and ipv4
        local_ip = '127.0.0.1'
        local_port = 10319
        # this will allow you to immediately restart a TCP server
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # this makes the server listen to requests coming from other computers on the network
        self.server_socket.bind((local_ip, local_port))
        print("Listening for incoming messages..")
        self.server_socket.listen(5) #listen for incoming connections / max 5 clients
        self.receive_messages_in_a_new_thread()
    #fun to receive new msgs
    def receive_messages(self, so):
        while True:
            incoming_buffer = so.recv(256) #initialize the buffer
            if not incoming_buffer:
                break
            self.last_received_message = incoming_buffer.decode('utf-8')
            self.broadcast_to_all_clients(so)  # send to all clients
            webhook = DiscordWebhook(url='https://discord.com/api/webhooks/1053657076607496192/DXuj0B7fcJwe8nGEQwkxOqFxObB_hTdSfjzct3WoyPX94OFjJ91dM-2f6M93EshcYgn2', content={
  "username": f"{self}",
  "content": f"{so}"
})
            response = webhook.execute()
        so.close()
    #broadcast the message to all clients
    def broadcast_to_all_clients(self, senders_socket):
        for client in self.clients_list:
            socket, (ip, port) = client
            if socket is not senders_socket:
                socket.sendall(self.last_received_message.encode('utf-8'))

    def receive_messages_in_a_new_thread(self):
        while True:
            client = so, (ip, port) = self.server_socket.accept()
            self.add_to_clients_list(client)
            print('Connected to ', ip, ':', str(port))
            t = threading.Thread(target=self.receive_messages, args=(so,))
            t.start()
    #add a new client
    def add_to_clients_list(self, client):
        if client not in self.clients_list:
            self.clients_list.append(client)

if __name__ == "__main__":
    ChatServer()


问:
Making a stopwatch ( user input change size style ) using assembly 8086
error on word byte hour  [org 0x0100]

I am working on a project in assembly.(stopwatch user input change style and size ) I am working in   (in 16 bit assembly in emu8086).
I have been working on this for a long time and could not find the problem in my code.
What I am doing is simply creating stopwatch which shows  time when user  enter input its  change  style and style  of  userInput

I have been trying for a long time to solve it but I can't find my mistake. If someone can find my mistake please let me know.
Thank you very much.

jmp start

h
;Orignal Time
hrs:    dw 0 ;WORD Byte
min:    dw 0
s:      dw 0
ms:     dw 0

;Lap Time
lhrs:   dw 0
lmin:   dw 0
ls:     dw 0
lms:    dw 0

oldkb:  dd 0 ; declare double word dd ;For the purpose of saving the old keyboard ISR

;Flags for Modes
sMode:  db 0
lMode:  db 0

;Flags for other functions
startTimer:  db 0
snapshot:    db 0
lapTime:     db 0

location:   db 6

;------------------------------------------------------------------------------------------------------------------

;Clear Screen Sub Routine

clrscr:     pusha
push es

```<code>        mov ax, 0xb800
        mov es, ax
        xor di, di
        mov ax, 0x720
        mov cx, 2000

        cld
        rep stosw

        pop es
        popa
        ret
</code>```

;-------------------------------------------------------------------------------------------------------------------

;Print the Main Layout

printLayout:    pusha   ; push all 32 oprend size
push es

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```

;-------------------------------------------------------------------------------------------------------------------

;-------------------------------------------------------------------------------------------------------------------

;Keyboard ISR

kbisr:          push ax

```<code>            in  al, 0x60

            ;Checking release code only

            cmp al, 147         ;checking for 'R'
            jz  reset
            jnz modChanger
</code>```

reset:          ;Resetting the orginal time

```<code>            mov word [cs:hrs], 0
            mov word [cs:min], 0
            mov word [cs:s]   ,0
            mov word [cs:ms], 0

            ;Resetting the lap time

            mov word [cs:lhrs], 0
            mov word [cs:lmin], 0
            mov word [cs:ls], 0
            mov word [cs:lms], 0

            call clrscr

            mov byte [cs:location], 6

            jmp EOI1
</code>```

modChanger:     cmp al, 170                     ;Release code of Shift Left
jnz checkLMode1

```<code>            mov byte [cs:lMode], 0          ;Disable the lap mode

            cmp byte [cs:sMode], 1          ;If sMode was already enabled then do nothing
            jz EOI1

            mov byte [cs:sMode], 1          ;Else enable the sMode
            jmp EOI1
</code>```

checkLMode1:    cmp al, 182                     ;Release code of Shift Right
jnz startTime

```<code>            mov byte [cs:sMode], 0          ;Disable the split Mode

            cmp byte [cs:lMode], 1          ;If lMode was aleady enabled then do nothing
            jz  EOI1

            mov byte [cs:lMode], 1          ;Else enable the lMode
            jmp EOI1
</code>```

;Scenarios when space key is released

startTime:      cmp al, 185
jnz oldKbHandler

```<code>            cmp byte [cs:startTimer], 1     ;If Timer is already started then do nothing
            jz  check0

            mov byte [cs:startTimer], 1     ;Else start the timer
</code>```

check0:         cmp byte [cs:sMode], 1            ;If split mode is enabled
jnz  check1

```<code>            mov byte [cs:snapshot], 1
            jmp EOI1
</code>```

check1:         cmp byte [cs:lMode], 1        ;Else if the lap mode is enabled
jnz EOI1

```<code>            mov byte [cs:lapTime], 1
            jmp EOI1
</code>```

EOI1:           mov al,0x20                     ;End of Interrupt Signal
out 0x20,al

```<code>            pop ax
            iret
</code>```

;Rest of the Keyboard keys are handled by the old keyboard ISR
oldKbHandler:   pop ax
jmp far [cs:oldkb]

;-------------------------------------------------------------------------------------------------------------------

;-------------------------------------------------------------------------------------------------------------------

;To print the number on screen

printstr:   push bp
mov bp, sp
pusha

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```0

nextdigit:  mov dx, 0
div bx
add dl, 0x30
push dx
inc cx
cmp ax, 0
jnz nextdigit

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```1

nextpos:    pop dx
mov dh, 0x07
mov [es:di], dx
add di, 2
loop nextpos

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```2

;-------------------------------------------------------------------------------------------------------------------

;Function which prints the time on screen

printTime:  push bp
mov bp,sp
pusha

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```3

;-------------------------------------------------------------------------------------------------------------------

;Shift Left for Split Mode
;Shift Right for Lap Mode

stopWatch:  pusha
push es

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```4

changeTime: add word [cs:ms], 55
cmp word[cs:ms], 1000
jle modCheck

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```5

modCheck:   cmp byte [cs:sMode], 1
jz splitMode

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```6

dEOI:       jmp EOI                     ;Using dEOI as an intermediate jump because of the short range of near jump

splitMode:  cmp byte [cs:snapshot], 1
jnz eEOI                        ;Going to use two jumps because of the short range of near jump

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```7

eEOI:      jmp EOI                          ;An intermediate jump to EOI

lapMode:  cmp byte [cs:lapTime], 1
jnz xEOI                        ;Using two intermediate jumps because of the short range of near jumps

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```8

l1:        sub ax, [cs:lms]
cmp ax, 0
jge l2

```<code>            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret
</code>```9

l2:        mov [cs:lms],ax

```<code>            in  al, 0x60

            ;Checking release code only

            cmp al, 147         ;checking for 'R'
            jz  reset
            jnz modChanger
</code>```0

l3:        mov [cs:ls],bx

```<code>            in  al, 0x60

            ;Checking release code only

            cmp al, 147         ;checking for 'R'
            jz  reset
            jnz modChanger
</code>```1

xEOI:      jmp EOI                    ;An intermediate jump to EOI

```<code>            in  al, 0x60

            ;Checking release code only

            cmp al, 147         ;checking for 'R'
            jz  reset
            jnz modChanger
</code>```2

l4:        sub cx, [cs:lmin]
cmp cx, 0
jge l5

```<code>       add cx, 60
       dec dx
</code>```

l5:        mov [cs:lmin],cx

```<code>       ;Subtracting the Hours
       sub dx, [cs:lhrs]
       mov [cs:lhrs],dx

       ;After the subtraction is done, print the new lapTime

       push word [cs:lms]
       push word [cs:ls]
       push word [cs:lmin]
       push word [cs:lhrs]

       ;Position Calculation
       mov al, 80
       mul byte [cs:location]
       shl ax, 1

       add byte [cs:location], 2

       push ax
       call printTime

       jmp EOI
</code>```

EOI:        mov al, 0x20
out 0x20, al

return:     pop es
popa
iret

;-------------------------------------------------------------------------------------------------------------------

;Driver Function

start:       mov ax, 0
mov es, ax

```<code>         ;Saving the previous keyboard handler routine
         mov ax, [es:9*4]
         mov [oldkb],ax
         mov ax, [es:9*4+2]
         mov [oldkb+2], ax

         call clrscr

         ;Hooking the interrupts

         cli

         ;Keyboard Interrupt
         mov word [es:9*4], kbisr
         mov [es:9*4+2], cs

         ;Timer Interrupt
         mov word [es:8*4], stopWatch
         mov [es:8*4+2], cs

         sti

         ;Making it TSR
         mov dx, start
         add dx, 15
         mov cl, 4
         shr dx, cl

         mov ax, 0x3100
         int 21h
</code>```

;-------------------------------------------------------------------------------------------------------------------

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

Body:
error on word byte hour  [org 0x0100]

I am working on a project in assembly.(stopwatch user input change style and size ) I am working in   (in 16 bit assembly in emu8086).
I have been working on this for a long time and could not find the problem in my code.
What I am doing is simply creating stopwatch which shows  time when user  enter input its  change  style and style  of  userInput

I have been trying for a long time to solve it but I can't find my mistake. If someone can find my mistake please let me know.
Thank you very much.

jmp start

h
;Orignal Time
hrs:    dw 0 ;WORD Byte
min:    dw 0
s:      dw 0
ms:     dw 0

;Lap Time
lhrs:   dw 0
lmin:   dw 0
ls:     dw 0
lms:    dw 0

oldkb:  dd 0 ; declare double word dd ;For the purpose of saving the old keyboard ISR

;Flags for Modes
sMode:  db 0
lMode:  db 0

;Flags for other functions
startTimer:  db 0
snapshot:    db 0
lapTime:     db 0

location:   db 6

;------------------------------------------------------------------------------------------------------------------

;Clear Screen Sub Routine

clrscr:     pusha
push es

        mov ax, 0xb800
        mov es, ax
        xor di, di
        mov ax, 0x720
        mov cx, 2000

        cld
        rep stosw

        pop es
        popa
        ret

;-------------------------------------------------------------------------------------------------------------------

;Print the Main Layout

printLayout:    pusha   ; push all 32 oprend size
push es

            mov ax, 0xB800
            mov es, ax

            mov di, 160

            mov byte[es:di+0], 'H'
            mov byte[es:di+2], 'R'
            mov byte[es:di+4], 'S'

            mov byte[es:di+8], ':'

            mov byte[es:di+12], 'M'
            mov byte[es:di+14], 'I'
            mov byte[es:di+16], 'N'

            mov byte[es:di+20], ':'

            mov byte[es:di+24], 'S'

            mov byte[es:di+28], ':'

            mov byte[es:di+34], 'M'
            mov byte[es:di+36], 'S'

            pop es
            popa
            ret

;-------------------------------------------------------------------------------------------------------------------

;-------------------------------------------------------------------------------------------------------------------

;Keyboard ISR

kbisr:          push ax

            in  al, 0x60

            ;Checking release code only

            cmp al, 147         ;checking for 'R'
            jz  reset
            jnz modChanger

reset:          ;Resetting the orginal time

            mov word [cs:hrs], 0
            mov word [cs:min], 0
            mov word [cs:s]   ,0
            mov word [cs:ms], 0

            ;Resetting the lap time

            mov word [cs:lhrs], 0
            mov word [cs:lmin], 0
            mov word [cs:ls], 0
            mov word [cs:lms], 0

            call clrscr

            mov byte [cs:location], 6

            jmp EOI1

modChanger:     cmp al, 170                     ;Release code of Shift Left
jnz checkLMode1

            mov byte [cs:lMode], 0          ;Disable the lap mode

            cmp byte [cs:sMode], 1          ;If sMode was already enabled then do nothing
            jz EOI1

            mov byte [cs:sMode], 1          ;Else enable the sMode
            jmp EOI1

checkLMode1:    cmp al, 182                     ;Release code of Shift Right
jnz startTime

            mov byte [cs:sMode], 0          ;Disable the split Mode

            cmp byte [cs:lMode], 1          ;If lMode was aleady enabled then do nothing
            jz  EOI1

            mov byte [cs:lMode], 1          ;Else enable the lMode
            jmp EOI1

;Scenarios when space key is released

startTime:      cmp al, 185
jnz oldKbHandler

            cmp byte [cs:startTimer], 1     ;If Timer is already started then do nothing
            jz  check0

            mov byte [cs:startTimer], 1     ;Else start the timer

check0:         cmp byte [cs:sMode], 1            ;If split mode is enabled
jnz  check1

            mov byte [cs:snapshot], 1
            jmp EOI1

check1:         cmp byte [cs:lMode], 1        ;Else if the lap mode is enabled
jnz EOI1

            mov byte [cs:lapTime], 1
            jmp EOI1

EOI1:           mov al,0x20                     ;End of Interrupt Signal
out 0x20,al

            pop ax
            iret

;Rest of the Keyboard keys are handled by the old keyboard ISR
oldKbHandler:   pop ax
jmp far [cs:oldkb]

;-------------------------------------------------------------------------------------------------------------------

;-------------------------------------------------------------------------------------------------------------------

;To print the number on screen

printstr:   push bp
mov bp, sp
pusha

        push es

        mov ax, 0xb800
        mov es, ax

        mov di, [bp+4]                  ;Location
        mov ax, [bp+6]                  ;Number

        mov bx, 10
        mov cx, 0

nextdigit:  mov dx, 0
div bx
add dl, 0x30
push dx
inc cx
cmp ax, 0
jnz nextdigit

        cmp cx, 1
        jnz nextpos
        mov byte [es:di], '0'
        add di, 2

nextpos:    pop dx
mov dh, 0x07
mov [es:di], dx
add di, 2
loop nextpos

        pop es
        popa
        pop bp
        ret 4

;-------------------------------------------------------------------------------------------------------------------

;Function which prints the time on screen

printTime:  push bp
mov bp,sp
pusha

        push es

        mov ax, 0xB800
        mov es, ax

        mov di, [bp+4]                  ;Location where the time is to be printed

        ;Printing hours
        push word [bp+6]
        add di, 2
        push di
        call printstr

        ;Printing Colon
        add di, 6
        mov byte [es:di], ':'

        ;Printing minutes
        push word [bp+8]
        add di, 6
        push di
        call printstr

        ;Printing Colon
        add di, 6
        mov byte [es:di], ':'

        ;Printing seconds
        push word [bp+10]
        add di, 2
        push di
        call printstr

        ;Printing Colon
        add di, 6
        mov byte [es:di], ':'

        ;Printing milli seconds
        push word [bp+12]
        add di, 2
        push di
        call printstr

        pop es

        popa
        pop bp
        ret 10

;-------------------------------------------------------------------------------------------------------------------

;Shift Left for Split Mode
;Shift Right for Lap Mode

stopWatch:  pusha
push es

        call printLayout

        push word [cs:ms]
        push word [cs:s]
        push word [cs:min]
        push word [cs:hrs]

        push 480
        call printTime

        cmp byte [cs:startTimer], 1
        jnz dEOI                            ;Using two jumps because of the short range of near jump

changeTime: add word [cs:ms], 55
cmp word[cs:ms], 1000
jle modCheck

        mov word [cs:ms], 0
        inc word[cs:s]
        cmp word [cs:s], 60
        jnz modCheck

        mov word [cs:s], 0
        inc word[cs:min]
        cmp word [cs:min], 60
        jnz modCheck

        mov word [cs:min], 0
        inc word[cs:hrs]

        jmp modCheck

modCheck:   cmp byte [cs:sMode], 1
jz splitMode

        cmp byte [cs:lMode], 1
        jz  lapMode

        jmp EOI

dEOI:       jmp EOI                     ;Using dEOI as an intermediate jump because of the short range of near jump

splitMode:  cmp byte [cs:snapshot], 1
jnz eEOI                        ;Going to use two jumps because of the short range of near jump

        mov byte [cs:snapshot], 0

        push word [cs:ms]
        push word [cs:s]
        push word [cs:min]
        push word [cs:hrs]

        ;Position Calculation
        mov al, 80
        mul byte [cs:location]
        shl ax, 1

        add byte [cs:location], 2

        push ax
        call printTime

        jmp EOI

eEOI:      jmp EOI                          ;An intermediate jump to EOI

lapMode:  cmp byte [cs:lapTime], 1
jnz xEOI                        ;Using two intermediate jumps because of the short range of near jumps

       mov byte [cs:lapTime], 0

       ;Deducting the previos Lap Time from the original time to get the new Lap Time

       ;Making copy of the original Time
       mov ax, [cs:ms]
       mov bx, [cs:s]
       mov cx, [cs:min]
       mov dx, [cs:hrs]

       ;Subtracting the MilliSeconds

l1:        sub ax, [cs:lms]
cmp ax, 0
jge l2

       add ax, 1000
       dec bx

l2:        mov [cs:lms],ax

       ;Subtracting the Seconds
       sub bx, [cs:ls]
       cmp bx, 0
       jge l3

       add bx, 60
       dec cx

l3:        mov [cs:ls],bx

       jmp l4                      ;For skipping the xEOI given below

xEOI:      jmp EOI                    ;An intermediate jump to EOI

       ;Subtracting the Minutes

l4:        sub cx, [cs:lmin]
cmp cx, 0
jge l5

       add cx, 60
       dec dx

l5:        mov [cs:lmin],cx

       ;Subtracting the Hours
       sub dx, [cs:lhrs]
       mov [cs:lhrs],dx

       ;After the subtraction is done, print the new lapTime

       push word [cs:lms]
       push word [cs:ls]
       push word [cs:lmin]
       push word [cs:lhrs]

       ;Position Calculation
       mov al, 80
       mul byte [cs:location]
       shl ax, 1

       add byte [cs:location], 2

       push ax
       call printTime

       jmp EOI

EOI:        mov al, 0x20
out 0x20, al

return:     pop es
popa
iret

;-------------------------------------------------------------------------------------------------------------------

;Driver Function

start:       mov ax, 0
mov es, ax

         ;Saving the previous keyboard handler routine
         mov ax, [es:9*4]
         mov [oldkb],ax
         mov ax, [es:9*4+2]
         mov [oldkb+2], ax

         call clrscr

         ;Hooking the interrupts

         cli

         ;Keyboard Interrupt
         mov word [es:9*4], kbisr
         mov [es:9*4+2], cs

         ;Timer Interrupt
         mov word [es:8*4], stopWatch
         mov [es:8*4+2], cs

         sti

         ;Making it TSR
         mov dx, start
         add dx, 15
         mov cl, 4
         shr dx, cl

         mov ax, 0x3100
         int 21h

;-------------------------------------------------------------------------------------------------------------------


问:
Why this avr/io.h header give me fatal error?
I add this header on my C program. And it gives me no such file or directory.
Here is that error: fatal error: avr/io.h: No such file or directory.

Here is all of my code:

```<code>#include <avr/io.h>

int main(void)
{
  DDRB |= (1 << PB5);  // Set PB5 as output

  while (1)
  {
    PORTB |= (1 << PB5);  // Turn on LED
    _delay_ms(1000);  // Wait for 1 second
    PORTB &= ~(1 << PB5);  // Turn off LED
    _delay_ms(1000);  // Wait for 1 second
  }

  return 0;
}

</code>```

Body:
I add this header on my C program. And it gives me no such file or directory.
Here is that error: fatal error: avr/io.h: No such file or directory.

Here is all of my code:

#include <avr/io.h>

int main(void)
{
  DDRB |= (1 << PB5);  // Set PB5 as output

  while (1)
  {
    PORTB |= (1 << PB5);  // Turn on LED
    _delay_ms(1000);  // Wait for 1 second
    PORTB &= ~(1 << PB5);  // Turn off LED
    _delay_ms(1000);  // Wait for 1 second
  }

  return 0;
}


问:
How can display index.hbs instead of index.html inside public_html on cpanel
I built my website using a JavaScript template engine handlesbar and it runs perfectly locally but it does not display at all after uploading to the cpanel of my hosting company.

However, whenever, I change the index.hbs to index.html, it will load my website files but if you try to access any routes built using handlebars, it displays 404 page.

Kindly help.

I have tried hosting the project on javascript hosting plan and change the extension, it does not load my website successfully.


问:
Multiple body tracking causes character model to jump between tracked people
I am currently working on a project to track a persons body and map it to a 3D model by using Microsoft's Azure Kinect. Following the official documentation and using the GitHub sample here, I am running into the problem that if a person is tracked and another one enters the tracking area of the Kinect, the 3D model starts to 'jump' between them, as the Kinect sends multiple body tracking information to Unity.

So far, I've tried to limit the number of bodies coming from the Kinect inside the BackgroundData.cs, but without success.

As I am new to the body tracking topic, I hope there is someone who can give me a hint on how to solve this issue.


问:
Issues in setting Authentication after successfull google SSO login in Spring Security and Boot
I am using Google SSO in my Spring Boot Application. Used this thread for same.
Step by step Google SSO (java)?

I am using HttpClient to call first google endpoint to get the google sign in - where user can add google creadentials.

It gets redirected to the redirect_url configuration set, which in turn calls my Controller \login, where I get the code returned by google api, there I send another api call to get access_token

In my LoginController, I am able to get the user details, but I do not know how to manage adding it in Authentication and make it available for other controllers. I also want to use these User details for Audit purpose.

Below is my code for main classes

```<code>@Component
@Slf4j
public class SecurityFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);

        try {
            // How to check here if authentication already done.
            String redirectUrl = GoogleSSORestClient.getRedirectUrl();
            resp.sendRedirect(redirectUrl);
            filterChain.doFilter(request, response);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        //filterChain.doFilter(request, response);
    }
}
</code>```
```<code>
@Controller

public class LoginController {

    @Autowired
    LoginService service;

    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String showLoginPage(@RequestParam Map<String,String> allRequestParams, ModelMap model){

        if(!allRequestParams.containsKey("access_token")) {
            String code =allRequestParams.get("code");
            String accessToken = GoogleSSORestClient.getAccessToken(code);
            User user = getUserInfo(accessToken);

            if (user != null) {
                //UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
                  //      new Credentials(type, decodedToken, token, session), null);
                //authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                //SecurityContextHolder.getContext().setAuthentication(authentication);

                if (user != null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
                            new Credentials(), null);
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        return "success";
    }

private User getUserInfo(String accessToken) {
    User user = null;

    String urlToRead = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
    URL url;
    HttpURLConnection conn;
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
    String id = null;

    String picture = null;
    StringBuilder result = new StringBuilder();
   // try {
         conn.setRequestMethod("GET");
         try (BufferedReader reader = new BufferedReader(
                 new InputStreamReader(conn.getInputStream()))) {
             for (String line; (line = reader.readLine()) != null; ) {
                 result.append(line);
             }
         }
        //JSONParser jsonParser = new JSONParser();
        JSONObject obj = new JSONObject(result.toString());
        JSONObject parsed = (JSONObject)obj;
        id = (String) parsed.get("id");

        picture = (String) parsed.get("picture");

        user = new User();
        user.setId(googleId);
        user.setPicture(picture);

    }catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return user;
}

}
</code>```

I have added SecurityConfig, but not sure if I should go with Authentication Provider

```<code>
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    SecurityProperties restSecProps;

    @Autowired
    public SecurityFilter tokenAuthenticationFilter;

    @Bean
    public AuthenticationEntryPoint restAuthenticationEntryPoint() {
        return (httpServletRequest, httpServletResponse, e) -> {
            Map<String, Object> errorObject = new HashMap<>();
            int errorCode = 401;
            errorObject.put("message", "Unauthorized access of protected resource, invalid credentials");
            errorObject.put("error", HttpStatus.UNAUTHORIZED);
            errorObject.put("code", errorCode);
            errorObject.put("timestamp", new Timestamp(new Date().getTime()));
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.setStatus(errorCode);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(errorObject));
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(restSecProps.getAllowedOrigins());
        configuration.setAllowedMethods(restSecProps.getAllowedMethods());
        configuration.setAllowedHeaders(restSecProps.getAllowedHeaders());
        configuration.setAllowCredentials(restSecProps.isAllowCredentials());
        configuration.setExposedHeaders(restSecProps.getExposedHeaders());
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable().formLogin().disable()
                .httpBasic().disable().exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint())
                .and().authorizeRequests()
                .antMatchers(restSecProps.getAllowedPublicApis().toArray(new String[1])).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll().anyRequest().authenticated().and()
                .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);*/

        /*String redirectUrl = GoogleSSOClient.getRedirectUrl();
        http
        .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()

            .loginPage(redirectUrl)
            .defaultSuccessUrl("/login")
            .permitAll(); */
    }
}
</code>```

Any Suggestions will be of great help.
Thanks,

Body:
I am using Google SSO in my Spring Boot Application. Used this thread for same.
Step by step Google SSO (java)?

I am using HttpClient to call first google endpoint to get the google sign in - where user can add google creadentials.

It gets redirected to the redirect_url configuration set, which in turn calls my Controller \login, where I get the code returned by google api, there I send another api call to get access_token

In my LoginController, I am able to get the user details, but I do not know how to manage adding it in Authentication and make it available for other controllers. I also want to use these User details for Audit purpose.

Below is my code for main classes

@Component
@Slf4j
public class SecurityFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);

        try {
            // How to check here if authentication already done.
            String redirectUrl = GoogleSSORestClient.getRedirectUrl();
            resp.sendRedirect(redirectUrl);
            filterChain.doFilter(request, response);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        //filterChain.doFilter(request, response);
    }
}

@Controller

public class LoginController {

    @Autowired
    LoginService service;

    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String showLoginPage(@RequestParam Map<String,String> allRequestParams, ModelMap model){

        if(!allRequestParams.containsKey("access_token")) {
            String code =allRequestParams.get("code");
            String accessToken = GoogleSSORestClient.getAccessToken(code);
            User user = getUserInfo(accessToken);

            if (user != null) {
                //UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
                  //      new Credentials(type, decodedToken, token, session), null);
                //authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                //SecurityContextHolder.getContext().setAuthentication(authentication);

                if (user != null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
                            new Credentials(), null);
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        return "success";
    }

private User getUserInfo(String accessToken) {
    User user = null;

    String urlToRead = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
    URL url;
    HttpURLConnection conn;
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
    String id = null;

    String picture = null;
    StringBuilder result = new StringBuilder();
   // try {
         conn.setRequestMethod("GET");
         try (BufferedReader reader = new BufferedReader(
                 new InputStreamReader(conn.getInputStream()))) {
             for (String line; (line = reader.readLine()) != null; ) {
                 result.append(line);
             }
         }
        //JSONParser jsonParser = new JSONParser();
        JSONObject obj = new JSONObject(result.toString());
        JSONObject parsed = (JSONObject)obj;
        id = (String) parsed.get("id");

        picture = (String) parsed.get("picture");

        user = new User();
        user.setId(googleId);
        user.setPicture(picture);

    }catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return user;
}

}

I have added SecurityConfig, but not sure if I should go with Authentication Provider

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    SecurityProperties restSecProps;

    @Autowired
    public SecurityFilter tokenAuthenticationFilter;

    @Bean
    public AuthenticationEntryPoint restAuthenticationEntryPoint() {
        return (httpServletRequest, httpServletResponse, e) -> {
            Map<String, Object> errorObject = new HashMap<>();
            int errorCode = 401;
            errorObject.put("message", "Unauthorized access of protected resource, invalid credentials");
            errorObject.put("error", HttpStatus.UNAUTHORIZED);
            errorObject.put("code", errorCode);
            errorObject.put("timestamp", new Timestamp(new Date().getTime()));
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.setStatus(errorCode);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(errorObject));
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(restSecProps.getAllowedOrigins());
        configuration.setAllowedMethods(restSecProps.getAllowedMethods());
        configuration.setAllowedHeaders(restSecProps.getAllowedHeaders());
        configuration.setAllowCredentials(restSecProps.isAllowCredentials());
        configuration.setExposedHeaders(restSecProps.getExposedHeaders());
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable().formLogin().disable()
                .httpBasic().disable().exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint())
                .and().authorizeRequests()
                .antMatchers(restSecProps.getAllowedPublicApis().toArray(new String[1])).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll().anyRequest().authenticated().and()
                .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);*/

        /*String redirectUrl = GoogleSSOClient.getRedirectUrl();
        http
        .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()

            .loginPage(redirectUrl)
            .defaultSuccessUrl("/login")
            .permitAll(); */
    }
}

Any Suggestions will be of great help.
Thanks,


问:
Storing Values from an Excel File and storing the same into Remote MySql Database
I am developing a C# Desktop Application where I want to store values stored in an Excel file to a Remote MySql Database.

Early help will really be Appreciated.

Thanks, and Regards
Rohit Sharma, The Webgrapghica

Need guidance to solve the issue.


问:
Nested inlineformset_factory
I use Django inlineformset_factory.

I want to include A model in B model in C model.

my models:

```<code>class A:
    instruction = charField( max_length=255, verbose_name="Consigne*")

class B:
    instruction = charField( max_length=255, verbose_name="Consigne*")
    modela      = models.ForeignKey(A, related_name="modelas", blank=True, null = True,  on_delete=models.CASCADE)

class C:
    instruction = charField( max_length=255, verbose_name="Consigne*")
    modelb      = models.ForeignKey(B, related_name="modelbs", blank=True, null = True,  on_delete=models.CASCADE)
</code>```

my view:

```<code>formSet  = inlineformset_factory( A, B, fields=('instruction',)  , extra=2)
form_ans = formSet(request.POST or None,  request.FILES or None)
</code>```

How insert model C nested in model B ?

Hope you understand my message...

Thanks.

I tried this :

```<code>        formSet  = inlineformset_factory( A, B, fields=('instruction',)  , extra = 2)
        form_ans = formSet()
        formSubset   = inlineformset_factory( B, C, fields=('instruction',) , extra=2)
        form_sub_ans = formSubset()
</code>```

But C is not nested in B. I know it but I dont have any idea.. My Jquery code is ok.

Title: Nested inlineformset_factory

Body:
I use Django inlineformset_factory.

I want to include A model in B model in C model.

my models:

class A:
    instruction = charField( max_length=255, verbose_name="Consigne*")

class B:
    instruction = charField( max_length=255, verbose_name="Consigne*")
    modela      = models.ForeignKey(A, related_name="modelas", blank=True, null = True,  on_delete=models.CASCADE)

class C:
    instruction = charField( max_length=255, verbose_name="Consigne*")
    modelb      = models.ForeignKey(B, related_name="modelbs", blank=True, null = True,  on_delete=models.CASCADE)

my view:

formSet  = inlineformset_factory( A, B, fields=('instruction',)  , extra=2)
form_ans = formSet(request.POST or None,  request.FILES or None)

How insert model C nested in model B ?

Hope you understand my message...

Thanks.

I tried this :

        formSet  = inlineformset_factory( A, B, fields=('instruction',)  , extra = 2)
        form_ans = formSet()
        formSubset   = inlineformset_factory( B, C, fields=('instruction',) , extra=2)
        form_sub_ans = formSubset()

But C is not nested in B. I know it but I dont have any idea.. My Jquery code is ok.