问:
spring + hibernate configuration error ? XML document from class path resource [spring.xml] is invalid
i am currently trying to configure spring with hibernate in a maven project (webapp). However, I have an error that I have not been able to resolve for 2 weeks.

pom.xml :

```<code> <?xml version="1.0" encoding="UTF-8"?>

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.oc</groupId>
  <artifactId>nom</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>nom Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.2.1.RELEASE</spring.version>
    <hibernate.version>5.4.10.Final</hibernate.version>
    <!-- Logging -->
    <logback.version>1.0.13</logback.version>
    <slf4j.version>1.7.5</slf4j.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-framework-bom</artifactId>
      <version>${spring.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.2.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.17</version>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>${logback.version}</version>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>nom</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
</code>```

spring.xml :

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://springframework.org/schema/beans/spring-beans-5.2.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/db_person" />
        <property name="username" value="root" />
        <property name="password" value="0324" />
    </bean>

    <!-- Hibernate 5 XML SessionFactory Bean definition-->
        <bean id="hibernate5SessionFactory"
            class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="mappingResources">
                <list>
                    <value>person.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.MySQLDialect
                </value>
            </property>
        </bean>

    <!-- Hibernate 5 Annotation SessionFactory Bean definition-->
    <bean id="hibernate5AnnotatedSessionFactory"
          class="org.springframework.orm.hibernate5.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.oc.model.Person</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>

    <bean id="personDAO" class="com.oc.dao.PersonDAOImpl">
        <property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
    </bean>
</beans>
</code>```

person.hbm.xml :

```<code><?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name = "com.oc.model.Person" table = "person">

        <meta attribute = "class-description">
            This class contains the employee detail.
        </meta>

        <id name = "id" type = "int" column = "id">
            <generator class="native"/>
        </id>

        <property name = "name" column = "name" type = "string"/>
        <property name = "country" column = "country" type = "string"/>

    </class>
</hibernate-mapping>
</code>```

Person.java :

```<code>package com.oc.model;

import javax.persistence.*;

@Entity
@Table(name ="Person")
public class Person {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    private String country;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString(){
        return "id="+id+", name="+name+", country="+country;
    }
}
</code>```

Main.java :

```<code>package com.oc.main;

import com.oc.dao.PersonDAO;
import com.oc.model.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Main {
        public static void main(String[] args) {

            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

            PersonDAO personDAO = context.getBean(PersonDAO.class);

            Person person = new Person();
            person.setName("geo"); person.setCountry("france");

            personDAO.save(person);

            System.out.println("Person::"+person);

            List<Person> list = personDAO.list();

            for(Person p : list){
                System.out.println("Person List::"+p);
            }
            //close resources
            context.close();
        }

}
</code>```

the project organization

When compiling the main.java, I get the following error:

```<code>Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 5 in XML document from class path resource [spring.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 68; cvc-elt.1.a : Déclaration de l'élément 'beans' introuvable.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:405)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:337)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:305)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:224)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:195)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:257)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:128)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:637)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:522)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
    at com.oc.main.Main.main(Main.java:12)
Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 68; cvc-elt.1.a : Déclaration de l'élément 'beans' introuvable.
    at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
    at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:135)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
    at java.xml/com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2132)
    at java.xml/com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:829)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:836)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:246)
    at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:77)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:435)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:393)
    ... 14 more
</code>```

Can you help me solve my problem?

答:
According to this article Spring bean – XML config

instead of

```<code><dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.2.2.RELEASE</version>
</dependency>
</code>```

try to insert this

```<code>    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
</code>```

Body:
i am currently trying to configure spring with hibernate in a maven project (webapp). However, I have an error that I have not been able to resolve for 2 weeks.

pom.xml :

 <?xml version="1.0" encoding="UTF-8"?>

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.oc</groupId>
  <artifactId>nom</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>nom Maven Webapp</name>

  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.2.1.RELEASE</spring.version>
    <hibernate.version>5.4.10.Final</hibernate.version>

    <logback.version>1.0.13</logback.version>
    <slf4j.version>1.7.5</slf4j.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-framework-bom</artifactId>
      <version>${spring.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.2.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.17</version>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>${logback.version}</version>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>nom</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>

        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

spring.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://springframework.org/schema/beans/spring-beans-5.2.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/db_person" />
        <property name="username" value="root" />
        <property name="password" value="0324" />
    </bean>

        <bean id="hibernate5SessionFactory"
            class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="mappingResources">
                <list>
                    <value>person.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.MySQLDialect
                </value>
            </property>
        </bean>

    <bean id="hibernate5AnnotatedSessionFactory"
          class="org.springframework.orm.hibernate5.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.oc.model.Person</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>

    <bean id="personDAO" class="com.oc.dao.PersonDAOImpl">
        <property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
    </bean>
</beans>

person.hbm.xml :

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name = "com.oc.model.Person" table = "person">

        <meta attribute = "class-description">
            This class contains the employee detail.
        </meta>

        <id name = "id" type = "int" column = "id">
            <generator class="native"/>
        </id>

        <property name = "name" column = "name" type = "string"/>
        <property name = "country" column = "country" type = "string"/>

    </class>
</hibernate-mapping>

Person.java :

package com.oc.model;

import javax.persistence.*;

@Entity
@Table(name ="Person")
public class Person {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    private String country;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString(){
        return "id="+id+", name="+name+", country="+country;
    }
}

Main.java :

package com.oc.main;

import com.oc.dao.PersonDAO;
import com.oc.model.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Main {
        public static void main(String[] args) {

            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

            PersonDAO personDAO = context.getBean(PersonDAO.class);

            Person person = new Person();
            person.setName("geo"); person.setCountry("france");

            personDAO.save(person);

            System.out.println("Person::"+person);

            List<Person> list = personDAO.list();

            for(Person p : list){
                System.out.println("Person List::"+p);
            }
            //close resources
            context.close();
        }

}

the project organization

When compiling the main.java, I get the following error:

Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 5 in XML document from class path resource [spring.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 68; cvc-elt.1.a : Déclaration de l'élément 'beans' introuvable.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:405)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:337)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:305)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:224)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:195)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:257)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:128)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:637)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:522)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
    at com.oc.main.Main.main(Main.java:12)
Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 68; cvc-elt.1.a : Déclaration de l'élément 'beans' introuvable.
    at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
    at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:135)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
    at java.xml/com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2132)
    at java.xml/com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:829)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:836)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:246)
    at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:77)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:435)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:393)
    ... 14 more

Can you help me solve my problem?

Body:
According to this article Spring bean – XML config

instead of

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.2.2.RELEASE</version>
</dependency>

try to insert this

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>


来源: stackexchange

问:
Google Script - Appending google spreadsheet in async mode
I created a function to append an array to a google spreadsheet. Usually, my array has more than 5 items. In the client side, I group the data in a array and I send to the server using the "google.script.run.myFunction(params)". Then, I use a loop structure to do this in the server side. I belive my client side is running even the server side doesn't ended the job.
How I could to do to the client side waits the server side to finish the run?

At least, my server side also running an append to the spreadsheet without to wait the run finish.

My function in the client side:

```<code>function sendArr(){
          var userInfo = {};
          var arr = new Array();
          var localTable = "";
          var gravar = 0;

          try{

            localTable = document.getElementById("scheduleTable");

            if(document.getElementById("repNome").value === "") {
              throw new Error();
            }

            if(document.getElementById("yearSchedule").value === ""){
              throw new Error();
            };

            for(var i=1;i<localTable.rows.length;i++){

              for(var y=1;y<localTable.rows[0].cells.length;y++){

                var hour = document.getElementById(localTable.rows[i].cells[0].innerHTML+localTable.rows[0].cells[y].innerHTML).value;

                if(hour !== ""){
                  userInfo.repName = document.getElementById("repNome").value;
                  userInfo.week = document.getElementById("yearSchedule").value;
                  userInfo.cdlName = localTable.rows[i].cells[0].innerHTML;
                  userInfo.dayName = localTable.rows[0].cells[y].innerHTML;
                  userInfo.hour = hour;

                  arr.push(userInfo);

                  gravar = 1;

                }
              }
            }

            if(gravar === 1) {
              google.script.run.myFunction(arr);
              alert("Ok!")
            };

          } catch(err) {
            alert(err.message);
          }

        }
</code>```

My function in the server side:

```<code>var url = "mylink.com";

function myFunction(arr) {
try{
    var ss = SpreadsheetApp.openByUrl(url);
    var ws = ss.getSheetByName("AgendaSemanal");
    let userInfo = [];

    for(i = 0; i<arr.length; i++) {

      userInfo = arr[i];

      ws.appendRow([userInfo.repName,
                    userInfo.week,
                    userInfo.cdlName,
                    userInfo.dayName,
                    userInfo.hour,
                    new Date()])

  }

  } catch(err){
      Logger.log(err);
  } finally {

  return ;
  }
}```

```

答:
Use the withSuccessHandler as shown below:

```<code>if(gravar === 1) {
  google.script.withSuccessHandler(function() {
    alert("Ok!");
  }).run.myFunction(arr);
};
</code>```

The callback is called after the server-side returns.

ContentLicense: CC BY-SA 4.0

Body:
I created a function to append an array to a google spreadsheet. Usually, my array has more than 5 items. In the client side, I group the data in a array and I send to the server using the "google.script.run.myFunction(params)". Then, I use a loop structure to do this in the server side. I belive my client side is running even the server side doesn't ended the job.
How I could to do to the client side waits the server side to finish the run?

At least, my server side also running an append to the spreadsheet without to wait the run finish.

My function in the client side:

function sendArr(){
          var userInfo = {};
          var arr = new Array();
          var localTable = "";
          var gravar = 0;

          try{

            localTable = document.getElementById("scheduleTable");

            if(document.getElementById("repNome").value === "") {
              throw new Error();
            }

            if(document.getElementById("yearSchedule").value === ""){
              throw new Error();
            };

            for(var i=1;i<localTable.rows.length;i++){

              for(var y=1;y<localTable.rows[0].cells.length;y++){

                var hour = document.getElementById(localTable.rows[i].cells[0].innerHTML+localTable.rows[0].cells[y].innerHTML).value;

                if(hour !== ""){
                  userInfo.repName = document.getElementById("repNome").value;
                  userInfo.week = document.getElementById("yearSchedule").value;
                  userInfo.cdlName = localTable.rows[i].cells[0].innerHTML;
                  userInfo.dayName = localTable.rows[0].cells[y].innerHTML;
                  userInfo.hour = hour;

                  arr.push(userInfo);

                  gravar = 1;

                }
              }
            }

            if(gravar === 1) {
              google.script.run.myFunction(arr);
              alert("Ok!")
            };

          } catch(err) {
            alert(err.message);
          }

        }

My function in the server side:

var url = "mylink.com";

function myFunction(arr) {
try{
    var ss = SpreadsheetApp.openByUrl(url);
    var ws = ss.getSheetByName("AgendaSemanal");
    let userInfo = [];

    for(i = 0; i<arr.length; i++) {

      userInfo = arr[i];

      ws.appendRow([userInfo.repName,
                    userInfo.week,
                    userInfo.cdlName,
                    userInfo.dayName,
                    userInfo.hour,
                    new Date()])

  }

  } catch(err){
      Logger.log(err);
  } finally {

  return ;
  }
}```

Body:
Use the withSuccessHandler as shown below:

if(gravar === 1) {
  google.script.withSuccessHandler(function() {
    alert("Ok!");
  }).run.myFunction(arr);
};

The callback is called after the server-side returns.


问:
Automapping nested classes with one DTO
So i'm building a webapp with some friends where i will create the backend code for it. I have got several models but only one model is coming in from the httppost.

so what i have got for incoming http post:

```<code>    public class LanpartyDto
{
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    public string Description { get; set; }

    public Dictionary<DateTime, IList<string>> UsersAvailableForDate { get; set; }

}

public class Lanparty
{
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public Guid  AvailablityId{ get; set; }

    public IList<Availability> AvailableUsers { get; set; }
}

public class Availability
{

    public Guid Id { get; set; }

    public string DateAvailable { get; set; }

    public IList<string> Name { get; set; }

}

 public AutoMapping()
    {
        CreateMap<Lanparty, LanpartyDto>()
            .ForMember(dest => dest.UsersAvailableForDate, m => m.MapFrom(src => src.AvailableUsers.ToDictionary(k=>k.DateAvailable, v=>v.Name.ToList())));

    }
</code>```

So can I map one dto with multiple nested classes? so far i guess not coz i'm getting a map exception and looking here and on google it's possible if i would make a availabilitydto aswell but i see no use of that?
So what's my best option try to change the frontend code so i can change my dto? or just create mapping code myself since this is for one class its not difficult?

答:
The mapping you want would look like this:

```<code>CreateMap<Lanparty, LanpartyDto>()
    .ForMember(dest => dest.UsersAvailableForDate,
        m => m.MapFrom(src => src.AvailableUsers.ToDictionary(k => k.DateAvailable, v => v.Name)));

CreateMap<LanpartyDto, Lanparty>()
    .ForMember(dest => dest.AvailableUsers,
        m => m.MapFrom(src => src.UsersAvailableForDate.Select(u => new Availability { DateAvailable = u.Key, Name = u.Value })));
</code>```

I allowed myself to change Availability.DateAvailable property type to DateTime as I don't quite understand why you're using string there. But if you want it to be a string, just add ToString() to the u.Key part.

Title: Automapping nested classes with one DTO

Body:
So i'm building a webapp with some friends where i will create the backend code for it. I have got several models but only one model is coming in from the httppost.

so what i have got for incoming http post:

    public class LanpartyDto
{
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    public string Description { get; set; }

    public Dictionary<DateTime, IList<string>> UsersAvailableForDate { get; set; }

}

public class Lanparty
{
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public Guid  AvailablityId{ get; set; }

    public IList<Availability> AvailableUsers { get; set; }
}

public class Availability
{

    public Guid Id { get; set; }

    public string DateAvailable { get; set; }

    public IList<string> Name { get; set; }

}

 public AutoMapping()
    {
        CreateMap<Lanparty, LanpartyDto>()
            .ForMember(dest => dest.UsersAvailableForDate, m => m.MapFrom(src => src.AvailableUsers.ToDictionary(k=>k.DateAvailable, v=>v.Name.ToList())));

    }

So can I map one dto with multiple nested classes? so far i guess not coz i'm getting a map exception and looking here and on google it's possible if i would make a availabilitydto aswell but i see no use of that?
So what's my best option try to change the frontend code so i can change my dto? or just create mapping code myself since this is for one class its not difficult?

Body:
The mapping you want would look like this:

CreateMap<Lanparty, LanpartyDto>()
    .ForMember(dest => dest.UsersAvailableForDate,
        m => m.MapFrom(src => src.AvailableUsers.ToDictionary(k => k.DateAvailable, v => v.Name)));

CreateMap<LanpartyDto, Lanparty>()
    .ForMember(dest => dest.AvailableUsers,
        m => m.MapFrom(src => src.UsersAvailableForDate.Select(u => new Availability { DateAvailable = u.Key, Name = u.Value })));

I allowed myself to change Availability.DateAvailable property type to DateTime as I don't quite understand why you're using string there. But if you want it to be a string, just add ToString() to the u.Key part.


问:
How to create a scallable background for text which is in div using css
I want to create a div like below.

And the html is

Text

```

This work fine in 100% page view but if i zoom in or out the page the background of the 'text' div's shape is changing. Can you help me to fix this. Basically I want a scallable background for the div.

答:
Use a pseudo-element...

body {
  text-align: center;
}

:root {
  --val: 200%;
}

h2 {
  display: inline-block;
  margin-top: 50px; /* adjust as required - or align some other way*/
  position: relative;
}

h2::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: var(--val);
  padding-bottom: var(--val);
  transform: translate(-50%, -50%);
  background: lightgrey;
  z-index: -1;
  border-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Text</h2></code>```

Body:
I want to create a div like below.

And the html is

Text

This work fine in 100% page view but if i zoom in or out the page the background of the 'text' div's shape is changing. Can you help me to fix this. Basically I want a scallable background for the div.

Body:
Use a pseudo-element...

body {
  text-align: center;
}

:root {
  --val: 200%;
}

h2 {
  display: inline-block;
  margin-top: 50px; /* adjust as required - or align some other way*/
  position: relative;
}

h2::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: var(--val);
  padding-bottom: var(--val);
  transform: translate(-50%, -50%);
  background: lightgrey;
  z-index: -1;
  border-radius: 50%;
}

<h2>Text</h2>


问:
Changing value of a an object of Integer class
How to change value of a an object of Integer class ex: here I have declared the values of objects x and y to 5 and 6 respectively and I want to swap the value stored in the objects i.e x.intValue() should be 6 and y.intValue() should be 5. Please help.</p>

```<code>class second{
    public static void main(String[] args) {

        System.out.println(In1.a);
        Integer x = new Integer(5);
        Integer y = new Integer(6);
        System.out.println(x.equals(y));
        System.out.println(x.intValue());

    }
}
</code>```

答:
Try,

```<code>Integer temp = x;
x = y;
y = temp;
</code>```

1 ) Have the value of x in a temporary variable

2 ) Assign value of y to x

3 ) Assign value of temp to y

In this way, your values of x and y will get swapped.

Body:
How to change value of a an object of Integer class ex: here I have declared the values of objects x and y to 5 and 6 respectively and I want to swap the value stored in the objects i.e x.intValue() should be 6 and y.intValue() should be 5. Please help.

class second{
    public static void main(String[] args) {

        System.out.println(In1.a);
        Integer x = new Integer(5);
        Integer y = new Integer(6);
        System.out.println(x.equals(y));
        System.out.println(x.intValue());

    }
}

Body:
Try,

Integer temp = x;
x = y;
y = temp;

1 ) Have the value of x in a temporary variable

2 ) Assign value of y to x

3 ) Assign value of temp to y

In this way, your values of x and y will get swapped.


问:
Android Pysical Back Button closes the app
i am pushing the new widget by below code:

```<code>Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (BuildContext context) => BigPhoto(widget.images)))
          },
</code>```

After the new page opened then when I click to back button which android physical back button then the app closing instead of popping back. How can i fix it?

full implementation:

```<code>return Stack(
  children: <Widget>[
    StreamBuilder<int>(
      stream: bloc.currentItemStream,
      builder: (context, snapshot) {
        return GestureDetector(
          onTap: () => {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (BuildContext context) => BigPhoto(widget.images, snapshot.data - 1)))
          },
          child: AspectRatio(
              aspectRatio: 411 / 308,
              child: PageView.builder(
                physics: BouncingScrollPhysics(),
                itemCount: widget.images.length,
                onPageChanged: (value) {
                  bloc.changeCurrentItemIndex(value + 1);
                },
                itemBuilder: (context, position) {
                  return FittedBox(
                    fit: BoxFit.cover,
                    child: Container(
                      child: Image.network(
                        "{widget.images[position]}",
                        fit: BoxFit.cover,
                      ),
                    ),
                  );
                },
              )),
        );
      }
    ),
    Positioned(
      left: 26,
      bottom: 9,
      child: StreamBuilder<int>(
          stream: bloc.currentItemStream,
          builder: (context, snapshot) {
            return Container(
              padding: const EdgeInsets.only(
                  bottom: 3, top: 3, left: 7, right: 7),
              decoration: BoxDecoration(
                border: Border.all(width: 3.0, color: Colors.white),
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(20.0)),
              ),
              child: Text(
                " ${snapshot.data} / ${widget.images.length}",
                style: TextStyle(
                    fontSize: 11.0,
                    fontFamily: 'Roboto-Regular',
                    backgroundColor: Colors.white),
              ),
            );
          }),
    ),
  ],
);
</code>```

答:
I would suggest this solution:
You can unable the return with the physical back button on the page that you are navigating to, by putting the build widget into a WillPopScoop widget and set onWillPop to false. And implement your own back button just like that.

```<code>Widget build(BuildContext context) {
WillPopScope(
  onWillPop: () async => false,
  child: Material(
      child: Scaffold(
          appBar: AppBar(
          leading: IconButton(
                  icon: Icon(Icons.arrow_back_ios),
                  onPressed: () {
                    _goBack(context);
                  })),
          body : Image.asset("YOUR_URL_IMAGE"));
</code>```

the _goback() methode :

```<code>_goBack(BuildContext context) {
Navigator.pop(context); }
</code>```

Body:
i am pushing the new widget by below code:

Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (BuildContext context) => BigPhoto(widget.images)))
          },

After the new page opened then when I click to back button which android physical back button then the app closing instead of popping back. How can i fix it?

full implementation:

return Stack(
  children: <Widget>[
    StreamBuilder<int>(
      stream: bloc.currentItemStream,
      builder: (context, snapshot) {
        return GestureDetector(
          onTap: () => {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (BuildContext context) => BigPhoto(widget.images, snapshot.data - 1)))
          },
          child: AspectRatio(
              aspectRatio: 411 / 308,
              child: PageView.builder(
                physics: BouncingScrollPhysics(),
                itemCount: widget.images.length,
                onPageChanged: (value) {
                  bloc.changeCurrentItemIndex(value + 1);
                },
                itemBuilder: (context, position) {
                  return FittedBox(
                    fit: BoxFit.cover,
                    child: Container(
                      child: Image.network(
                        "{widget.images[position]}",
                        fit: BoxFit.cover,
                      ),
                    ),
                  );
                },
              )),
        );
      }
    ),
    Positioned(
      left: 26,
      bottom: 9,
      child: StreamBuilder<int>(
          stream: bloc.currentItemStream,
          builder: (context, snapshot) {
            return Container(
              padding: const EdgeInsets.only(
                  bottom: 3, top: 3, left: 7, right: 7),
              decoration: BoxDecoration(
                border: Border.all(width: 3.0, color: Colors.white),
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(20.0)),
              ),
              child: Text(
                " ${snapshot.data} / ${widget.images.length}",
                style: TextStyle(
                    fontSize: 11.0,
                    fontFamily: 'Roboto-Regular',
                    backgroundColor: Colors.white),
              ),
            );
          }),
    ),
  ],
);

Body:
I would suggest this solution:
You can unable the return with the physical back button on the page that you are navigating to, by putting the build widget into a WillPopScoop widget and set onWillPop to false. And implement your own back button just like that.

Widget build(BuildContext context) {
WillPopScope(
  onWillPop: () async => false,
  child: Material(
      child: Scaffold(
          appBar: AppBar(
          leading: IconButton(
                  icon: Icon(Icons.arrow_back_ios),
                  onPressed: () {
                    _goBack(context);
                  })),
          body : Image.asset("YOUR_URL_IMAGE"));

the _goback() methode :

_goBack(BuildContext context) {
Navigator.pop(context); }


问:
Facing issues in doing round off in Java
I have to show the fund value to customers for the next 30 years in one of my application , but the issue is there are some decimal values present , so we have to do the round off those values so that we will be calculated properly .e.g we there are values like, 414.598940334717 , it should round off to 414.60 but it is not getting round off with this function till 414.61 according to the spreadsheet.
I have written this method</p>

```<code>BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));

bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );
</code>```

答:
try</p>

```<code>  DecimalFormat twoDForm = new DecimalFormat("#.##");
  System.out.print(twoDForm.format(Double.valueOf("414.588940334717")));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to show the fund value to customers for the next 30 years in one of my application , but the issue is there are some decimal values present , so we have to do the round off those values so that we will be calculated properly .e.g we there are values like, 414.598940334717 , it should round off to 414.60 but it is not getting round off with this function till 414.61 according to the spreadsheet.
I have written this method

BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));

bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );

Body:
try

  DecimalFormat twoDForm = new DecimalFormat("#.##");
  System.out.print(twoDForm.format(Double.valueOf("414.588940334717")));


问:
Does Q.allSettled ever fail?
I've seen some places in unit tests where a function returns a q.allSettled() promise from a function call and there's a .fail attached to the promise. But .allSettled will call .then even if some/all promises are rejected.

Here's an example:

```<code>function someFunctionToTest(){
  var aRejectedDeferred = Q.defer();
  var anotherRejectedDeferred = Q.defer();
  var aResolvedDeferred = Q.defer();

  aRejectedDeferred.reject(new Error("I'm aRejectedPromise"));
  anotherRejectedDeferred.reject(new Error("I'm anotherRejectedPromise"));
  aResolvedDeferred.resolve({awesome:"I'm aResolvedPromise"});

  return Q.allSettled([aRejectedDeferred.promise,anotherRejectedDeferred.promise, aResolvedDeferred.promise])
}

it('should never fail', function(done) {

  someFunctionToTest()
      .then(function (data) {
        should.equal(data[0].state,'rejected');
        should.equal(data[1].state,'rejected');
        should.equal(data[2].state,'fulfilled');
        // throw(new Error('I will trigger fail!!!'));
        done();
      })
      .fail(function (err) {
        done(err);
      });
});
</code>```

Can you provide some examples where .fail would be triggered?

答:
There are two things you might want to consider:

Q.allSettled does not have a fail function, it only works with done()  which has promise states as a parameter. you should check those states to see if promises are either fulfilled or rejected. however Q.all has a then and a fail function that you might want to use but no parameter will be passed to then so no state will be known.

If you catch the errors manually in each one of promises (i.e. implement fail() function for each one of promises), the states will be always fullfiled, so while using Q.all or Q.allSettled, either don't catch the errors in promises or throw them again after catching!

Title: Does Q.allSettled ever fail?

Body:
I've seen some places in unit tests where a function returns a q.allSettled() promise from a function call and there's a .fail attached to the promise. But .allSettled will call .then even if some/all promises are rejected.

Here's an example:

function someFunctionToTest(){
  var aRejectedDeferred = Q.defer();
  var anotherRejectedDeferred = Q.defer();
  var aResolvedDeferred = Q.defer();

  aRejectedDeferred.reject(new Error("I'm aRejectedPromise"));
  anotherRejectedDeferred.reject(new Error("I'm anotherRejectedPromise"));
  aResolvedDeferred.resolve({awesome:"I'm aResolvedPromise"});

  return Q.allSettled([aRejectedDeferred.promise,anotherRejectedDeferred.promise, aResolvedDeferred.promise])
}

it('should never fail', function(done) {

  someFunctionToTest()
      .then(function (data) {
        should.equal(data[0].state,'rejected');
        should.equal(data[1].state,'rejected');
        should.equal(data[2].state,'fulfilled');
        // throw(new Error('I will trigger fail!!!'));
        done();
      })
      .fail(function (err) {
        done(err);
      });
});

Can you provide some examples where .fail would be triggered?


问:
How to get data from different SQLite tables and display it in one SimpleAdapter Android
I am new to Android and need to display Starttime, Stoptime and Name in a Listview. For displaying I use a SimpleAdapter. The problem is that I have two SQLite tables:

Table time:
Starttime | Stoptime | Student ID

Table student:
Student ID | Student name

Right now, I use a Cursor to get Starttime, Stoptime and Student ID from my database

```<code> Cursor curm1 = myDb.getAllMonday();
 while (curm1.moveToNext()) {
        final HashMap<String, String> resultMapMonday = new HashMap<>();
        resultMapMonday.put("Start", curm1.getString(3));
        resultMapMonday.put("Stop", curm1.getString(4));
        resultMapMonday.put("Student", curm1.getString(5));
        arrayListStudentsName.add(curm1.getString(5));
        listItemsMo.add(resultMapMonday);
 }
</code>```

and then a SimpleAdapter to display it:

```<code>final SimpleAdapter adaptersimpleMo = new SimpleAdapter(this, listItemsMo, R.layout.timeslots_configurate,
            new String[]{"Start", "Stop", "Student"},
            new int[]{R.id.oneTime_start, R.id.oneTime_stop, R.id.selectedStudent});
</code>```

But instead of the id, I want to display the names, which are stored in the other table. I can get the matching names of the Ids with another cursor

```<code>Cursor curm2 = myDb.getNamesbyIDs(arrayListStudentsName);
while (curm2.moveToNext()) {
        final HashMap<String, String> resultMapNames = new HashMap<>();
        resultMapNames.put("Name", curm2.getString(1));
}
</code>```

But I don't know how to get the names in the same adapter to display the names in the same list Item as the matching start & stop time.

EDIT

```<code>  public Cursor getAllMonday() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_TIME + " WHERE day = 'Montag' ORDER BY CAST(start as unsigned)", null);
    return res;
}
</code>```

答:
Change getAllMonday() to use a query that joins the 2 tables:

```<code>public Cursor getAllMonday() {
    SQLiteDatabase db = this.getWritableDatabase();
    String sql = "SELECT t.Start, t.Stop, s.Studentname FROM " + TABLE_TIME + " AS t INNER JOIN " + TABLE_STUDENT +
                 " AS s ON s.StudentID = t.StudentID WHERE t.day = 'Montag' ORDER BY CAST(t.start as unsigned)"
    Cursor res = db.rawQuery(sql, null);
    return res;
}
</code>```

Change the table variable TABLE_STUDENT and the column names that I used to the actual ones.

Now the cursor contains the name of the student and not the id.

Next change the code to:

```<code>Cursor curm1 = myDb.getAllMonday();
while (curm1.moveToNext()) {
    final HashMap<String, String> resultMapMonday = new HashMap<>();
    resultMapMonday.put("Start", curm1.getString(curm1.getColumnIndex("Start")));
    resultMapMonday.put("Stop", curm1.getString(curm1.getColumnIndex("Stop")));
    resultMapMonday.put("Student", curm1.getString(curm1.getColumnIndex("Studentname")));
    arrayListStudentsName.add(curm1.getString(curm1.getColumnIndex("Studentname")));
    listItemsMo.add(resultMapMonday);
}
curm1.close();
</code>```

Body:
I am new to Android and need to display Starttime, Stoptime and Name in a Listview. For displaying I use a SimpleAdapter. The problem is that I have two SQLite tables:

Table time:
Starttime | Stoptime | Student ID

Table student:
Student ID | Student name

Right now, I use a Cursor to get Starttime, Stoptime and Student ID from my database

 Cursor curm1 = myDb.getAllMonday();
 while (curm1.moveToNext()) {
        final HashMap<String, String> resultMapMonday = new HashMap<>();
        resultMapMonday.put("Start", curm1.getString(3));
        resultMapMonday.put("Stop", curm1.getString(4));
        resultMapMonday.put("Student", curm1.getString(5));
        arrayListStudentsName.add(curm1.getString(5));
        listItemsMo.add(resultMapMonday);
 }

and then a SimpleAdapter to display it:

final SimpleAdapter adaptersimpleMo = new SimpleAdapter(this, listItemsMo, R.layout.timeslots_configurate,
            new String[]{"Start", "Stop", "Student"},
            new int[]{R.id.oneTime_start, R.id.oneTime_stop, R.id.selectedStudent});

But instead of the id, I want to display the names, which are stored in the other table. I can get the matching names of the Ids with another cursor

Cursor curm2 = myDb.getNamesbyIDs(arrayListStudentsName);
while (curm2.moveToNext()) {
        final HashMap<String, String> resultMapNames = new HashMap<>();
        resultMapNames.put("Name", curm2.getString(1));
}

But I don't know how to get the names in the same adapter to display the names in the same list Item as the matching start & stop time.

EDIT

  public Cursor getAllMonday() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_TIME + " WHERE day = 'Montag' ORDER BY CAST(start as unsigned)", null);
    return res;
}

Body:
Change getAllMonday() to use a query that joins the 2 tables:

public Cursor getAllMonday() {
    SQLiteDatabase db = this.getWritableDatabase();
    String sql = "SELECT t.Start, t.Stop, s.Studentname FROM " + TABLE_TIME + " AS t INNER JOIN " + TABLE_STUDENT +
                 " AS s ON s.StudentID = t.StudentID WHERE t.day = 'Montag' ORDER BY CAST(t.start as unsigned)"
    Cursor res = db.rawQuery(sql, null);
    return res;
}

Change the table variable TABLE_STUDENT and the column names that I used to the actual ones.

Now the cursor contains the name of the student and not the id.

Next change the code to:

Cursor curm1 = myDb.getAllMonday();
while (curm1.moveToNext()) {
    final HashMap<String, String> resultMapMonday = new HashMap<>();
    resultMapMonday.put("Start", curm1.getString(curm1.getColumnIndex("Start")));
    resultMapMonday.put("Stop", curm1.getString(curm1.getColumnIndex("Stop")));
    resultMapMonday.put("Student", curm1.getString(curm1.getColumnIndex("Studentname")));
    arrayListStudentsName.add(curm1.getString(curm1.getColumnIndex("Studentname")));
    listItemsMo.add(resultMapMonday);
}
curm1.close();


问:
iPhone event in "inactive" view firing
I'm pretty new to iPhone development.  I have my "root" view and it is implementing

```<code>- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
</code>```

This implementation is working just fine.  After a user pushes a button, I do a pushViewController to push a new view onto the stack.  If the user shakes the iPhone, the accelerometer fires even though the currently "popped" view is not implementing any accelerometer related methods.  It appears to me that the root view is still active even though a different view has been pushed onto the stack.  Why is a view that's not the active view still responding to accelerometer?

Thanks

Tom

答:
I think the accelerometer doesn't know anything about active or inactive view controllers.

The only thing you do is to set your ViewController as a delegate (to receive events) to the accelerometer. After pushing another ViewController onto the stack your origin ViewController continues to exist. And so it continues to receive events.

You have to deal with this on your own - eg. by checking a local variable or (but not tested) by checking the window property of the view.

if (self.view.window!=nil) {
// viewController is active
}

Title: iPhone event in "inactive" view firing

Body:
I'm pretty new to iPhone development.  I have my "root" view and it is implementing

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration

This implementation is working just fine.  After a user pushes a button, I do a pushViewController to push a new view onto the stack.  If the user shakes the iPhone, the accelerometer fires even though the currently "popped" view is not implementing any accelerometer related methods.  It appears to me that the root view is still active even though a different view has been pushed onto the stack.  Why is a view that's not the active view still responding to accelerometer?

Thanks

Tom


问:
In Typescript, how to define a type with exact number of property of unknown names
Let's say I have a variable. It has a name and a value, and I want them both for something, e.g. to log them - the value and a variable name. It can be done like so:

const some_symbol = "qwer"
const some_other_symbol = 100000

const log1 = (name: string, value: any) => console.log(name, value)

log1("some_symbol", some_symbol)
log1("some_other_symbol", some_other_symbol)
log1("some_symbol", some_symbol, "some_other_symbol", some_other_symbol) // compile time error
log1() // compile time error

```

<p>But a much better way would be</p>

<pre class="lang-js prettyprint-override"><code>log2({some_symbol})
log2({some_other_symbol})
</code>```

To do so I can write a function

const log2 = (obj: { [key: string]: any }) => {
    const keys = Object.keys(obj)
    if( keys.length !== 1 ) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}
```

<p>But</p>

<pre class="lang-js prettyprint-override"><code>log2({some_symbol, some_other_symbol}) // compiles. run time error
log2({}) // compiles. run time error
</code>```

I want compilation to fail on lines like log2({v1, v2}) and log2({}).

I would like get rid of dynamic type checks, and enforce a compile time check that obj param has only one key. And in general case - exact number of keys which names are unknown to me.

答:
```<code>const log2 = (obj: { [key: string]: any }) => {
    const keys = Object.keys(obj)
    // in your two run time examples. you have 2 keys, and 0 keys, and thus
    // by design your code throws an error
    if( keys.length !== 1 ) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}
</code>```

I'm not sure what you're expecting. It compiles because it's correct. It gives you a runtime error because of your code.

Perhaps, you meant to call your function as:

```<code>log2({some_symbol: some_other_symbol})
</code>```

This makes it a dictionary with only a single key, which will pass your code check.

Body:
Let's say I have a variable. It has a name and a value, and I want them both for something, e.g. to log them - the value and a variable name. It can be done like so:

const some_symbol = "qwer"
const some_other_symbol = 100000

const log1 = (name: string, value: any) => console.log(name, value)

log1("some_symbol", some_symbol)
log1("some_other_symbol", some_other_symbol)
log1("some_symbol", some_symbol, "some_other_symbol", some_other_symbol) // compile time error
log1() // compile time error

But a much better way would be

log2({some_symbol})
log2({some_other_symbol})

To do so I can write a function

const log2 = (obj: { [key: string]: any }) => {
    const keys = Object.keys(obj)
    if( keys.length !== 1 ) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}

But

log2({some_symbol, some_other_symbol}) // compiles. run time error
log2({}) // compiles. run time error

I want compilation to fail on lines like log2({v1, v2}) and log2({}).

I would like get rid of dynamic type checks, and enforce a compile time check that obj param has only one key. And in general case - exact number of keys which names are unknown to me.

Body:
const log2 = (obj: { [key: string]: any }) => {
    const keys = Object.keys(obj)
    // in your two run time examples. you have 2 keys, and 0 keys, and thus
    // by design your code throws an error
    if( keys.length !== 1 ) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}

I'm not sure what you're expecting. It compiles because it's correct. It gives you a runtime error because of your code.

Perhaps, you meant to call your function as:

log2({some_symbol: some_other_symbol})

This makes it a dictionary with only a single key, which will pass your code check.


问:
How to make Laravel Session Array Push?
I want to keep the records added in the last 20 seconds in the session. I check this with Ajax. But the most recent record is constantly being added. I can't write on it. I'm trying session :: pull this time, {} sounds empty this way.

Here is the sample code;

```<code>$crm = \GuzzleHttp\json_decode($guzzle->getBody()->getContents(), true);

foreach($crm['list'] as $row) {
      if(Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
             Session::put('data', [$row]);
       }
 }

 return response()->json(Session::get('data'));
</code>```

答:
Define array and send it into JSON instead of using the session.</p>

```<code>$data = array();
foreach($crm['list'] as $row) {
      if(Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
             $data[] =  $row;
       }
 }

 return response()->json($data);
</code>```

Title: How to make Laravel Session Array Push?

Body:
I want to keep the records added in the last 20 seconds in the session. I check this with Ajax. But the most recent record is constantly being added. I can't write on it. I'm trying session :: pull this time, {} sounds empty this way.

Here is the sample code;

$crm = \GuzzleHttp\json_decode($guzzle->getBody()->getContents(), true);

foreach($crm['list'] as $row) {
      if(Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
             Session::put('data', [$row]);
       }
 }

 return response()->json(Session::get('data'));

Body:
Define array and send it into JSON instead of using the session.

$data = array();
foreach($crm['list'] as $row) {
      if(Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
             $data[] =  $row;
       }
 }

 return response()->json($data);


问:
In C++, how do i use like strncmp function in C?
In C++, Isn`t there string function like strncmp() in C ???

for example

```<code>string str1 = "abc";
string str2 = "ab";

str2.compare(0,1,str1) == 0
</code>```

is it possible??

答:
Yes the class std::string has the member function compare declared for you use case like

```<code>int compare(size_type pos1, size_type n1, basic_string_view<charT, traits> sv) const;
</code>```

Here is a demonstrative program that shows using this overloaded member function.

```<code>#include <iostream>
#include <string>

int main()
{
    std::string str1 = "abc";
    std::string str2 = "ab";

    std::cout << str2.compare( 0, 1 ,str1) << '\n';
    std::cout << str1.compare(  0, 2 , str2) << '\n';
    std::cout << str2.compare( str1 ) << '\n';
    std::cout << str2.compare( 1, 1, str1 ) << '\n';

    return 0;
}
</code>```

The program output is

```<code>-2
0
-1
1
</code>```

So if two strings are equal then the function returns 0. If the first string is less than the second string then the function returns a negative value. Otherwise the function returns a positive value.

Body:
In C++, Isn`t there string function like strncmp() in C ???

for example

string str1 = "abc";
string str2 = "ab";

str2.compare(0,1,str1) == 0

is it possible??

Body:
Yes the class std::string has the member function compare declared for you use case like

int compare(size_type pos1, size_type n1, basic_string_view<charT, traits> sv) const;

Here is a demonstrative program that shows using this overloaded member function.

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "abc";
    std::string str2 = "ab";

    std::cout << str2.compare( 0, 1 ,str1) << '\n';
    std::cout << str1.compare(  0, 2 , str2) << '\n';
    std::cout << str2.compare( str1 ) << '\n';
    std::cout << str2.compare( 1, 1, str1 ) << '\n';

    return 0;
}

The program output is

-2
0
-1
1

So if two strings are equal then the function returns 0. If the first string is less than the second string then the function returns a negative value. Otherwise the function returns a positive value.


问:
Test where ID not in (n, n1, n2)
Given a value, #some_id = x, what's the proper syntax or method to test that the id does not exist in a collection of id's?

For example...

```<code>if($some_id not in array(3, 5, 9)){
  //do something
}
</code>```

答:
The in_array answers are correct, but in case there's some ambiguity between the term "id" and "key", if what you're trying to do is check if a key exists, you could do either of the following:

```<code>if (array_key_exists($key, $array)) ...
</code>```

or...

```<code>if (isset($array[$key])) ...
</code>```

Title: Test where ID not in (n, n1, n2)

Body:
Given a value, #some_id = x, what's the proper syntax or method to test that the id does not exist in a collection of id's?

For example...

if($some_id not in array(3, 5, 9)){
  //do something
}

Body:
The in_array answers are correct, but in case there's some ambiguity between the term "id" and "key", if what you're trying to do is check if a key exists, you could do either of the following:

if (array_key_exists($key, $array)) ...

or...

if (isset($array[$key])) ...


问:
Use a single column to index/match in two columns
I want to use a single column to do a lookup in two columns.  Example below.

```
| a |   | c | a | foo |   | c | a | foo |
| b |   | e | c | bar |   | b | a | baz |
| c |   | b | a | baz |
| d |
```

The first table is the data I'm using to match on.

The second table is the data table that I'm indexing into.

The third table is the result I want.

答:
try:

```<code>=FILTER(C:E,
 REGEXMATCH(C:C&"", "^"&TEXTJOIN("$|^", 1, A:A)&"$"),
 REGEXMATCH(D:D&"", "^"&TEXTJOIN("$|^", 1, A:A)&"$"))
</code>```

note, it's case sensitive

Body:
I want to use a single column to do a lookup in two columns.  Example below.

| a |   | c | a | foo |   | c | a | foo |
| b |   | e | c | bar |   | b | a | baz |
| c |   | b | a | baz |
| d |

The first table is the data I'm using to match on.

The second table is the data table that I'm indexing into.

The third table is the result I want.

Body:
try:

=FILTER(C:E,
 REGEXMATCH(C:C&"", "^"&TEXTJOIN("$|^", 1, A:A)&"$"),
 REGEXMATCH(D:D&"", "^"&TEXTJOIN("$|^", 1, A:A)&"$"))

note, it's case sensitive


问:
TFS Visual Studio 2017: Search for a file by name in source control
Our application code is spread over many dozens of folders in a nested hierarchy, and we have several hundred files making up the application.

So I wanted to know if there is a way to search for files by their name in the Visual Studio 2017 version of TFS ?

I spotted Q & A as per:
TFS: Search for a file by name in source control

but this answer seems no longer applicable for TFS and Visual Studio 2017.

I can, of course use tools outside of TFS (like the "Search Everything" app) and then navigate to the same folder and file in TFS.

I just felt that surely there must be a way of doing this file search within TFS ?

I have tried the search option in Team Explorer but I'm not sure how to use this ... not sure if this works ?

i.e.

答: There should be a search bar at the top of the TFS site that looks something like this you can enter all sorts of filter like those in the picture.  Or you can search in files but that will only look at what you have checked out at the moment and not all over TFS.  If you don't see the Search bar, it might be because your TFS Administrator did not install the search extension.  You might want to contact him/her.


问:
Extracting item from list
On Python I have a list like:

```<code>["Years : 1970 - aaaaa", "Month : May - aaaaaaaaa", "Day : 20 - aaaaaaa", "Years : 1971 - aaaaa"]
</code>```

I just need to extract all items starting by "Years" in another list to have a list like:

```<code>["Years : 1970 - aaaaaaa", Years :  1971 - aaaaaaaa"]
</code>```

How can I achieve this?

答:
You can do that with list comprehension:

```<code>[i for i in lst if i.startswith('Years')]
</code>```

Basically, it says For all i elements, return i if it starts with 'Years'

Title: Extracting item from list

Body:
On Python I have a list like:

["Years : 1970 - aaaaa", "Month : May - aaaaaaaaa", "Day : 20 - aaaaaaa", "Years : 1971 - aaaaa"]

I just need to extract all items starting by "Years" in another list to have a list like:

["Years : 1970 - aaaaaaa", Years :  1971 - aaaaaaaa"]

How can I achieve this?

Body:
You can do that with list comprehension:

[i for i in lst if i.startswith('Years')]

Basically, it says For all i elements, return i if it starts with 'Years'


问:
How call a python script from a python process
I  have to call a long run process from a bottle script (web framework like Django).

So in a bottle script i have

```<code>os.system("python /home/tom/Documents/proc_test/main.py")
</code>```

Anyway the main.py script is not executed.
How can i call a python script from another running python program?

P.S: in python shell interpreter i have write os.system("python /home/tom/Documents/proc_test/main.py") and the file is called

答:
You can import the python script directly via full path using importlib.

Lets assume this example main.py:

```<code>def func():
    print("func called")
</code>```

In your main script, you import as follows:

```<code>import importlib as imp
spec = imp.util.spec_from_file_location('d', '/home/tom/Documents/proc_test/main.py')
foo = imp.util.module_from_spec(spec)
spec.loader.exec_module(foo)

foo.func()
</code>```

Output:

```<code>func called
</code>```

Body:
I  have to call a long run process from a bottle script (web framework like Django).

So in a bottle script i have

os.system("python /home/tom/Documents/proc_test/main.py")

Anyway the main.py script is not executed.
How can i call a python script from another running python program?

P.S: in python shell interpreter i have write os.system("python /home/tom/Documents/proc_test/main.py") and the file is called

Body:
You can import the python script directly via full path using importlib.

Lets assume this example main.py:

def func():
    print("func called")

In your main script, you import as follows:

import importlib as imp
spec = imp.util.spec_from_file_location('d', '/home/tom/Documents/proc_test/main.py')
foo = imp.util.module_from_spec(spec)
spec.loader.exec_module(foo)

foo.func()

Output:

func called


问:
What's the difference between Dataflow sql, Beam SQL (Zeta sql or CALCITE SQL)?
While browsing I just came across Dataflow SQL. Is it any different from beamSQL?</p>

答:
Apache Beam SQL is a functionality of Apache Beam that allows you to execute queries directly from your pipeline.

As you can see here, Beam SQL has two options of SQL syntax: Beam Calcite SQL and Zeta SQL. The advantage of using Zeta SQL is that its very similar to BigQuery's syntax hence its useful in pipelines that read from or write to BigQuery.

Dataflow SQL is a functionality of Dataflow that allows you to create pipelines directly from a BigQuery query. It's said in the documentation that it supports the Zeta SQL syntax (BigQuery syntax).

To create a new Dataflow job through the BigQuery's console, to the following steps:

Go to BigQuery's console

Just under the Query editor, click in More and then in Query settings

Select Cloud Dataflow engine in the first option as you can see below

After that, you can click in Create Cloud Dataflow job and your query will become a job in Dataflow.

I hope it helps


问:
How User account be locked for 30 min after 5 unsuccessful login attempts with asp.net?
I am using asp.net membership provider for managing users. I have a requirement to lock user accounts for 30 mins after 5 unsuccessful attempts. How should I do that using asp.net membership provider on the server side?

Also I want that 'Passwords should expire after 3 months', 'Last 10 used passwords should be remembered'. Is there any way to solve these requirements.

答:
ASp.Net membership provider doesn't provide any built in support for your requirements, still you can achieve them by doing some custom work.i-e

You can schedule a job that unlocks all locked user accounts, every 30 minutes.

In your application you can put a check if subsequent user logins are 3months apart, the user should be redirected to changepassword page.

Last 10 password of the user can be kept in another table, for which you need to write some code on change password functionality.


问:
Python, Is there any way to login to google cloud identity that then connects through SAML to Azure AD?
As in the user clicks a link, and instead of being presented with google login page he is presented with azure, however in the backend the server connects through oauth to google cloud identity and then shows the user the SAML login page for Azure.

Below an image that represents what I mean

Keeping in mind I already have third party SSO enabled, and already tested logging in to google console from Azure AD and it works fine, however when I try to do it programatically by calling google Oauth2 I get the login page from google, then then the login page from Azure and finally an error.

答: I suggest following this guide in Federating Google Cloud with Azure Active Directory: Configuring provisioning and single sign-on. The login process should function similarly to what you detailed. </p>


问:
Shapely Convex Hull area gives radically different results from scipy.ConvexHull area?
I must be missing something incredibly obvious, but there seems to be a huge difference in the area computed by scipy.ConvexHull.area compared to shapely.convex_hull.area. I get

Scipy Convex Hull Area: 457761.9061526276, Shapely Convex Hull Area: 13192154623.86528

from shapely.geometry import MultiPoint
from scipy.spatial import ConvexHull
import json

def convex_hull_compare():
    with open("./test_points.json", 'r') as f:
        points = json.load(f)
        print(points)
        hull = ConvexHull(points)
        ch_area = MultiPoint(points).convex_hull.area

        print(
            f"Scipy Convex Hull Area: {hull.area}, Shapely Convex Hull Area: {ch_area}")
        # Scipy Convex Hull Area: 457761.9061526276, Shapely Convex Hull Area: 13192154623.86528

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

I've uploaded the test_points.json on a Github Gist here and written a minimal version of the code for easy reproduction.

答:
A helpful commenter linked the following question: the gist of it is that for 2D points, we want ConvexHull.volume, not ConvexHull.area.

This indeed gives us the right answer, but this is really confusing because the documentation doesn't mention this at all.

from shapely.geometry import MultiPoint
from scipy.spatial import ConvexHull
import json

def convex_hull_compare():
    with open("./test_points.json", 'r') as f:
        points = json.load(f)
        print(points)
        hull = ConvexHull(points)
        ch_area = MultiPoint(points).convex_hull.area

        print(
            f"Scipy Convex Hull Area: {hull.area}, Shapely Convex Hull Area: {ch_area}")
        # Scipy Convex Hull Area: 457761.9061526276, Shapely Convex Hull Area: 13192154623.86528

        print(
            f"Scipy Convex Hull Area: {hull.volume}, Shapely Convex Hull Area: {ch_area}")
        #Scipy Convex Hull Area: 13192154623.865295, Shapely Convex Hull Area: 13192154623.86528

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

Body:
I must be missing something incredibly obvious, but there seems to be a huge difference in the area computed by scipy.ConvexHull.area compared to shapely.convex_hull.area. I get

Scipy Convex Hull Area: 457761.9061526276, Shapely Convex Hull Area: 13192154623.86528

from shapely.geometry import MultiPoint
from scipy.spatial import ConvexHull
import json

def convex_hull_compare():
    with open("./test_points.json", 'r') as f:
        points = json.load(f)
        print(points)
        hull = ConvexHull(points)
        ch_area = MultiPoint(points).convex_hull.area

        print(
            f"Scipy Convex Hull Area: {hull.area}, Shapely Convex Hull Area: {ch_area}")
        # Scipy Convex Hull Area: 457761.9061526276, Shapely Convex Hull Area: 13192154623.86528

if __name__ == "__main__":
    convex_hull_compare()

I've uploaded the test_points.json on a Github Gist here and written a minimal version of the code for easy reproduction.


问:
EC2 instance scheduler
I would like to ask, what automatic tools are there to
start Amazon EC2 instance at 08:00AM
and stop it on 16:00
(And where to run it from?)</p>

答:
Well to shut the servers down, you could just schedule a task on the server(s) itself to tell it to shutdown at 16:00.

However if you use the Amazon EC2 Command Line Tools you can run commands from your workstation to start and stop instances:

http://docs.amazonwebservices.com/AWSEC2/latest/CommandLineReference/index.html?ApiReference-cmd-RunInstances.html

In order to set up the Command Line Tools on your workstation for Mac/Linux the following guides may be useful:

http://www.robertsosinski.com/2008/01/26/starting-amazon-ec2-with-mac-os-x/

http://cloud-computing.learningtree.com/2010/09/28/using-the-amazon-ec2-command-line-tools-and-api/

You could even configure these commands to run when you boot your workstation, or schedule them on your workstation.

ContentLicense: CC BY-SA 2.5

Title: EC2 instance scheduler


问:
Run Android Studio with JRE 1.8 or later version
I am facing issue for Android N layout XML preview. it is showing following message :

"Android N requires the IDE to be running with Java 1.8 or later"

also i install JAVA 1.8 in my OS.

also change the project JDK location with Java 1.8.

but when i see help->about of android studio it is show always 1.7.

how can i change it.?

about JRE:1.7" />

答:
just add the tag below, in your build.gradel ( app level file), under android{ } tag,

```<code>compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
</code>```

like this,

```<code>android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
    applicationId "com.example.code"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
</code>```

}

And now you are good to go.

Body:
just add the tag below, in your build.gradel ( app level file), under android{ } tag,

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

like this,

android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
    applicationId "com.example.code"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

}

And now you are good to go.


问:
Pass two variable to method in Laravel
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

```<code>public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}
</code>```

Route

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

答:
in web.php:

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

in controller:

```<code>public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
    return view('content.post',compact('post','comments'));
}
</code>```

Title: Pass two variable to method in Laravel

Body:
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}

Route

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

Body:
in web.php:

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

in controller:

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
    return view('content.post',compact('post','comments'));
}