问:
How do I fix the hibernate validator problem with spring boot and ejb intergration
I am using some of the jars that have ejb services for a spring based rest interface I am trying to build. I am using spring boot for the project. I added the required dependencies, but the application is having issues with hibernate validator. Can someone please look at it and let me know what could be wrong with it? Please find the stack trace below:

```<code> org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultValidator' defined in class path resource [org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.validation.beanvalidation.LocalValidatorFactoryBean]: Factory method 'defaultValidator' threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at com.mrs.MrsApplication.main(MrsApplication.java:25) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.validation.beanvalidation.LocalValidatorFactoryBean]: Factory method 'defaultValidator' threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    ... 19 common frames omitted
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:33) ~[hibernate-validator-6.0.17.Final.jar:6.0.17.Final]
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:296) ~[validation-api-2.0.1.Final.jar:na]
    at org.springframework.boot.validation.MessageInterpolatorFactory.getObject(MessageInterpolatorFactory.java:53) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration.defaultValidator(ValidationAutoConfiguration.java:57) ~[spring-boot-autoconfigure-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    ... 20 common frames omitted

</code>```

Please find the dependencies from the pom.xml below:

```<code><dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-validator</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
             <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-validator</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.3.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
</code>```

Please find the mvn dependency tree below:

```<code>[INFO]
[INFO] --- maven-dependency-plugin:3.1.1:tree (default-cli) @ mrs ---
[INFO] com.mrs:mrs:jar:0.0.1-SNAPSHOT
[INFO] +- log4j:log4j:jar:1.2.17:compile
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.1.8.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.1.8.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  |  |  |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  |  |  |  \- org.slf4j:slf4j-api:jar:1.7.28:compile
[INFO] |  |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.11.2:compile
[INFO] |  |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.11.2:compile
[INFO] |  |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.28:compile
[INFO] |  |  +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  |  +- org.springframework:spring-core:jar:5.1.9.RELEASE:compile
[INFO] |  |  |  \- org.springframework:spring-jcl:jar:5.1.9.RELEASE:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.23:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-json:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.9.3:compile
[INFO] |  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] |  |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.9.9:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.9:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.9:compile
[INFO] |  |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.9.9:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.24:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.24:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.24:compile
[INFO] |  +- org.hibernate.validator:hibernate-validator:jar:6.0.17.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.4.0:compile
[INFO] |  +- org.springframework:spring-web:jar:5.1.9.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:5.1.9.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:5.1.9.RELEASE:compile
[INFO] |     +- org.springframework:spring-aop:jar:5.1.9.RELEASE:compile
[INFO] |     +- org.springframework:spring-context:jar:5.1.9.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:5.1.9.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-web-services:jar:2.1.8.RELEASE:compile
[INFO] |  +- com.sun.xml.messaging.saaj:saaj-impl:jar:1.5.0:compile
[INFO] |  |  +- javax.xml.soap:javax.xml.soap-api:jar:1.4.0:compile
[INFO] |  |  +- org.jvnet.mimepull:mimepull:jar:1.9.11:compile
[INFO] |  |  \- org.jvnet.staxex:stax-ex:jar:1.8:compile
[INFO] |  +- javax.xml.ws:jaxws-api:jar:2.3.1:compile
[INFO] |  |  \- javax.xml.bind:jaxb-api:jar:2.3.1:compile
[INFO] |  |     \- javax.activation:javax.activation-api:jar:1.2.0:compile
[INFO] |  +- org.springframework:spring-oxm:jar:5.1.9.RELEASE:compile
[INFO] |  \- org.springframework.ws:spring-ws-core:jar:3.0.7.RELEASE:compile
[INFO] |     +- org.springframework.ws:spring-xml:jar:3.0.7.RELEASE:compile
[INFO] |     \- commons-io:commons-io:jar:2.5:compile
[INFO] +- com.google.code.gson:gson:jar:2.8.5:compile
[INFO] +- org.jboss.logging:jboss-logging:jar:3.3.3.Final:compile
[INFO] \- javax.validation:validation-api:jar:2.0.1.Final:compile

</code>```

答:
You need to add spring-boot-starter-validation to your pom.xml

```<code><dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</code>```

Body:
I am using some of the jars that have ejb services for a spring based rest interface I am trying to build. I am using spring boot for the project. I added the required dependencies, but the application is having issues with hibernate validator. Can someone please look at it and let me know what could be wrong with it? Please find the stack trace below:

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultValidator' defined in class path resource [org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.validation.beanvalidation.LocalValidatorFactoryBean]: Factory method 'defaultValidator' threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at com.mrs.MrsApplication.main(MrsApplication.java:25) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.validation.beanvalidation.LocalValidatorFactoryBean]: Factory method 'defaultValidator' threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    ... 19 common frames omitted
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:33) ~[hibernate-validator-6.0.17.Final.jar:6.0.17.Final]
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:296) ~[validation-api-2.0.1.Final.jar:na]
    at org.springframework.boot.validation.MessageInterpolatorFactory.getObject(MessageInterpolatorFactory.java:53) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration.defaultValidator(ValidationAutoConfiguration.java:57) ~[spring-boot-autoconfigure-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    ... 20 common frames omitted

Please find the dependencies from the pom.xml below:

<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-validator</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
             <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-validator</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.3.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

Please find the mvn dependency tree below:

[INFO]
[INFO] --- maven-dependency-plugin:3.1.1:tree (default-cli) @ mrs ---
[INFO] com.mrs:mrs:jar:0.0.1-SNAPSHOT
[INFO] +- log4j:log4j:jar:1.2.17:compile
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.1.8.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.1.8.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  |  |  |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  |  |  |  \- org.slf4j:slf4j-api:jar:1.7.28:compile
[INFO] |  |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.11.2:compile
[INFO] |  |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.11.2:compile
[INFO] |  |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.28:compile
[INFO] |  |  +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  |  +- org.springframework:spring-core:jar:5.1.9.RELEASE:compile
[INFO] |  |  |  \- org.springframework:spring-jcl:jar:5.1.9.RELEASE:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.23:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-json:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.9.3:compile
[INFO] |  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] |  |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.9.9:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.9:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.9:compile
[INFO] |  |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.9.9:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.1.8.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.24:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.24:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.24:compile
[INFO] |  +- org.hibernate.validator:hibernate-validator:jar:6.0.17.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.4.0:compile
[INFO] |  +- org.springframework:spring-web:jar:5.1.9.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:5.1.9.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:5.1.9.RELEASE:compile
[INFO] |     +- org.springframework:spring-aop:jar:5.1.9.RELEASE:compile
[INFO] |     +- org.springframework:spring-context:jar:5.1.9.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:5.1.9.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-web-services:jar:2.1.8.RELEASE:compile
[INFO] |  +- com.sun.xml.messaging.saaj:saaj-impl:jar:1.5.0:compile
[INFO] |  |  +- javax.xml.soap:javax.xml.soap-api:jar:1.4.0:compile
[INFO] |  |  +- org.jvnet.mimepull:mimepull:jar:1.9.11:compile
[INFO] |  |  \- org.jvnet.staxex:stax-ex:jar:1.8:compile
[INFO] |  +- javax.xml.ws:jaxws-api:jar:2.3.1:compile
[INFO] |  |  \- javax.xml.bind:jaxb-api:jar:2.3.1:compile
[INFO] |  |     \- javax.activation:javax.activation-api:jar:1.2.0:compile
[INFO] |  +- org.springframework:spring-oxm:jar:5.1.9.RELEASE:compile
[INFO] |  \- org.springframework.ws:spring-ws-core:jar:3.0.7.RELEASE:compile
[INFO] |     +- org.springframework.ws:spring-xml:jar:3.0.7.RELEASE:compile
[INFO] |     \- commons-io:commons-io:jar:2.5:compile
[INFO] +- com.google.code.gson:gson:jar:2.8.5:compile
[INFO] +- org.jboss.logging:jboss-logging:jar:3.3.3.Final:compile
[INFO] \- javax.validation:validation-api:jar:2.0.1.Final:compile

Body:
You need to add spring-boot-starter-validation to your pom.xml

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-validation</artifactId>
</dependency>


来源: stackexchange

问:
Order by as Number, even if column type is string, Laravel
I have a string column, but I have only double numbers (age), and I want to do a order by, but the obvious problem is that i get wrong response, because is string. ex: (1,10,2,3,4,40,etc...). In my code $table = name of the table, sort_by, in this particular case is "age".

```<code>$query->orderBy("CAST(" . $table . $request->sort_by . "as NUMERIC)", 'ASC');
</code>```

Error:

Undefined table: 7 ERROR:  missing FROM-clause entry for table
  "CAST(people"↵LINE 1:

答:
Use orderByRaw and cast the text number to an integer:

```<code>$query->orderByRaw("age::int")
</code>```

Note that if you have a persistent need to use this text number column as actual numeric data, it might imply a design problem, and perhaps the column should really be integer in your Postgres table.

ContentLicense: CC BY-SA 4.0

Body:
I have a string column, but I have only double numbers (age), and I want to do a order by, but the obvious problem is that i get wrong response, because is string. ex: (1,10,2,3,4,40,etc...). In my code $table = name of the table, sort_by, in this particular case is "age".

$query->orderBy("CAST(" . $table . $request->sort_by . "as NUMERIC)", 'ASC');

Error:

Undefined table: 7 ERROR:  missing FROM-clause entry for table
  "CAST(people"↵LINE 1:

Body:
Use orderByRaw and cast the text number to an integer:

$query->orderByRaw("age::int")

Note that if you have a persistent need to use this text number column as actual numeric data, it might imply a design problem, and perhaps the column should really be integer in your Postgres table.


问:
SeleniumGrid : org.openqa.selenium.SessionNotCreatedException: Unable to create new service: ChromeDriverService Build info: version: '3.141.59'
Thats how I started : Hub command : java -jar selenium-server-standalone-3.141.59.jar -role hub
Node Command : java -Dwebdriver.chrome.driver="\Users\rachitamittal\eclipse-workspace\firstjavaproject\drivers\chromedriver.exe" -jar selenium-server-standalone-3.141.59.jar -role node -port 5556 -hub "http://localhost:4444/wd/hub" -browser browserName=chrome,maxInstances=3
I have first only created a single node.
MY program :

@Test

public void remotetester() throws MalformedURLException

{

DesiredCapabilities cap = DesiredCapabilities.chrome();

cap.setBrowserName("chrome");

cap.setPlatform(Platform.MAC);

RemoteWebDriver driver=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),cap);

driver.get("https://www.google.com/");

driver.manage().window().maximize();

driver.close();

}

Error :
org.openqa.selenium.SessionNotCreatedException: Unable to create new service: ChromeDriverService

Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'

System info: host: '///////////', ip: '/////////////////', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.4', java.version: '14.0.1'

答:
Hope so you are doing great and you are safe. The problem is the webdriver path is incorrect. I believe that you have missed to method drive i.e C: in your web driver path.

If you are new and do not know how to configure the selenium grid in the local system then you can use the below utility for the automatic configuration.
https://github.com/frostyaxe/Talongrid


问:
How to get parent URL in Java?
In Objective-C I use -[NSURL URLByDeletingLastPathComponent] to get parent URL. What's the equivalent of this in Java?

答:
The simple solution offered by Guava library.

Code:

```<code>URL url = new URL("https://www.ibm.watson.co.uk");
String host = url.getHost();

InternetDomainName parent = InternetDomainName.from(host).parent(); // returns ibm.watson.co.uk
System.out.println("Immediate ancestor: "+parent);

ImmutableList<String> parts = InternetDomainName.from(host).parts();
System.out.println("Individual components:  "+parts);

InternetDomainName name = InternetDomainName.from(host).topPrivateDomain(); // watson.co.uk
System.out.println("Top private domain - " + name);
</code>```

Output:

```<code>Immediate ancestor: ibm.watson.co.uk

Individual components:  [www, ibm, watson, co, uk]

Top private domain - watson.co.uk
</code>```

For reference:
https://guava.dev/releases/snapshot/api/docs/com/google/common/net/InternetDomainName.html

Dependency required:

https://mvnrepository.com/artifact/com.google.guava/guava

I'm using version 19.0

```<code><dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
</dependency>
</code>```

And, many more related functionalities are provided by this class InternetDomainName.

ContentLicense: CC BY-SA 3.0

Title: How to get parent URL in Java?

Body:
The simple solution offered by Guava library.

Code:

URL url = new URL("https://www.ibm.watson.co.uk");
String host = url.getHost();

InternetDomainName parent = InternetDomainName.from(host).parent(); // returns ibm.watson.co.uk
System.out.println("Immediate ancestor: "+parent);

ImmutableList<String> parts = InternetDomainName.from(host).parts();
System.out.println("Individual components:  "+parts);

InternetDomainName name = InternetDomainName.from(host).topPrivateDomain(); // watson.co.uk
System.out.println("Top private domain - " + name);

Output:

Immediate ancestor: ibm.watson.co.uk

Individual components:  [www, ibm, watson, co, uk]

Top private domain - watson.co.uk

For reference:
https://guava.dev/releases/snapshot/api/docs/com/google/common/net/InternetDomainName.html

Dependency required:

https://mvnrepository.com/artifact/com.google.guava/guava

I'm using version 19.0

<dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
</dependency>

And, many more related functionalities are provided by this class InternetDomainName.


问:
Handling properties with "DatabaseGenerated" in ASP.NET Core WebAPI with Entity Framework Core
I have the following model class:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}
</code>```

When doing GET operations I want to return the object with the Id property, so the user can know what ID to query for update or specific GET. However I DON'T want the client to be able to provide a value for the ID property when doing POST requests and want it to be generated by the database as part of the IDENTITY thing.

How would I achieve that?

答:
You cannot manually set the value of an Identity (Auto Increment) column.

Here, in the below example PurchaseId is an Identity column.

```<code>purchase.PurchaseId = 6;
_dbContext.Purchases.Add(purchase);
_dbContext.SaveChanges();
</code>```

When saving changes to the database the EF Core throws Microsoft.EntityFrameworkCore.DbUpdateException with Cannot insert explicit value for identity column in table 'Purchases' when IDENTITY_INSERT is set to OFF. error.

So, by default, you cannot assign the value.

But this is not the issue here.

The bigger issue is that you are exposing the Domain classes to your client. This flaw in API design can lead to more than this problem.

You have to create a DTO e.g. CreateItemDTO whose only responsibility is to contain all the methods required to create an Item in the database.

The same way you should not expose Item class in the GET request. This leads to a problem when API related columns that are not for clients gets exposed. Create a GetItemDTO which would only contain information that is important for the GET request.

CreateItemDTO

```<code>public class CreateItemDTO
{
    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}
</code>```

Read Exposing domain models over API for more information.

Body:
I have the following model class:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}

When doing GET operations I want to return the object with the Id property, so the user can know what ID to query for update or specific GET. However I DON'T want the client to be able to provide a value for the ID property when doing POST requests and want it to be generated by the database as part of the IDENTITY thing.

How would I achieve that?

Body:
You cannot manually set the value of an Identity (Auto Increment) column.

Here, in the below example PurchaseId is an Identity column.

purchase.PurchaseId = 6;
_dbContext.Purchases.Add(purchase);
_dbContext.SaveChanges();

When saving changes to the database the EF Core throws Microsoft.EntityFrameworkCore.DbUpdateException with Cannot insert explicit value for identity column in table 'Purchases' when IDENTITY_INSERT is set to OFF. error.

So, by default, you cannot assign the value.

But this is not the issue here.

The bigger issue is that you are exposing the Domain classes to your client. This flaw in API design can lead to more than this problem.

You have to create a DTO e.g. CreateItemDTO whose only responsibility is to contain all the methods required to create an Item in the database.

The same way you should not expose Item class in the GET request. This leads to a problem when API related columns that are not for clients gets exposed. Create a GetItemDTO which would only contain information that is important for the GET request.

CreateItemDTO

public class CreateItemDTO
{
    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}

Read Exposing domain models over API for more information.


问:
How to code a very simple user login in Java?
I'm doing a coding exercise where I'm basically building a little shop application and I'm very very new to Java

I'm having some trouble though, I want to write a method called setPrice() that allows a user to change the price of a Content object by logging in and declaring a price

This is the Admin class (it extends user, I'll include that too). The Admin class has some commented out code that I tried to use to invoke the login (I'm not sure this is the right way to go about this though:

```<code>import java.util.Scanner;

public class Admin extends User {

    //class attributes
    String password;
    int privilegeLevel;
    boolean loggedIn;
    Scanner console = new Scanner(System.in);

    public Admin(String id, String name, String pass, int level) {
        super(id, name);
        password = pass;
        privilegeLevel = level;
    }

    public String getPassword() {
        return password;
    }

    public int getLevel() {
        return privilegeLevel;
    }

//  public void login() {
//      System.out.println("Please enter your password.");
//      String passwordAttempt = console.next();
//
//      if (password.contentEquals(passwordAttempt)) {
//          System.out.println("Log in successful");
//          loggedIn = true;
//      }else {
//          loggedIn = false;
//      }
//  }

}

</code>```

```<code>
public abstract class User {
    //Content Attributes
    private String ID;
    private String userName;

    public User(String id, String name) {
        ID = id;
        userName = name;
    }

    public void changeName(String newName) {
        this.userName = newName;

    }

    public String getUserID() {
        return ID;
    }

    public String getUsername() {
        return userName;
    }

}
</code>```

The piece of code I've been given that's supposed that  has to invoke the setPrice() method looks like this: b1.setPrice(a2.login(), 14.25);. Where b1 is a Book which is an extension of the Content class:

```<code>public abstract class Content {

    // Content Attributes
    private String contentName;
    private String contentID;
    private double contentPrice;
    private int downloadCount= 0;
    private Comment[] comments = new Comment[100];
    private int commentCount = 0;

    // Constructor
    public Content(String ID, String Name, double price) {
        this.contentID = ID;
        this.contentName = Name;
        this.contentPrice = price;

    }

    public Content(String ID, String Name) {
        this.contentID = ID;
        this.contentName = Name;
        this.contentPrice = 0;

    }
</code>```

```<code>import java.util.ArrayList;

public class Book extends Publication{
    //attributes
    private String[] authorNames;

    // constructor
    public Book(String ID, String name, double price, String publisher, int numberPages, String[] authors1){
        super(ID, name, price, publisher, numberPages);
        this.authorNames = authors1;
    }

    // accessor methods
    public String[] getAuthorName() {
        return authorNames;
    }

    public String[] getAuthorNames() {
        return authorNames;
    }
    }

</code>```

Basically I can work out what to write within the method, I just can't work out how to let the method accept a2.login() as a parameter?

答:
You can modify your login() code as below :

```<code>public boolean isloggedIn() {
      System.out.println("Please enter your password.");
      String passwordAttempt = console.next();

      if (password.contentEquals(passwordAttempt)) {
          System.out.println("Log in successful");
          loggedIn = true;
      }else {
          loggedIn = false;
      }
      return loggedIn;
  }
</code>```

And your setPrice() method as below :

```<code>void setPrice(boolean isLoggedIn, Double value)
  {
      if(isLoggedIn)
      {
          //set the price
      }
  }
</code>```

Then you can call:

```<code>b.setPrice(a2.isloggedIn(), 14.25);
</code>```

Body:
I'm doing a coding exercise where I'm basically building a little shop application and I'm very very new to Java

I'm having some trouble though, I want to write a method called setPrice() that allows a user to change the price of a Content object by logging in and declaring a price

This is the Admin class (it extends user, I'll include that too). The Admin class has some commented out code that I tried to use to invoke the login (I'm not sure this is the right way to go about this though:

import java.util.Scanner;

public class Admin extends User {

    //class attributes
    String password;
    int privilegeLevel;
    boolean loggedIn;
    Scanner console = new Scanner(System.in);

    public Admin(String id, String name, String pass, int level) {
        super(id, name);
        password = pass;
        privilegeLevel = level;
    }

    public String getPassword() {
        return password;
    }

    public int getLevel() {
        return privilegeLevel;
    }

//  public void login() {
//      System.out.println("Please enter your password.");
//      String passwordAttempt = console.next();
//
//      if (password.contentEquals(passwordAttempt)) {
//          System.out.println("Log in successful");
//          loggedIn = true;
//      }else {
//          loggedIn = false;
//      }
//  }

}

public abstract class User {
    //Content Attributes
    private String ID;
    private String userName;

    public User(String id, String name) {
        ID = id;
        userName = name;
    }

    public void changeName(String newName) {
        this.userName = newName;

    }

    public String getUserID() {
        return ID;
    }

    public String getUsername() {
        return userName;
    }

}

The piece of code I've been given that's supposed that  has to invoke the setPrice() method looks like this: b1.setPrice(a2.login(), 14.25);. Where b1 is a Book which is an extension of the Content class:

public abstract class Content {

    // Content Attributes
    private String contentName;
    private String contentID;
    private double contentPrice;
    private int downloadCount= 0;
    private Comment[] comments = new Comment[100];
    private int commentCount = 0;

    // Constructor
    public Content(String ID, String Name, double price) {
        this.contentID = ID;
        this.contentName = Name;
        this.contentPrice = price;

    }

    public Content(String ID, String Name) {
        this.contentID = ID;
        this.contentName = Name;
        this.contentPrice = 0;

    }

import java.util.ArrayList;

public class Book extends Publication{
    //attributes
    private String[] authorNames;

    // constructor
    public Book(String ID, String name, double price, String publisher, int numberPages, String[] authors1){
        super(ID, name, price, publisher, numberPages);
        this.authorNames = authors1;
    }

    // accessor methods
    public String[] getAuthorName() {
        return authorNames;
    }

    public String[] getAuthorNames() {
        return authorNames;
    }
    }

Basically I can work out what to write within the method, I just can't work out how to let the method accept a2.login() as a parameter?

Body:
You can modify your login() code as below :

public boolean isloggedIn() {
      System.out.println("Please enter your password.");
      String passwordAttempt = console.next();

      if (password.contentEquals(passwordAttempt)) {
          System.out.println("Log in successful");
          loggedIn = true;
      }else {
          loggedIn = false;
      }
      return loggedIn;
  }

And your setPrice() method as below :

void setPrice(boolean isLoggedIn, Double value)
  {
      if(isLoggedIn)
      {
          //set the price
      }
  }

Then you can call:

b.setPrice(a2.isloggedIn(), 14.25);


问:
pgAdmin 4 v3.1 How can I use another browser? (Win 7)
I'd like to change my default browser to IE (as that one has most of our internal sites programmed for). But currently, I can only get pgadmin4 to work well with Opera.
Is there a way to tell pgAdmin4 to use a different browser apart from the stock one?</p>

答: You just set as a default browser in any browser setting.PGAdmin Automatically Open as the set default browser</p>


问:
Pivot array of structs into columns using pyspark - not explode the array
I currently have a dataframe with an id and a column which is an array of structs:

```<code> root
 |-- id: string (nullable = true)
 |-- lists: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _1: string (nullable = true)
 |    |    |-- _2: string (nullable = true)
</code>```

Here is an example table with data:

```<code> id | list1             | list2
 ------------------------------------------
 1  | [[a, av], [b, bv]]| [[e, ev], [f,fv]]
 2  | [[c, cv]]         | [[g,gv]]
</code>```

How do I transform the above dataframe to the one below? I need to "explode" the array and add columns based on first value in the struct.

```<code> id | a   | b   | c   | d   | e  | f  | g
 ----------------------------------------
 1  | av  | bv  | null| null| ev | fv | null
 2  | null| null| cv  | null|null|null|gv
</code>```

A pyspark code to create the dataframe is as below:

```<code>d1 = spark.createDataFrame([("1", [("a","av"),("b","bv")], [("e", "ev"), ("f", "fv")]), \
                                    ("2", [("c", "cv")],  [("g", "gv")])], ["id","list1","list2"])
</code>```

Note: I have a spark version of 2.2.0 so some sql functions don't work such as concat_map, etc.

答:
You can do this using hogher order functions without exploding the arrays like:

```<code>d1.select('id',
          f.when(f.size(f.expr('''filter(list1,x->x._1='a')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='a'),value->value._2)'''))).alias('a'),\
          f.when(f.size(f.expr('''filter(list1,x->x._1='b')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='b'),value->value._2)'''))).alias('b'),\
          f.when(f.size(f.expr('''filter(list1,x->x._1='c')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='c'),value->value._2)'''))).alias('c'),\
          f.when(f.size(f.expr('''filter(list1,x->x._1='d')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='d'),value->value._2)'''))).alias('d'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='e')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='e'),value->value._2)'''))).alias('e'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='f')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='f'),value->value._2)'''))).alias('f'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='g')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='g'),value->value._2)'''))).alias('g'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='h')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='h'),value->value._2)'''))).alias('h')\
          ).show()

+---+----+----+----+----+----+----+----+----+
| id|   a|   b|   c|   d|   e|   f|   g|   h|
+---+----+----+----+----+----+----+----+----+
|  1|  av|  bv|null|null|  ev|  fv|null|null|
|  2|null|null|  cv|null|null|null|  gv|null|
+---+----+----+----+----+----+----+----+----+

</code>```

Hope it helps

Body:
I currently have a dataframe with an id and a column which is an array of structs:

 root
 |-- id: string (nullable = true)
 |-- lists: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _1: string (nullable = true)
 |    |    |-- _2: string (nullable = true)

Here is an example table with data:

 id | list1             | list2
 ------------------------------------------
 1  | [[a, av], [b, bv]]| [[e, ev], [f,fv]]
 2  | [[c, cv]]         | [[g,gv]]

How do I transform the above dataframe to the one below? I need to "explode" the array and add columns based on first value in the struct.

 id | a   | b   | c   | d   | e  | f  | g
 ----------------------------------------
 1  | av  | bv  | null| null| ev | fv | null
 2  | null| null| cv  | null|null|null|gv

A pyspark code to create the dataframe is as below:

d1 = spark.createDataFrame([("1", [("a","av"),("b","bv")], [("e", "ev"), ("f", "fv")]), \
                                    ("2", [("c", "cv")],  [("g", "gv")])], ["id","list1","list2"])

Note: I have a spark version of 2.2.0 so some sql functions don't work such as concat_map, etc.

Body:
You can do this using hogher order functions without exploding the arrays like:

d1.select('id',
          f.when(f.size(f.expr('''filter(list1,x->x._1='a')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='a'),value->value._2)'''))).alias('a'),\
          f.when(f.size(f.expr('''filter(list1,x->x._1='b')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='b'),value->value._2)'''))).alias('b'),\
          f.when(f.size(f.expr('''filter(list1,x->x._1='c')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='c'),value->value._2)'''))).alias('c'),\
          f.when(f.size(f.expr('''filter(list1,x->x._1='d')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list1,x->x._1='d'),value->value._2)'''))).alias('d'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='e')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='e'),value->value._2)'''))).alias('e'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='f')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='f'),value->value._2)'''))).alias('f'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='g')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='g'),value->value._2)'''))).alias('g'),\
          f.when(f.size(f.expr('''filter(list2,x->x._1='h')'''))>0,f.concat_ws(',',f.expr('''transform(filter(list2,x->x._1='h'),value->value._2)'''))).alias('h')\
          ).show()

+---+----+----+----+----+----+----+----+----+
| id|   a|   b|   c|   d|   e|   f|   g|   h|
+---+----+----+----+----+----+----+----+----+
|  1|  av|  bv|null|null|  ev|  fv|null|null|
|  2|null|null|  cv|null|null|null|  gv|null|
+---+----+----+----+----+----+----+----+----+

Hope it helps


问:
What is the difference between app:contentPadding and android:Padding?
I have a CardView and inside that there is a TextView. I am trying to add padding in card view. But when i use android:Padding="16dp" nothing happens between the textview and Cardview while when i use app:contentPadding="16dp" the 16dp space is created between the CardView and TextView.

Why is this happening?

答:
You can check the javadoc:

Since padding is used to offset content for shadows, you cannot set padding on CardView. Instead, you can use content padding attributes in XML or setContentPadding(int, int, int, int) in code to set the padding between the edges of the CardView and children of CardView.


问:
How to show for text More/Less in React-Native (JavaScript)
I am developing react-native application. In that, We are showing some description on Text, It may be number of lines.

So, If data has more than 3 lines, I have to show More and Less if it's expanded.

```<code>        <FlatList
          style={styles.faltList}
          showsVerticalScrollIndicator
          data={data}
          extraData={this.state}
          renderItem={({ item, index }) => (
            <View style={styles.flatListCell}>
                <Text style={styles.description}>{item.description}</Text>
              </View>
            </View>
          )
          }
          ItemSeparatorComponent={() => (
            <View style={{ height: 10}} />
          )}
        />
</code>```

I have found react-native-view-more-text library, But I would like to implement it by custom code.

Note: I am displaying that Text in FlatList.

Any suggestions?

答:
I tried in this way, Hope it helps to you and others!

const postTextContent = (props) => {
const [textShown, setTextShown] = useState(false); //To show ur remaining Text
const [lengthMore,setLengthMore] = useState(false); //to show the "Read more & Less Line"
const toggleNumberOfLines = () => { //To toggle the show text or hide it
    setTextShown(!textShown);
}

const onTextLayout = useCallback(e =>{
    setLengthMore(e.nativeEvent.lines.length >=4); //to check the text is more than 4 lines or not
    // console.log(e.nativeEvent);
},[]);

  return (
      <View style={styles.mainContainer}>
          <Text
              onTextLayout={onTextLayout}
              numberOfLines={textShown ? undefined : 4}
              style={{ lineHeight: 21 }}>{Your Long Text}</Text>

              {
                  lengthMore ? <Text
                  onPress={toggleNumberOfLines}
                  style={{ lineHeight: 21, marginTop: 10 }}>{textShown ? 'Read less...' : 'Read more...'}</Text>
                  :null
              }
      </View>
  )
}
```

Body:
I am developing react-native application. In that, We are showing some description on Text, It may be number of lines.

So, If data has more than 3 lines, I have to show More and Less if it's expanded.

        <FlatList
          style={styles.faltList}
          showsVerticalScrollIndicator
          data={data}
          extraData={this.state}
          renderItem={({ item, index }) => (
            <View style={styles.flatListCell}>
                <Text style={styles.description}>{item.description}</Text>
              </View>
            </View>
          )
          }
          ItemSeparatorComponent={() => (
            <View style={{ height: 10}} />
          )}
        />

I have found react-native-view-more-text library, But I would like to implement it by custom code.

Note: I am displaying that Text in FlatList.

Any suggestions?


问:
HTTP REST: If a request is idempotent, but the resource is unchangeable once inserted, should PUT or POST be used?
Imagine an HTTP REST endpoint, where a resource is inserted, and that the resource is understood to be a "message".  Each individual message is identified by a unique identifier, such as a GUID value of some sort.  The same message cannot be duplicated.

Now, in a lot of cases, that would lend itself to the PUT verb, since it's idempotent.  However consider the following scenario:

```<code>1. The sender sends this message to the receiver:

    {
        "id": 123,
        "text": "original text"
    }

2. Now the receiver has this value for the message stored in its database:

    {
        "id": 123,
        "text": "original text"
    }

3. For whatever reason, the sender tries to send the same message again, but with amended
   text:

    {
        "id": 123,
        "text": "amended text"
    }

4. The receiver receives that as well, but since the id field is the same as before, no
   action is taken, and this is what the receiver still has in its database:

    {
        "id": 123,
        "text": "original text"
    }
</code>```

The reason for the receiver's behavior is that each distinct message is to be uniquely identified by its id field, and that if another message is sent with the same id, it is simply considered a duplicate.  Furthermore, trying to change the message's contents like that and resend it with the same ID is invalid behavior on the sender's end.

So technically this is idempotent, which usually leans toward PUT.  However updates are not allowed in any context here, simply inserts.  So do we choose PUT or POST, or does it even matter?  PUT is supposed to be the full representation of the resource, but if it's simply discarded, is it okay to still return a 2xx response?

For the purposes of this question, assume that the route used is always of the form <host>/.../message, never of the form <host>/.../message/{id}.  In that case, I am wondering if being restricted to the <host>/.../message route scheme automatically means POST should be used.

答:
Imagine an HTTP REST endpoint,  ...

According to Fielding himself

There is no such thing as a REST endpoint. There are resources. A countably infinite set of resources bound only by restrictions on URL length. (Source)

So technically this is idempotent, which usually leans toward either PUT or PATCH ...

Idempotency is an important property to a client in regards to temporary network issues which allows it to automatically resend the request in case it did not receive a response within a reasonable amount of time. In such a case a client does not know whether the initial request received the server at all or just the response got lost. Idempotency has nothing to do with your demand to only allow to write to a resource only once. In addition to that, PATCH is not idempotent by default. Idempotent just means that processing a request always results in the same outcome, regardless how many times you send that request to the server.

Each individual message is identified by a unique identifier, such as a GUID value of some sort

... each distinct message is to be uniquely identified by its id field, and that if another message is sent with the same id, it is simply considered a duplicate.

A resource always is uniquely identifiable via its URI as a URI itself can only reference one single resource. A single resource however may have multiple URIs, i.e. one with an other without query parameters available. URI is an abbreviation for uniform resource identifier, where uniform denotes to remaining the same in all cases and at all times. This makes the requirement for the id  field in my opinion redundant.

As far as I understood your question, the actual text of the message does not define whether a message is a duplicate or not. So basically

PUT /messages/eaff31bd-5291-4287-a7dd-fbe5b1e47b67 HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
...

{
  "text": "original text"
}
```
<p>and</p>
<pre class="lang-json prettyprint-override"><code>PUT /messages/eb1db214-d231-4a50-916c-8de2d64c7d3a HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
...

{
  "text": "original text"
}
</code>```

are requests for two different messages as they target different resources, while you don't want to allow something like

PUT /messages/eaff31bd-5291-4287-a7dd-fbe5b1e47b67 HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
...

{
  "text": "amended text"
}
```
<p>as this would update an existing message.</p>
<p>In such a case I'd disable <code>PUT</code> completely for messages by not supporting it while allowing the creation of new messages only via <code>POST</code>. A request/response sample may look like this:</p>
<pre class="lang-json prettyprint-override"><code>POST /messages HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
Accept: application/json
...

{
  "text": "Some other text"
}
</code>```

which may yield a response such as:

HTTP/1.1 201 Created
Content-Type: application/json; charset="utf-8"
Location: http://www.acme.com/messages/740177d2-1de9-41bd-bd5b-6a52f39bf227
Etag: 33a64df551425fcc55e4d42a148795d9f25f89d4

{
  "text": "some other text"
}
```
<p>Attempting to update such a resource via</p>
<pre class="lang-json prettyprint-override"><code>PUT /messages/740177d2-1de9-41bd-bd5b-6a52f39bf227 HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
Etag: 33a64df551425fcc55e4d42a148795d9f25f89d4

{
  "text": "updated text"
}
</code>```

should result in a

```<code>HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD
</code>```

response, which states that a server knows the indicated PUT operation but does not support that operation on the target resource. The mandatory Allow header furthermore teaches your client about the valid HTTP operations supported by that resource.

For the purposes of this question, assume that the route used is always of the form /.../message, never of the form /.../message/{id}. In that case, I am wondering if being restricted to the /.../message route scheme automatically means POST should be used.

In such a case PUT is not an option for you unless that request contains all the messages that should be available after the request was processed. The semantics of PUT are defined as replacing the current representation stored on the target resource with the one provided in the request payload. So, if you send a PUT request to a "collection resource" you'd technically replace all of the messages currently available with the ones defined in the request.

Body:
Imagine an HTTP REST endpoint, where a resource is inserted, and that the resource is understood to be a "message".  Each individual message is identified by a unique identifier, such as a GUID value of some sort.  The same message cannot be duplicated.

Now, in a lot of cases, that would lend itself to the PUT verb, since it's idempotent.  However consider the following scenario:

1. The sender sends this message to the receiver:

    {
        "id": 123,
        "text": "original text"
    }

2. Now the receiver has this value for the message stored in its database:

    {
        "id": 123,
        "text": "original text"
    }

3. For whatever reason, the sender tries to send the same message again, but with amended
   text:

    {
        "id": 123,
        "text": "amended text"
    }

4. The receiver receives that as well, but since the id field is the same as before, no
   action is taken, and this is what the receiver still has in its database:

    {
        "id": 123,
        "text": "original text"
    }

The reason for the receiver's behavior is that each distinct message is to be uniquely identified by its id field, and that if another message is sent with the same id, it is simply considered a duplicate.  Furthermore, trying to change the message's contents like that and resend it with the same ID is invalid behavior on the sender's end.

So technically this is idempotent, which usually leans toward PUT.  However updates are not allowed in any context here, simply inserts.  So do we choose PUT or POST, or does it even matter?  PUT is supposed to be the full representation of the resource, but if it's simply discarded, is it okay to still return a 2xx response?

For the purposes of this question, assume that the route used is always of the form <host>/.../message, never of the form <host>/.../message/{id}.  In that case, I am wondering if being restricted to the <host>/.../message route scheme automatically means POST should be used.

Body:
Imagine an HTTP REST endpoint,  ...

According to Fielding himself

There is no such thing as a REST endpoint. There are resources. A countably infinite set of resources bound only by restrictions on URL length. (Source)

So technically this is idempotent, which usually leans toward either PUT or PATCH ...

Idempotency is an important property to a client in regards to temporary network issues which allows it to automatically resend the request in case it did not receive a response within a reasonable amount of time. In such a case a client does not know whether the initial request received the server at all or just the response got lost. Idempotency has nothing to do with your demand to only allow to write to a resource only once. In addition to that, PATCH is not idempotent by default. Idempotent just means that processing a request always results in the same outcome, regardless how many times you send that request to the server.

Each individual message is identified by a unique identifier, such as a GUID value of some sort

... each distinct message is to be uniquely identified by its id field, and that if another message is sent with the same id, it is simply considered a duplicate.

A resource always is uniquely identifiable via its URI as a URI itself can only reference one single resource. A single resource however may have multiple URIs, i.e. one with an other without query parameters available. URI is an abbreviation for uniform resource identifier, where uniform denotes to remaining the same in all cases and at all times. This makes the requirement for the id  field in my opinion redundant.

As far as I understood your question, the actual text of the message does not define whether a message is a duplicate or not. So basically

PUT /messages/eaff31bd-5291-4287-a7dd-fbe5b1e47b67 HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
...

{
  "text": "original text"
}

and

PUT /messages/eb1db214-d231-4a50-916c-8de2d64c7d3a HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
...

{
  "text": "original text"
}

are requests for two different messages as they target different resources, while you don't want to allow something like

PUT /messages/eaff31bd-5291-4287-a7dd-fbe5b1e47b67 HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
...

{
  "text": "amended text"
}

as this would update an existing message.

In such a case I'd disable PUT completely for messages by not supporting it while allowing the creation of new messages only via POST. A request/response sample may look like this:

POST /messages HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
Accept: application/json
...

{
  "text": "Some other text"
}

which may yield a response such as:

HTTP/1.1 201 Created
Content-Type: application/json; charset="utf-8"
Location: http://www.acme.com/messages/740177d2-1de9-41bd-bd5b-6a52f39bf227
Etag: 33a64df551425fcc55e4d42a148795d9f25f89d4

{
  "text": "some other text"
}

Attempting to update such a resource via

PUT /messages/740177d2-1de9-41bd-bd5b-6a52f39bf227 HTTP/1.1
Host: www.acme.com
Content-Type: application/json; charset="utf-8"
Etag: 33a64df551425fcc55e4d42a148795d9f25f89d4

{
  "text": "updated text"
}

should result in a

HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD

response, which states that a server knows the indicated PUT operation but does not support that operation on the target resource. The mandatory Allow header furthermore teaches your client about the valid HTTP operations supported by that resource.

For the purposes of this question, assume that the route used is always of the form /.../message, never of the form /.../message/{id}. In that case, I am wondering if being restricted to the /.../message route scheme automatically means POST should be used.

In such a case PUT is not an option for you unless that request contains all the messages that should be available after the request was processed. The semantics of PUT are defined as replacing the current representation stored on the target resource with the one provided in the request payload. So, if you send a PUT request to a "collection resource" you'd technically replace all of the messages currently available with the ones defined in the request.


问:
How to find all symlinks in directory and its subdirectories in python
I need to list symlinks using python. Broken aswell

How do I do it? I was searching everywhere and tried alot.

The best result I found was:

```<code>import os,sys
print '\n'.join([os.path.join(sys.argv[1],i)
    for i in os.listdir(sys.argv[1]) if
    os.path.islink(os.path.join(sys.argv[1],i))])
</code>```

It does not show where its linked to and it doesn't go to subdirs.

答:
You can use a code similar to this one to achieve what you need. Directories to search are passed as arguments or current directory taken as the default. You can modify this further with the os.walk method to make it recursive.

```<code>import sys, os

def lll(dirname):
    for name in os.listdir(dirname):
        if name not in (os.curdir, os.pardir):
            full = os.path.join(dirname, name)
            if os.path.isdir(full) and not os.path.islink(full):
                lll(full)
            elif os.path.islink(full):
                print(name, '->', os.readlink(full))
def main(args):
    if not args: args = [os.curdir]
    first = 1
    for arg in args:
        if len(args) > 1:
            if not first: print()
            first = 0
            print(arg + ':')
        lll(arg)

if __name__ == '__main__':
    main(sys.argv[1:])
</code>```

Ref: https://github.com/python/cpython/blob/master/Tools/scripts/lll.py

Body:
I need to list symlinks using python. Broken aswell

How do I do it? I was searching everywhere and tried alot.

The best result I found was:

import os,sys
print '\n'.join([os.path.join(sys.argv[1],i)
    for i in os.listdir(sys.argv[1]) if
    os.path.islink(os.path.join(sys.argv[1],i))])

It does not show where its linked to and it doesn't go to subdirs.

Body:
You can use a code similar to this one to achieve what you need. Directories to search are passed as arguments or current directory taken as the default. You can modify this further with the os.walk method to make it recursive.

import sys, os

def lll(dirname):
    for name in os.listdir(dirname):
        if name not in (os.curdir, os.pardir):
            full = os.path.join(dirname, name)
            if os.path.isdir(full) and not os.path.islink(full):
                lll(full)
            elif os.path.islink(full):
                print(name, '->', os.readlink(full))
def main(args):
    if not args: args = [os.curdir]
    first = 1
    for arg in args:
        if len(args) > 1:
            if not first: print()
            first = 0
            print(arg + ':')
        lll(arg)

if __name__ == '__main__':
    main(sys.argv[1:])

Ref: https://github.com/python/cpython/blob/master/Tools/scripts/lll.py


问:
Oracle issue with concat()
```<code>SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME," ",LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES
</code>```

I tried running the above code and it's giving me error ( invalid number of arguments ) for concatenation. I am trying to add a space between FIRST_NAME and LAST_NAME.

答:
The error you get suggests you're using Oracle as DBMS, but not MySQL, and getting error code ORA-00909.

At Most two arguments can be put in the Oracle's CONCAT() function, and using double quotes are prohibited within that, single quotes might be used , instead. So, in your case, try to use as

```<code>SELECT EMPLOYEE_ID, CONCAT(CONCAT(FIRST_NAME,' '),LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
  FROM EMPLOYEES
</code>```

or pipes as concatenetion operators

```<code>SELECT EMPLOYEE_ID, FIRST_NAME||' '||LAST_NAME AS EMPLOYEE_NAME, HIRE_DATE
  FROM EMPLOYEES
</code>```

Title: Oracle issue with concat()

Body:
SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME," ",LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES

I tried running the above code and it's giving me error ( invalid number of arguments ) for concatenation. I am trying to add a space between FIRST_NAME and LAST_NAME.

Body:
The error you get suggests you're using Oracle as DBMS, but not MySQL, and getting error code ORA-00909.

At Most two arguments can be put in the Oracle's CONCAT() function, and using double quotes are prohibited within that, single quotes might be used , instead. So, in your case, try to use as

SELECT EMPLOYEE_ID, CONCAT(CONCAT(FIRST_NAME,' '),LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
  FROM EMPLOYEES

or pipes as concatenetion operators

SELECT EMPLOYEE_ID, FIRST_NAME||' '||LAST_NAME AS EMPLOYEE_NAME, HIRE_DATE
  FROM EMPLOYEES


问:
Nginx Redirect based on what is contained in the url
I am a noob when it comes to redirect and rewrites and such...  My goal is to do a redirect based on what is sent to the server.
Example of the urls that will be sent:

https://example.org/git/#123

https://example.org/git/!123

and redirect to url based if ! or # is part of it
if ! then it would go to
https://git.example2.com/userhere/repohere/merge_requests/123
if # then it would go to
https://git.example2.com/userhere/repohere/issues/123

Some help with a nginx location block would be nice.

答:
You can’t match #123. So you need to use different character i.e &

Use below sample rule.

```<code>if ($request_uri ~ "^(.*)/!123)"{
return 301 https://git.example2.com/userhere/repohere/merge_requests/123;
}
if ($request_uri ~ "^(.*)/!456)"{
return 301 https://git.example2.com/userhere/repohere/merge_requests/456;
}
</code>```

Body:
You can’t match #123. So you need to use different character i.e &

Use below sample rule.

if ($request_uri ~ "^(.*)/!123)"{
return 301 https://git.example2.com/userhere/repohere/merge_requests/123;
}
if ($request_uri ~ "^(.*)/!456)"{
return 301 https://git.example2.com/userhere/repohere/merge_requests/456;
}


问:
Adding a grandchild to a stacklayout via c# xamarin forms
I have this code:

```<code>stackRecentList.Children.Add(
                    new Frame {
                        BackgroundColor = Color.White,
                        Margin = new Thickness(30, 20, 30, 0),
                        Padding = new Thickness(10),
                        CornerRadius = 5,
                        HasShadow = true
                    }
                );
</code>```

Basically I am adding a <Frame> to my stacklayout. I want to add a  to that <Frame> there for it becomes the <StackLayout>'s grandchild. How do I do it in Xamarin Forms Android?

答:
Generally speaking a StackLayout has only its Children to care of, and it's now every child task to organize its own children. Now your frame has to care of its children by itself.

A Frame has a unique property: Content.

Follow this snippet to create your UI in code behind:

```<code> Frame frame = new Frame
            {
                BackgroundColor = Color.White,
                Margin = new Thickness(30, 20, 30, 0),
                Padding = new Thickness(10),
                CornerRadius = 5,
                HasShadow = true
            };

            var sl = new StackLayout();
            sl.Children.Add(new Label() { Text = "test" });

            frame.Content = sl;

            stackRecentList.Children.Add(
                    frame
                );
</code>```

I recommand you to add a StackLayout to Frame's Content(Do not add the Label to Frame's Content directly, If you have other controls want to add the Frame in later).

Here is running screenshot.

Body:
I have this code:

stackRecentList.Children.Add(
                    new Frame {
                        BackgroundColor = Color.White,
                        Margin = new Thickness(30, 20, 30, 0),
                        Padding = new Thickness(10),
                        CornerRadius = 5,
                        HasShadow = true
                    }
                );

Basically I am adding a <Frame> to my stacklayout. I want to add a  to that <Frame> there for it becomes the <StackLayout>'s grandchild. How do I do it in Xamarin Forms Android?

Body:
Generally speaking a StackLayout has only its Children to care of, and it's now every child task to organize its own children. Now your frame has to care of its children by itself.

A Frame has a unique property: Content.

Follow this snippet to create your UI in code behind:

 Frame frame = new Frame
            {
                BackgroundColor = Color.White,
                Margin = new Thickness(30, 20, 30, 0),
                Padding = new Thickness(10),
                CornerRadius = 5,
                HasShadow = true
            };

            var sl = new StackLayout();
            sl.Children.Add(new Label() { Text = "test" });

            frame.Content = sl;

            stackRecentList.Children.Add(
                    frame
                );

I recommand you to add a StackLayout to Frame's Content(Do not add the Label to Frame's Content directly, If you have other controls want to add the Frame in later).

Here is running screenshot.


问:
Show Only One Value In Dropdown If There are Duplicates
Hi i'm trying to get the information of printers by the location. so if i have few printers at the same location ill see them both at the dropdown but i actually want to see only one location on the dropdown if they are the same location.
i know i can solve this in the database level and add relationships but maybe there is a way to do it without it ?

import {
  Component,
  OnInit
} from '@angular/core';
import {
  HttpClient
} from '@angular/common/http';
import {
  DomSanitizer
} from '@angular/platform-browser';
import {
  Values
} from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) {}

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><H2>Printer Manager</H2>
<div id="selectCompanyDiv">
  <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
    <label for="">Select Location</label>
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each.location">{{each.location}} </option>
      <!-- {{each.specificLocation}} -->
    </select>
    <!-- Search -->
    <!-- <input id="test" *ngFor="let each of values " class="form-control" type="search" placeholder="Search"  {{values.location}}>

         <button ondblclick="Access()">click here
        </button> -->
  </div>
  <br>
  <br>
  <div>
    <div *ngFor="let value of values" id="mainDiv">
      <div *ngIf="value.location===selectedPrinter">
        <span>HostName: {{value.hostName}}</span>
        <br>
        <!-- <span>Location: {{value.location}}</span> -->

        <span>Manufacturer: {{value.manufacturer}}</span>
        <br>
        <span>IP: {{value.ip}}</span>
        <br>
        <h2>{{value.location}}</h2>
        <span>{{value.specificLocation}}</span>
        <br>
        Full view
        <div>
          <div *ngIf="value.model==='J480'" class="outerFrame">
            <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrotherj480" scrolling="no"></iframe>
          </div>
          <div *ngIf="value.model==='6530DW'" class="outerFrame">
            <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
          </div>
        </div>
      </div>
    </div></code>```

答:
What i would do is the following:

In getValues():

```<code> getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = Array.from(new Set(response));
    }, error => {
      console.log(error);
    })
  }
</code>```

Take a look at Array.from documentation and Array.from(set)

Good luck!

Body:
Hi i'm trying to get the information of printers by the location. so if i have few printers at the same location ill see them both at the dropdown but i actually want to see only one location on the dropdown if they are the same location.
i know i can solve this in the database level and add relationships but maybe there is a way to do it without it ?

import {
  Component,
  OnInit
} from '@angular/core';
import {
  HttpClient
} from '@angular/common/http';
import {
  DomSanitizer
} from '@angular/platform-browser';
import {
  Values
} from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) {}

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}

Printer Manager

    Select Location
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each.location">{{each.location}} </option>

    </select>

        HostName: {{value.hostName}}

        Manufacturer: {{value.manufacturer}}

        IP: {{value.ip}}

{{value.location}}

        {{value.specificLocation}}

        Full view

Body:
What i would do is the following:

In getValues():

 getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = Array.from(new Set(response));
    }, error => {
      console.log(error);
    })
  }

Take a look at Array.from documentation and Array.from(set)

Good luck!


问:
How to export Oracle database as system user with os authentication?
User oracle is configured with os authentication and logged in as oracle.

I am trying to to take full db export using the following expression:

exp 'system/as sysdba' file='full_exp.dmp' log='full_exp.log'  consistent='y'

but getting error:

LRM-00108: Invalid positional parameter value 'sysdba'

Also tried with:

exp 'system' file='full_exp.dmp' log='full_exp.log'  consistent='y'

Asks for password for system and empty password doesn't work, throws errors EXP-00004, EXP-00056 and ORA-01017.

Please guide me in taking full db export by os authenticated user.

答:
To use Oracle OS authentification for a non SYSDBA connection, you just need to connect with the OS account that is mapped to the Oracle account and use / as user/password:

```<code>sqlplus /
expdp / ...
</code>```

See details for Unix and Windows in
https://oracle-base.com/articles/misc/os-authentication

Body:
To use Oracle OS authentification for a non SYSDBA connection, you just need to connect with the OS account that is mapped to the Oracle account and use / as user/password:

sqlplus /
expdp / ...

See details for Unix and Windows in
https://oracle-base.com/articles/misc/os-authentication


问:
Why do these two NHibernate queries produce different results?
This is for a M:N relationship, with the collection being mapped in NHibernate as a Set.

The criteria query we were using previously "worked" but it did not populate the Skills collection properly, in that only the first/looking-for skill was brought down, even if the employee had multiple skills.

I changed it to a LINQ query and it fixes the issue, properly fetching all the skills of that employee.

Dim sId = 1 ' Just to have one for example
Dim lstEmployees = Session.CreateCriteria(Of Employee)() _
                    .CreateAlias("Skills", "s", NHibernate.SqlCommand.JoinType.LeftOuterJoin) _
                    .Add(Expression.Or(Expression.Eq("PrimarySkillId", sId),
                                       Expression.Eq("s.Id", sId))) _
                    .SetResultTransformer(New DistinctRootEntityResultTransformer()) _
                    .List(Of Employee)()

' Returns correct employees but only their first skill in the Skills collection, even if they have more than one

Dim lstEmployees = (From e In Session.Query(Of Employee)()
                  Where e.PrimarySkillId =sId OrElse e.Skills.Any(Function(s) s.Id = sId)
                  Select e Distinct).Fetch(Function(e) e.Skills).ToList()

' Returns correct employees and their Skills collection contains all of their skills
```

Does anyone understand what's different about the two seemingly-equivalent queries?

答:
Off the bat, the first query is doing the distinct separation after retrieving all rows, while the second query actually does a select distinct .... What's likely happening is that it hydrates the Employee model with just the one Skill retrieved

To make the first query actually do a select distinct ... you will need to use projections.

Something like

Session.CreateCriteria(Of Employee)() _
       .CreateAlias("Skills", "s", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
       .Add(Expression.Or(Expression.Eq("PrimarySkillId", sId),
                          Expression.Eq("s.Id", sId))) _
       .SetProjection(Projections.Distinct("Id")) _
       .SetFetchMode("s", FetchMode.Eager)
```

<p>may work. Alternatively you can try to just set the fetch mode with the DistinctRootEntityResultTransformer</p>

<pre class="lang-vb prettyprint-override"><code>Session.CreateCriteria(Of Employee)() _
       .CreateAlias("Skills", "s", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
       .Add(Expression.Or(Expression.Eq("PrimarySkillId", sId),
                          Expression.Eq("s.Id", sId))) _
       .SetResultTransformer(Transformers.DistinctRootEntityResultTransformer) _
       .SetFetchMode("s", FetchMode.Eager)
</code>```

Body:
This is for a M:N relationship, with the collection being mapped in NHibernate as a Set.

The criteria query we were using previously "worked" but it did not populate the Skills collection properly, in that only the first/looking-for skill was brought down, even if the employee had multiple skills.

I changed it to a LINQ query and it fixes the issue, properly fetching all the skills of that employee.

Dim sId = 1 ' Just to have one for example
Dim lstEmployees = Session.CreateCriteria(Of Employee)() _
                    .CreateAlias("Skills", "s", NHibernate.SqlCommand.JoinType.LeftOuterJoin) _
                    .Add(Expression.Or(Expression.Eq("PrimarySkillId", sId),
                                       Expression.Eq("s.Id", sId))) _
                    .SetResultTransformer(New DistinctRootEntityResultTransformer()) _
                    .List(Of Employee)()

' Returns correct employees but only their first skill in the Skills collection, even if they have more than one

Dim lstEmployees = (From e In Session.Query(Of Employee)()
                  Where e.PrimarySkillId =sId OrElse e.Skills.Any(Function(s) s.Id = sId)
                  Select e Distinct).Fetch(Function(e) e.Skills).ToList()

' Returns correct employees and their Skills collection contains all of their skills

Does anyone understand what's different about the two seemingly-equivalent queries?

Body:
Off the bat, the first query is doing the distinct separation after retrieving all rows, while the second query actually does a select distinct .... What's likely happening is that it hydrates the Employee model with just the one Skill retrieved

To make the first query actually do a select distinct ... you will need to use projections.

Something like

Session.CreateCriteria(Of Employee)() _
       .CreateAlias("Skills", "s", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
       .Add(Expression.Or(Expression.Eq("PrimarySkillId", sId),
                          Expression.Eq("s.Id", sId))) _
       .SetProjection(Projections.Distinct("Id")) _
       .SetFetchMode("s", FetchMode.Eager)

may work. Alternatively you can try to just set the fetch mode with the DistinctRootEntityResultTransformer

Session.CreateCriteria(Of Employee)() _
       .CreateAlias("Skills", "s", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
       .Add(Expression.Or(Expression.Eq("PrimarySkillId", sId),
                          Expression.Eq("s.Id", sId))) _
       .SetResultTransformer(Transformers.DistinctRootEntityResultTransformer) _
       .SetFetchMode("s", FetchMode.Eager)


问:
Check if a word is enclosed within quotes using javascript
I have a string like get(3,"No MATCH",obj). I want to check if the word MATCH is enclosed within quotes (either single quote or double quote). Here MATCH is enclosed within quotes, although not exactly as "MATCH", it is still a part of the text contained in quotes as "No MATCH".

I want to write a function which takes the word (MATCH) as argument and returns true if it is contained within quotes or false if not.

Following are some other input strings which needs to be checked by this
function:

* get(1101,"MATCH",obj) --> return true since MATCH is within quotes

* get(255,'NO MATCH',obj) --> return true since MATCH is a part of text contained within quotes

* get(1111,"" , MATCH) ---> return false since MATCH is not contained within quotes

答:
I guess this is for refactoring, so this should do

no mismatching quotes (maybe except ill stuff like 'MAT\'CH' or 'MAT' + 'CH'

single or double quotes

Left handled cases can be handled by hand

const inString = s => line => {
  const has = [...line.matchAll(/'[^']*'/g)].find(x => x[0].includes(s))
  return has || [...line.matchAll(/"[^"]*"/g)].find(x => x[0].includes(s))
}
const matcher = inString('MATCH')
console.log(matcher('get(1101,"MATCH",obj)'))
console.log(matcher("get(255,'YES MATCH',obj)"))
console.log(matcher('get(1111,"" , NO MATCH)')) // not in quotes
console.log(matcher('get(1111,"" , "NO MATCH\')')) // no mismatching quotes
console.log(matcher("get('a',NO MATCH , 'b')")) // wrapped by matching quotes does not match```


问:
Angular mat-table pagination not working, entire data is loaded on First page of mat-table
I have use Angular Material table, i have bind data source from ts file,but all the data is loaded on very first page, pagination is not working.I have two more table, which are on same page,same problem for other tables too.

I have tried

```<code>setTimeout(() => this.dataSource.paginator = this.paginator);
</code>```

and

```<code>ngAfterViewInit() {
   this.dataSource.paginator = this.paginator
}
</code>```

HTML:

```<code>    <mat-table class="mt-4 table-container" fxFlex="100" [dataSource]="allUsers">
      <ng-container matColumnDef="checked">
        <mat-header-cell fxFlex="10" (click)="selectAllUsers()" *matHeaderCellDef>
          <mat-checkbox [(ngModel)]="checkedAllUsers"></mat-checkbox>
        </mat-header-cell>
        <mat-cell fxFlex="10" *matCellDef="let element">
          <mat-checkbox [(ngModel)]="element.checked"></mat-checkbox>
        </mat-cell>
      </ng-container>

      <ng-container matColumnDef="firstName">
        <mat-header-cell fxFlex="25" *matHeaderCellDef> First Name </mat-header-cell>
        <mat-cell fxFlex="25" *matCellDef="let element"> {{element.firstName}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="lastName">
        <mat-header-cell fxFlex="25" *matHeaderCellDef> Last Name </mat-header-cell>
        <mat-cell fxFlex="25" *matCellDef="let element"> {{element.lastName}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="email">
        <mat-header-cell fxFlex="30" *matHeaderCellDef> Email </mat-header-cell>
        <mat-cell fxFlex="30" *matCellDef="let element"> {{element.email}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="actions">
        <mat-header-cell fxFlex="10" *matHeaderCellDef> Action </mat-header-cell>
        <mat-cell fxFlex="10" *matCellDef="let row; let i=index;">
          <button mat-icon-button class="viewButton" (click)="view(i, row.id, row.title, row.state, row.url, row.created_at, row.updated_at)">
            <mat-icon aria-label="Delete">remove_red_eye</mat-icon>
          </button>
        </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="allUsersColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: allUsersColumns;"></mat-row>
    </mat-table>
    <mat-paginator #allUsersPaginatorr [pageSizeOptions]="[10,20,30]" showFirstLastButtons></mat-paginator>
</code>```

TS Code:

```<code> @ViewChild(MatPaginator) paginator: MatPaginator;

 allUsersColumns: string[] = ['checked', 'firstName', 'lastName', 'email',
'actions'];
allUsersDataSource = new MatTableDataSource<any>();
 allUsers: any[] = [
{ checked: false, firstName: 'Debi', lastName: 'Austin', email:
 'd@gmail.com' },
  { checked: false, firstName: 'Jimmy', lastName: 'Williams', email:
 'w@yahoo.in' },
  { checked: false, firstName: 'Randy', lastName: 'Waif', email:
 'randy@gmail.com' },
  { checked: true, firstName: 'Chad', lastName: 'Spongla', email:
   'c@redif.com' },
   { checked: false, firstName: 'Debi', lastName: 'Austin', email:
  'd@gmail.com' },
  { checked: false, firstName: 'Jimmy', lastName: 'Williams', email:
  'w@yahoo.in' },
  { checked: false, firstName: 'Randy', lastName: 'Waif', email:
  'randy@gmail.com' },
  { checked: false, firstName: 'Chad', lastName: 'Spongla', email:
 'c@redif.com' },
  { checked: false, firstName: 'Debi', lastName: 'Austin', email:
 'd@gmail.com' },
    { checked: true, firstName: 'Jimmy', lastName: 'Williams', email:
 'w@yahoo.in' },
  { checked: false, firstName: 'Chad', lastName: 'Spongla', email:
 'c@redif.com' },
  { checked: false, firstName: 'Debi', lastName: 'Austin', email:
 'd@gmail.com' },
  { checked: true, firstName: 'Jimmy', lastName: 'Williams', email:
 'w@yahoo.in' }
 ];
ngOnInit() {
 this.allUsersDataSource = new MatTableDataSource(this.allUsers);
  this.allUsersDataSource.paginator = this.paginator;
}
</code>```

答:
You should to initialize paginator like this:</p>

```<code>@ViewChild(MatPaginator, {static: true}) set matPaginator(paginator: MatPaginator) {
    this.dataSource.paginator = paginator;
}
</code>```

Body:
I have use Angular Material table, i have bind data source from ts file,but all the data is loaded on very first page, pagination is not working.I have two more table, which are on same page,same problem for other tables too.

I have tried

setTimeout(() => this.dataSource.paginator = this.paginator);

and

ngAfterViewInit() {
   this.dataSource.paginator = this.paginator
}

HTML:

    <mat-table class="mt-4 table-container" fxFlex="100" [dataSource]="allUsers">
      <ng-container matColumnDef="checked">
        <mat-header-cell fxFlex="10" (click)="selectAllUsers()" *matHeaderCellDef>
          <mat-checkbox [(ngModel)]="checkedAllUsers"></mat-checkbox>
        </mat-header-cell>
        <mat-cell fxFlex="10" *matCellDef="let element">
          <mat-checkbox [(ngModel)]="element.checked"></mat-checkbox>
        </mat-cell>
      </ng-container>

      <ng-container matColumnDef="firstName">
        <mat-header-cell fxFlex="25" *matHeaderCellDef> First Name </mat-header-cell>
        <mat-cell fxFlex="25" *matCellDef="let element"> {{element.firstName}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="lastName">
        <mat-header-cell fxFlex="25" *matHeaderCellDef> Last Name </mat-header-cell>
        <mat-cell fxFlex="25" *matCellDef="let element"> {{element.lastName}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="email">
        <mat-header-cell fxFlex="30" *matHeaderCellDef> Email </mat-header-cell>
        <mat-cell fxFlex="30" *matCellDef="let element"> {{element.email}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="actions">
        <mat-header-cell fxFlex="10" *matHeaderCellDef> Action </mat-header-cell>
        <mat-cell fxFlex="10" *matCellDef="let row; let i=index;">
          <button mat-icon-button class="viewButton" (click)="view(i, row.id, row.title, row.state, row.url, row.created_at, row.updated_at)">
            <mat-icon aria-label="Delete">remove_red_eye</mat-icon>
          </button>
        </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="allUsersColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: allUsersColumns;"></mat-row>
    </mat-table>
    <mat-paginator #allUsersPaginatorr [pageSizeOptions]="[10,20,30]" showFirstLastButtons></mat-paginator>

TS Code:

 @ViewChild(MatPaginator) paginator: MatPaginator;

 allUsersColumns: string[] = ['checked', 'firstName', 'lastName', 'email',
'actions'];
allUsersDataSource = new MatTableDataSource<any>();
 allUsers: any[] = [
{ checked: false, firstName: 'Debi', lastName: 'Austin', email:
 'd@gmail.com' },
  { checked: false, firstName: 'Jimmy', lastName: 'Williams', email:
 'w@yahoo.in' },
  { checked: false, firstName: 'Randy', lastName: 'Waif', email:
 'randy@gmail.com' },
  { checked: true, firstName: 'Chad', lastName: 'Spongla', email:
   'c@redif.com' },
   { checked: false, firstName: 'Debi', lastName: 'Austin', email:
  'd@gmail.com' },
  { checked: false, firstName: 'Jimmy', lastName: 'Williams', email:
  'w@yahoo.in' },
  { checked: false, firstName: 'Randy', lastName: 'Waif', email:
  'randy@gmail.com' },
  { checked: false, firstName: 'Chad', lastName: 'Spongla', email:
 'c@redif.com' },
  { checked: false, firstName: 'Debi', lastName: 'Austin', email:
 'd@gmail.com' },
    { checked: true, firstName: 'Jimmy', lastName: 'Williams', email:
 'w@yahoo.in' },
  { checked: false, firstName: 'Chad', lastName: 'Spongla', email:
 'c@redif.com' },
  { checked: false, firstName: 'Debi', lastName: 'Austin', email:
 'd@gmail.com' },
  { checked: true, firstName: 'Jimmy', lastName: 'Williams', email:
 'w@yahoo.in' }
 ];
ngOnInit() {
 this.allUsersDataSource = new MatTableDataSource(this.allUsers);
  this.allUsersDataSource.paginator = this.paginator;
}

Body:
You should to initialize paginator like this:

@ViewChild(MatPaginator, {static: true}) set matPaginator(paginator: MatPaginator) {
    this.dataSource.paginator = paginator;
}


问:
How to add a download button or custom layout in center of progress bar?
I want to create a custom progress bar to display downloading progress with an icon and textview in center of it.

There are libraries and some samples but only with textview inside progress bar so how do i add this imageview also? Please help.

答:
You can create a custom layout that contains your progressBar, textView and imageView.

layout_custom_progressbar.xml

```<code><xml version="1.0" encoding="utf-8"?>
   <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@color/white">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:progressBackgroundTint="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download PDF"
        android:textColor="@color/textColorPrimary"
        android:textSize="18sp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Then add this layout in your desired activity using  tag and show or hide it using visibility property.

```<code><include
    android:id="@+id/progressBar"
    layout="@layout/layout_custom_progressbar"
    android:visibility="gone"/>
</code>```

Body:
You can create a custom layout that contains your progressBar, textView and imageView.

layout_custom_progressbar.xml

<xml version="1.0" encoding="utf-8"?>
   <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@color/white">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:progressBackgroundTint="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download PDF"
        android:textColor="@color/textColorPrimary"
        android:textSize="18sp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Then add this layout in your desired activity using  tag and show or hide it using visibility property.

<include
    android:id="@+id/progressBar"
    layout="@layout/layout_custom_progressbar"
    android:visibility="gone"/>