问:
Send Patch request from vuejs to PHP backend using AxiosAbstraction
I want to send a PATCH request to change user (promotor) birthdate from frontend Vuejs to backend PHP. with my code below, the new date of birth doesnt get to the data base, and somehow the date of birth in the data base turns to null when i send the request.

here is my front end code:

```<code>      updateDob(){
        let newdob = `${this.dob} 00:00:00`;
              // newdob will be like this > 1996-02-29 00:00:00
        this.$store.commit('updateRegistration', { key: 'dob', value: newdob });
        console.log('thats what changed    >>>>>>', newdob)
         window.AxiosAbstraction.request('PATCH', 'promotor/changeDob', { data: newdob }, { host: 'legacy' }).then((response) => {
         window.console.log('this is what we sent      >>>>>>>>>', newdob)
         window.console.log('helloooooooooo   rrrresspooooonse >>>>>>>>',response);
         }).catch((error) => {
           window.console.error(error);
           if(error.response.data && error.response.data.errors)
           {
             error.response.data.errors.forEach((error) => {
               alert(error.description);
             });
           }
         });
        this.edit= false;
      },
</code>```

and here is the endpoint I wrote in PHP :

```<code>SimpleRouter::patch('promotor/changeDob', function($promotorID) {
  cors();
  global $promotor;
  $response = new \Response();

  $data = HTTP::data();
   $data->dob;
  $promotor->update([
    'dob' => $data->dob
  ]);
   call promotor update dob
   $promotor->update([
     'dobChanged' => $data->1
   ]);
  \Response::json([
    'success'   => false
  ]);

  \Response::json($response_obj->error());
});
</code>```

on the database table:
-the date of birth data type is : datetime.
-the dobChanged data type is : tinyInt.

any idea what is wrong or can be done to modify the date of birth correctly?

Thanks!

答:
This is because you are trying to update the database without converting the data received from the frontend. The date sent from the Vue is converted during the HTTP transfer onto a string. You should be able to fix the issue by converting the date of birth into an actual date.</p>

```<code>SimpleRouter::patch('promotor/changeDob', function($promotorID) {
  cors();
  global $promotor;
  $response = new \Response();
  $data = HTTP::data();
  $dob_time = strtotime($data->dob);

  $dob = date('Y-m-d', $dob_time); // use your preferred format here

  $promotor->update([
    'dob' => $dob
  ]);
   call promotor update dob
   $promotor->update([
     'dobChanged' => $data->1
   ]);
  \Response::json([
    'success'   => false
  ]);

  \Response::json($response_obj->error());
});
</code>```

Body:
I want to send a PATCH request to change user (promotor) birthdate from frontend Vuejs to backend PHP. with my code below, the new date of birth doesnt get to the data base, and somehow the date of birth in the data base turns to null when i send the request.

here is my front end code:

      updateDob(){
        let newdob = `${this.dob} 00:00:00`;
              // newdob will be like this > 1996-02-29 00:00:00
        this.$store.commit('updateRegistration', { key: 'dob', value: newdob });
        console.log('thats what changed    >>>>>>', newdob)
         window.AxiosAbstraction.request('PATCH', 'promotor/changeDob', { data: newdob }, { host: 'legacy' }).then((response) => {
         window.console.log('this is what we sent      >>>>>>>>>', newdob)
         window.console.log('helloooooooooo   rrrresspooooonse >>>>>>>>',response);
         }).catch((error) => {
           window.console.error(error);
           if(error.response.data && error.response.data.errors)
           {
             error.response.data.errors.forEach((error) => {
               alert(error.description);
             });
           }
         });
        this.edit= false;
      },

and here is the endpoint I wrote in PHP :

SimpleRouter::patch('promotor/changeDob', function($promotorID) {
  cors();
  global $promotor;
  $response = new \Response();

  $data = HTTP::data();
   $data->dob;
  $promotor->update([
    'dob' => $data->dob
  ]);
   call promotor update dob
   $promotor->update([
     'dobChanged' => $data->1
   ]);
  \Response::json([
    'success'   => false
  ]);

  \Response::json($response_obj->error());
});

on the database table:
-the date of birth data type is : datetime.
-the dobChanged data type is : tinyInt.

any idea what is wrong or can be done to modify the date of birth correctly?

Thanks!

Body:
This is because you are trying to update the database without converting the data received from the frontend. The date sent from the Vue is converted during the HTTP transfer onto a string. You should be able to fix the issue by converting the date of birth into an actual date.

SimpleRouter::patch('promotor/changeDob', function($promotorID) {
  cors();
  global $promotor;
  $response = new \Response();
  $data = HTTP::data();
  $dob_time = strtotime($data->dob);

  $dob = date('Y-m-d', $dob_time); // use your preferred format here

  $promotor->update([
    'dob' => $dob
  ]);
   call promotor update dob
   $promotor->update([
     'dobChanged' => $data->1
   ]);
  \Response::json([
    'success'   => false
  ]);

  \Response::json($response_obj->error());
});


来源: stackexchange

问:
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?

答:
thanx for your answer ! i try but nothing to change, i see in a debug this :

14:30:42.865 [main] DEBUG o.s.b.f.xml.ResourceEntityResolver - Could not resolve XML entity [http://springframework.org/schema/beans/spring-beans-5.2.xsd] through URL [https://springframework.org/schema/beans/spring-beans-5.2.xsd]
java.io.FileNotFoundException: https://springframework.org/schema/beans/spring-beans-5.2.xsd

ContentLicense: CC BY-SA 4.0

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?


问:
slack doen't sent POST request on button
I'm trying to implement following:

python script sends message to slack with button and payload,

user clicks on button in the slack message,

button sends POST with payload to Request URL (aws api)

Currently button doesn't send POST.

I forge message with following python script

```<code>slack_token = 'xoxp-1111-111-111-qqqqqq'
sc = slack.WebClient(slack_token)
sc.chat_postMessage(
    channel="QQQQQ",
    blocks=[
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "send post"
                        }
                    }
                ]
            }
        ]
)
</code>```

I added https://here.aws.api.amazonaws.com/default/lambda as "Request url" in the "Interactive Components" and "Event Subscriptions" of my slack app.

When I send message to bot POST request is sent to aws api.

When I click button POST request is not sent.

Tried with both tokens xoxp- and xoxb-

答:
The problem is:
slack generates http request in strange way. Instead of json, it puts "blocks" into following structure:

```<code>{ ...... 'body': (byte[])\"payload=%7B%22type%22%3A%22block_actions%2 ...}
</code>```

after decoding it is equal to:

```<code>{...payload={"type": "block_actions",...}
</code>```

That isn't readable like json.
AWS API rejected these slack requests.

AWS cloudwatch helps to investigate problem.
To avoid this is necessary to enable "Use Lambda Proxy integration" option during  method adding.

Body:
I'm trying to implement following:

python script sends message to slack with button and payload,

user clicks on button in the slack message,

button sends POST with payload to Request URL (aws api)

Currently button doesn't send POST.

I forge message with following python script

slack_token = 'xoxp-1111-111-111-qqqqqq'
sc = slack.WebClient(slack_token)
sc.chat_postMessage(
    channel="QQQQQ",
    blocks=[
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "send post"
                        }
                    }
                ]
            }
        ]
)

I added https://here.aws.api.amazonaws.com/default/lambda as "Request url" in the "Interactive Components" and "Event Subscriptions" of my slack app.

When I send message to bot POST request is sent to aws api.

When I click button POST request is not sent.

Tried with both tokens xoxp- and xoxb-

Body:
The problem is:
slack generates http request in strange way. Instead of json, it puts "blocks" into following structure:

{ ...... 'body': (byte[])\"payload=%7B%22type%22%3A%22block_actions%2 ...}

after decoding it is equal to:

{...payload={"type": "block_actions",...}

That isn't readable like json.
AWS API rejected these slack requests.

AWS cloudwatch helps to investigate problem.
To avoid this is necessary to enable "Use Lambda Proxy integration" option during  method adding.


问:
Kali Linux Installing Bluto
Could somebody help me with the following problem? It would be much appreciated.

Goal : To install Bluto on Kali Linux 2020.1 using sudo pip install bluto command

Problem : Install does not complete

Error message:

ERROR: Command errored out with exit status 1:
     command: /usr/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-9scbuzrf/pdfminer/setup.py'"'"'; __file__='"'"'/tmp/pip-install-9scbuzrf/pdfminer/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-9scbuzrf/pdfminer/pip-egg-info
         cwd: /tmp/pip-install-9scbuzrf/pdfminer/
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-9scbuzrf/pdfminer/setup.py", line 3, in <module>
        from pdfminer import __version__
      File "/tmp/pip-install-9scbuzrf/pdfminer/pdfminer/__init__.py", line 5
        print __version__
              ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print(__version__)?
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Im running :
Kali Linux 2020.1

Python 3.8.1 (default, Jan 19 2020, 22:34:33)
git version 2.25.0
pip 20.0.2 from /home/kali/.local/lib/python3.8/site-packages/pip (python 3.8)

Screenshot

Bluto Kali Linux install error

答:
```<code>print __version__
</code>```

Is python 2x syntax and not compatible with python 3x. You are using 3.8, so it is incompatible.

In your case, bluto seems to have pdfminer==20140328 as a requirement, which is written with python 2x syntax. Note that also bluto itself is only compatible with python 2x.

What you can do is:

Use a python 2 interpreter with bluto - since python2 is deprecated, this is not a very good option

Download the source code of bluto, remove the pdfminer==20140328 and update the code to python 3

try to use something like this three year old fork that claims to have converted bluto to python 3

Title: Kali Linux Installing Bluto

Body:
print __version__

Is python 2x syntax and not compatible with python 3x. You are using 3.8, so it is incompatible.

In your case, bluto seems to have pdfminer==20140328 as a requirement, which is written with python 2x syntax. Note that also bluto itself is only compatible with python 2x.

What you can do is:

Use a python 2 interpreter with bluto - since python2 is deprecated, this is not a very good option

Download the source code of bluto, remove the pdfminer==20140328 and update the code to python 3

try to use something like this three year old fork that claims to have converted bluto to python 3


问:
Pagination with oauth azure data factory
Inside Azure data factory i make a call to microsoft graph through a REST copy activity utilizing rest to get an access token to the service. The Graph api returns max 200 results, and therefore i am interested in using the pagination rules that can be created in the source. In post man i can see that my response structure is

```<code>{
   "@odata.context" : <some context>,
   "@odata.nextLink" : <the link to next page>
   "value" : [<the response data on current page>]
}
</code>```

I have read in the documentation that i set the pagination rules by adding the key

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

and then the path to the next page given in the response as the value.
How do i tell azure data factory how to find this?

答:
Since your repsonse is a json structure the value of </p>

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

<p>should be </p>

```<code>$['@odata.nextLink']
</code>```

Body:
Inside Azure data factory i make a call to microsoft graph through a REST copy activity utilizing rest to get an access token to the service. The Graph api returns max 200 results, and therefore i am interested in using the pagination rules that can be created in the source. In post man i can see that my response structure is

{
   "@odata.context" : <some context>,
   "@odata.nextLink" : <the link to next page>
   "value" : [<the response data on current page>]
}

I have read in the documentation that i set the pagination rules by adding the key

AbsoluteUrl

and then the path to the next page given in the response as the value.
How do i tell azure data factory how to find this?

Body:
Since your repsonse is a json structure the value of

AbsoluteUrl

should be

$['@odata.nextLink']


问:
how to set display member to a concatenated expression? datasource is linq query
i'm trying to set the display member of my listbox to a concatenated value from a linq query:

```<code>var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;
</code>```

I was hoping to be able to set the display member by doing something like this:

```<code>listBox1.DisplayMember = "FirstName" + "LastName";
</code>```

but obviously that doesn't work.

how do i do this? I guess the tricky part is the fact that the datasource is a linq query result object. But its indexable so there's gotta be some way.

答:
AT first i have to tell you that LINQ query wont execute by itself so if you are writing the above query ie

```<code>var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;
</code>```

you wont get the desired output.

for that modify the query to

```<code>   var query =  (from a in db.Customers select new{Name = a.FirstName + a.LastName, OtherDetails = a.OtherDetails}).ToList();

listBox1.DataSouce = query;
ListBox1.DataBind();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'm trying to set the display member of my listbox to a concatenated value from a linq query:

var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;

I was hoping to be able to set the display member by doing something like this:

listBox1.DisplayMember = "FirstName" + "LastName";

but obviously that doesn't work.

how do i do this? I guess the tricky part is the fact that the datasource is a linq query result object. But its indexable so there's gotta be some way.

Body:
AT first i have to tell you that LINQ query wont execute by itself so if you are writing the above query ie

var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;

you wont get the desired output.

for that modify the query to

   var query =  (from a in db.Customers select new{Name = a.FirstName + a.LastName, OtherDetails = a.OtherDetails}).ToList();

listBox1.DataSouce = query;
ListBox1.DataBind();


问:
Validate the row data in one pyspark Dataframe matched in another Dataframe
I have 2 Pyspark Dataframe df1,df2. Both df1 and df2 contains millions of records.

df1 is like:

```<code>+-------------------+--------+--------+
|               name|state   | pincode|
+-------------------+--------+--------+
|  CYBEX INTERNATION| HOUSTON| 00530  |
|        FLUID POWER| MEDWAY | 02053  |
|   REFINERY SYSTEMS| FRANCE | 072234 |
|    K N ENTERPRISES| MUMBAI | 100010 |
+-------------------+--------+--------+
</code>```

df2 is like:

```<code>+--------------------+--------+--------+
|               name |state   | pincode|
+--------------------+--------+--------+
|FLUID POWER PVT LTD | MEDWAY | 02053  |
|  CYBEX INTERNATION | HOUSTON| 02356  |
|REFINERY SYSTEMS LTD| MUMBAI | 072234 |
+--------------------+--------+--------+
</code>```

So, I want to check whether df1 is found on df2 or not based on name state and Pincode and output should if validated i.e row found it will be 1 else 0 and df will be be

```<code>+-------------------+--------+--------+--------- --+
|               name|state   | pincode|  Validated |
+-------------------+--------+--------+---------- -+
|  CYBEX INTERNATION| HOUSTON| 00530  |     0      |
|        FLUID POWER| MEDWAY | 02053  |     1      |
|   REFINERY SYSTEMS| FRANCE | 072234 |     0      |
|    K N ENTERPRISES| MUMBAI | 100010 |     0      |
+-------------------+--------+--------+------------+
</code>```

In 1st Case of row 1 of df1 Pincode doesn't match with any df2 Pincode column so validated = 0

In 2nd case of row 2 of df1 Pincode matched, the state is also matched and for name column, I am using Levenshtein to match column name and final row is validated = 1

In 3rd Row Pincode match but the state does not match and validated = 0

In 4rth Pincode is not there and validated = 0

I tried it with the Pandas dataFrame while iterating the data in nested if, but data is so huge and iteration is not a good choice.

I am expecting to speed up the process using pyspark and leveraging parallel processing something like:

```<code>df_final = df1.withColumn('validated', if some_expression == True THEN 1,ELSE 0)
</code>```

But not able to figure out some_expression, and how to check for entire df1 validate on another df2 with given columns and without any iteration.

I have gone through different spark questions and similar problems but none of them helped me.
Any help will be appreciated. Please comment if any information is not clear.

答:
Using levenshtein-distance with left join you can do something like this:

```<code>join_condition = (col("df1.pincode") == col("df2.pincode")) \
                 & (levenshtein(col("df1.name"), col("df2.name")) <= 10) \
                 & (col("df1.state") == col("df2.state"))

result_df = df1.alias("df1").join(df2.alias("df2"), join_condition , "left")

result_df.select("df1.*",
              when(col("df2.name").isNotNull(), lit(1)).otherwise(lit(0)).alias("validated")
              ).show()

#+-----------------+-------+-------+---------+
#|             name|  state|pincode|validated|
#+-----------------+-------+-------+---------+
#|CYBEX INTERNATION|HOUSTON|  00530|        0|
#|      FLUID POWER| MEDWAY|  02053|        1|
#| REFINERY SYSTEMS| FRANCE| 072234|        0|
#|  K N ENTERPRISES| MUMBAI| 100010|        0|
#+-----------------+-------+-------+---------+
</code>```

Body:
I have 2 Pyspark Dataframe df1,df2. Both df1 and df2 contains millions of records.

df1 is like:

+-------------------+--------+--------+
|               name|state   | pincode|
+-------------------+--------+--------+
|  CYBEX INTERNATION| HOUSTON| 00530  |
|        FLUID POWER| MEDWAY | 02053  |
|   REFINERY SYSTEMS| FRANCE | 072234 |
|    K N ENTERPRISES| MUMBAI | 100010 |
+-------------------+--------+--------+

df2 is like:

+--------------------+--------+--------+
|               name |state   | pincode|
+--------------------+--------+--------+
|FLUID POWER PVT LTD | MEDWAY | 02053  |
|  CYBEX INTERNATION | HOUSTON| 02356  |
|REFINERY SYSTEMS LTD| MUMBAI | 072234 |
+--------------------+--------+--------+

So, I want to check whether df1 is found on df2 or not based on name state and Pincode and output should if validated i.e row found it will be 1 else 0 and df will be be

+-------------------+--------+--------+--------- --+
|               name|state   | pincode|  Validated |
+-------------------+--------+--------+---------- -+
|  CYBEX INTERNATION| HOUSTON| 00530  |     0      |
|        FLUID POWER| MEDWAY | 02053  |     1      |
|   REFINERY SYSTEMS| FRANCE | 072234 |     0      |
|    K N ENTERPRISES| MUMBAI | 100010 |     0      |
+-------------------+--------+--------+------------+

In 1st Case of row 1 of df1 Pincode doesn't match with any df2 Pincode column so validated = 0

In 2nd case of row 2 of df1 Pincode matched, the state is also matched and for name column, I am using Levenshtein to match column name and final row is validated = 1

In 3rd Row Pincode match but the state does not match and validated = 0

In 4rth Pincode is not there and validated = 0

I tried it with the Pandas dataFrame while iterating the data in nested if, but data is so huge and iteration is not a good choice.

I am expecting to speed up the process using pyspark and leveraging parallel processing something like:

df_final = df1.withColumn('validated', if some_expression == True THEN 1,ELSE 0)

But not able to figure out some_expression, and how to check for entire df1 validate on another df2 with given columns and without any iteration.

I have gone through different spark questions and similar problems but none of them helped me.
Any help will be appreciated. Please comment if any information is not clear.

Body:
Using levenshtein-distance with left join you can do something like this:

join_condition = (col("df1.pincode") == col("df2.pincode")) \
                 & (levenshtein(col("df1.name"), col("df2.name")) <= 10) \
                 & (col("df1.state") == col("df2.state"))

result_df = df1.alias("df1").join(df2.alias("df2"), join_condition , "left")

result_df.select("df1.*",
              when(col("df2.name").isNotNull(), lit(1)).otherwise(lit(0)).alias("validated")
              ).show()

#+-----------------+-------+-------+---------+
#|             name|  state|pincode|validated|
#+-----------------+-------+-------+---------+
#|CYBEX INTERNATION|HOUSTON|  00530|        0|
#|      FLUID POWER| MEDWAY|  02053|        1|
#| REFINERY SYSTEMS| FRANCE| 072234|        0|
#|  K N ENTERPRISES| MUMBAI| 100010|        0|
#+-----------------+-------+-------+---------+


问:
HttpWebRequest get unauthorized exception
Trying to call a remote server using the following code I get always the unauthorized exception from the server:

```<code>HttpWebRequest webRequest;
var myURI = "https://myURI";
webRequest = (HttpWebRequest)WebRequest.Create(myURI);

webRequest.Method = "GET";

string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("myUsername" + ":" + "myPassword"));
webRequest.Headers.Add("Authorization", "Basic " + myCredentials);

HttpWebResponse webResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();

string response = string.Empty;

using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
    response = sr.ReadToEnd();
    sr.Close();
}
</code>```

System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'

WWW-Authenticate: Basic realm="geoserver"

Cache-Control: proxy-revalidate

Connection: Keep-Alive

Set-Cookie: BCSI-CS-**********=1; Path=/

Proxy-Support: Session-based-authentication

Content-Type: text/plain; charset=UTF-8

Content-Length: 23

It is a litte bit weird because, if I try (almost) the same thing via postman, it works and i get the correct response from the remote server (without 401).

I've also tried other ways like the follwing code, but nothing helps:

```<code>CredentialCache cc = new CredentialCache();
cc.Add(
new Uri("https://mywebserver/webpage"),
"Basic",    //also tried NTLM
new NetworkCredential("user", "password"));
webRequest.Credentials = cc;
</code>```

If I try to call an other server with the same code it works.

答:
As you can see in the Exception, has a Session-based-authentication. The problem is: There is no documentation for the reverse proxy and I cannot find an endpoint in order to get a clean cookie. As workaround i've tried the fllowing code and it works now.
It's maybe not the best way to set the Cookie as HttpHeader.</p>

```<code>    static void Main(string[] args)
    {
        HttpWebRequest webRequest = CreateWebRequest();
        string cookie = null;

        HttpWebResponse webResponse;
        try
        {
            webResponse = (HttpWebResponse) webRequest.GetResponse();
        }
        catch (WebException ex)
        {
            var headers = (WebHeaderCollection)ex.Response.GetType().GetProperty("Headers").GetValue(ex.Response, null);
            cookie = headers.Get("Set-Cookie");
            webRequest = CreateWebRequest();
            webRequest.Headers.Add("Cookie", cookie);
            webResponse = (HttpWebResponse) webRequest.GetResponse();
        }

        string response = string.Empty;

        using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
        {
            response = sr.ReadToEnd();
            sr.Close();
        }
    }

    private static HttpWebRequest CreateWebRequest()
    {
        HttpWebRequest webRequest;
        var myURI = "https://myURI";
        webRequest = (HttpWebRequest)WebRequest.Create(myURI);
        webRequest.Method = "GET";
        string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("myUsername" + ":" + "myPassword"));
        webRequest.Headers.Add("Authorization", "Basic " + myCredentials);
        return webRequest;
    }
</code>```

Body:
Trying to call a remote server using the following code I get always the unauthorized exception from the server:

HttpWebRequest webRequest;
var myURI = "https://myURI";
webRequest = (HttpWebRequest)WebRequest.Create(myURI);

webRequest.Method = "GET";

string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("myUsername" + ":" + "myPassword"));
webRequest.Headers.Add("Authorization", "Basic " + myCredentials);

HttpWebResponse webResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();

string response = string.Empty;

using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
    response = sr.ReadToEnd();
    sr.Close();
}

System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'

WWW-Authenticate: Basic realm="geoserver"

Cache-Control: proxy-revalidate

Connection: Keep-Alive

Set-Cookie: BCSI-CS-**********=1; Path=/

Proxy-Support: Session-based-authentication

Content-Type: text/plain; charset=UTF-8

Content-Length: 23

It is a litte bit weird because, if I try (almost) the same thing via postman, it works and i get the correct response from the remote server (without 401).

I've also tried other ways like the follwing code, but nothing helps:

CredentialCache cc = new CredentialCache();
cc.Add(
new Uri("https://mywebserver/webpage"),
"Basic",    //also tried NTLM
new NetworkCredential("user", "password"));
webRequest.Credentials = cc;

If I try to call an other server with the same code it works.

Body:
As you can see in the Exception, has a Session-based-authentication. The problem is: There is no documentation for the reverse proxy and I cannot find an endpoint in order to get a clean cookie. As workaround i've tried the fllowing code and it works now.
It's maybe not the best way to set the Cookie as HttpHeader.

    static void Main(string[] args)
    {
        HttpWebRequest webRequest = CreateWebRequest();
        string cookie = null;

        HttpWebResponse webResponse;
        try
        {
            webResponse = (HttpWebResponse) webRequest.GetResponse();
        }
        catch (WebException ex)
        {
            var headers = (WebHeaderCollection)ex.Response.GetType().GetProperty("Headers").GetValue(ex.Response, null);
            cookie = headers.Get("Set-Cookie");
            webRequest = CreateWebRequest();
            webRequest.Headers.Add("Cookie", cookie);
            webResponse = (HttpWebResponse) webRequest.GetResponse();
        }

        string response = string.Empty;

        using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
        {
            response = sr.ReadToEnd();
            sr.Close();
        }
    }

    private static HttpWebRequest CreateWebRequest()
    {
        HttpWebRequest webRequest;
        var myURI = "https://myURI";
        webRequest = (HttpWebRequest)WebRequest.Create(myURI);
        webRequest.Method = "GET";
        string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("myUsername" + ":" + "myPassword"));
        webRequest.Headers.Add("Authorization", "Basic " + myCredentials);
        return webRequest;
    }


问:
Java int[] array to HashSet<Integer>
I have an array of int:

```<code>int[] a = {1, 2, 3};
</code>```

I need a typed set from it:

```<code>Set<Integer> s;
</code>```

If I do the following:

```<code>s = new HashSet(Arrays.asList(a));
</code>```

it, of course, thinks I mean:

```<code>List<int[]>
</code>```

whereas I meant:

```<code>List<Integer>
</code>```

This is because int is a primitive. If I had used String, all would work:

```<code>Set<String> s = new HashSet<String>(
    Arrays.asList(new String[] { "1", "2", "3" }));
</code>```

How to easily, correctly and succinctly go from:

```<code>A) int[] a...
</code>```

to

```<code>B) Integer[] a ...
</code>```

Thanks!

答:
Just add elements from array to Set with the below snippet</p>

```<code>public class RemoveDuplicateElements {

    public static void main(String args[]){
        int array[] =  {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5};
        Set <Integer> abc = new HashSet <Integer>();
        for (Integer t:array){
            abc.add(t);
        }
        System.out.println("sampleSet"+abc);
    }

}
</code>```

Title: Java int[] array to HashSet<Integer>

Body:
I have an array of int:

int[] a = {1, 2, 3};

I need a typed set from it:

Set<Integer> s;

If I do the following:

s = new HashSet(Arrays.asList(a));

it, of course, thinks I mean:

List<int[]>

whereas I meant:

List<Integer>

This is because int is a primitive. If I had used String, all would work:

Set<String> s = new HashSet<String>(
    Arrays.asList(new String[] { "1", "2", "3" }));

How to easily, correctly and succinctly go from:

A) int[] a...

to

B) Integer[] a ...

Thanks!

Body:
Just add elements from array to Set with the below snippet

public class RemoveDuplicateElements {

    public static void main(String args[]){
        int array[] =  {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5};
        Set <Integer> abc = new HashSet <Integer>();
        for (Integer t:array){
            abc.add(t);
        }
        System.out.println("sampleSet"+abc);
    }

}


问:
Problems in using "pdfetch"
I am trying to download a time series from this website - it is the very last item I am trying to get. I am using pdfetch as it is usually quick. It just requires to put the code of the series and the job is done. However, this time I get an error I can't solve. Find below the problem.

```<code>library(pdfetch)

pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")

Error in xts(as.matrix(suppressWarnings(as.numeric(fr[, 2]))), dates,  :
  'order.by' cannot contain 'NA', 'NaN', or 'Inf'

</code>```

Can anyone solve it?

Thanks a lot!

I am including my SessionInfo:

```<code>R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

Random number generation:
 RNG:     Mersenne-Twister
 Normal:  Inversion
 Sample:  Rounding

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252
[4] LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] Quandl_2.10.0        tsDyn_10-1.2         tseries_0.10-47      quantmod_0.4-15      TTR_0.23-5
 [6] xts_0.11-2           scales_1.0.0         stargazer_5.2.2      forecast_8.11        readxl_1.3.1
[11] dynlm_0.3-6          AER_1.2-9            survival_3.1-8       car_3.0-6            carData_3.0-3
[16] pdfetch_0.2.4        vars_1.5-3           lmtest_0.9-37        urca_1.3-0           strucchange_1.5-2
[21] sandwich_2.5-1       MASS_7.3-51.5        lubridate_1.7.4      zoo_1.8-6            pastecs_1.3.21
[26] rvest_0.3.5          xml2_1.2.2           ngram_3.0.4          quanteda_1.5.2       textstem_0.1.4
[31] koRpus.lang.en_0.1-3 koRpus_0.11-5        sylly_0.1-5          readtext_0.75        pdftools_2.3
[36] forcats_0.4.0        stringr_1.4.0        dplyr_0.8.4          purrr_0.3.2          readr_1.3.1
[41] tidyr_1.0.2          tibble_2.1.3         ggplot2_3.2.1        tidyverse_1.3.0      topicmodels_0.2-8

loaded via a namespace (and not attached):
 [1] backports_1.1.4       fastmatch_1.1-0       plyr_1.8.4            selectr_0.4-2         lazyeval_0.2.2
 [6] splines_3.6.2         digest_0.6.21         foreach_1.4.8         htmltools_0.4.0       fansi_0.4.0
[11] magrittr_1.5          tm_0.7-7              openxlsx_4.1.4        remotes_2.1.0         modelr_0.1.5
[16] RcppParallel_4.4.3    textshape_1.6.0       askpass_1.1           colorspace_1.4-1      haven_2.2.0
[21] xfun_0.12             crayon_1.3.4          jsonlite_1.6          iterators_1.0.12      glue_1.3.1
[26] stopwords_1.0         gtable_0.3.0          spacyr_1.2            abind_1.4-5           qpdf_1.1
[31] DBI_1.1.0             tseriesChaos_0.1-13.1 qdapRegex_0.7.2       Rcpp_1.0.2            foreign_0.8-74
[36] deSolve_1.27.1        Formula_1.2-3         textclean_0.9.3       stats4_3.6.2          httr_1.4.1
[41] modeltools_0.2-22     pkgconfig_2.0.3       XML_3.99-0.3          nnet_7.3-12           dbplyr_1.4.2
[46] utf8_1.1.4            janitor_1.2.1         tidyselect_0.2.5      labeling_0.3          rlang_0.4.4
[51] reshape2_1.4.3        munsell_0.5.0         cellranger_1.1.0      tools_3.6.2           cli_2.0.1
[56] generics_0.0.2        broom_0.5.4           evaluate_0.14         yaml_2.2.0            knitr_1.26
[61] fs_1.3.1              zip_2.0.4             nlme_3.1-143          slam_0.1-45           compiler_3.6.2
[66] rstudioapi_0.11       curl_4.1              reprex_0.3.0          syuzhet_1.0.4         stringi_1.4.3
[71] lattice_0.20-38       Matrix_1.2-18         vctrs_0.2.2           pillar_1.4.3          lifecycle_0.1.0
[76] data.table_1.12.2     sylly.en_0.1-3        R6_2.4.1              rio_0.5.16            lexicon_1.2.1
[81] codetools_0.2-16      boot_1.3-24           assertthat_0.2.1      withr_2.1.2           mnormt_1.5-6
[86] fracdiff_1.5-1        mgcv_1.8-31           parallel_3.6.2        hms_0.5.3             ISOcodes_2019.12.22
[91] quadprog_1.5-8        grid_3.6.2            timeDate_3043.102     rmarkdown_2.1         NLP_0.2-0
</code>```

答:
This seems to be a locale problem, most likely down to the failure of lubridate to parse the unusual English year-month format of the downloaded csv document in your locale.

I can replicate your error by doing

```<code>Sys.setlocale("LC_ALL", "Italian_Italy.1252")
pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")
#> Error in xts(as.matrix(suppressWarnings(as.numeric(fr[, 2]))), dates,  :
#>   'order.by' cannot contain 'NA', 'NaN', or 'Inf'
</code>```

and fix it by doing

```<code>Sys.setlocale("LC_ALL", "English_United Kingdom.1252")
pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")
#>            ICP.M.U2.Y.XEFUN0.3.INX
#> 1997-01-31                   75.45
#> 1997-02-28                   75.52
#> 1997-03-31                   75.59
#> 1997-04-30                   75.61
#> 1997-05-31                   75.71
#> 1997-06-30                   75.76
#> ...
</code>```

So this should work for you:

```<code>Sys.setlocale("LC_ALL", "English_United Kingdom.1252")
result <- pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")
Sys.setlocale("LC_ALL", "Italian_Italy.1252")
</code>```

Title: Problems in using "pdfetch"

Body:
I am trying to download a time series from this website - it is the very last item I am trying to get. I am using pdfetch as it is usually quick. It just requires to put the code of the series and the job is done. However, this time I get an error I can't solve. Find below the problem.

library(pdfetch)

pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")

Error in xts(as.matrix(suppressWarnings(as.numeric(fr[, 2]))), dates,  :
  'order.by' cannot contain 'NA', 'NaN', or 'Inf'

Can anyone solve it?

Thanks a lot!

I am including my SessionInfo:

R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

Random number generation:
 RNG:     Mersenne-Twister
 Normal:  Inversion
 Sample:  Rounding

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252
[4] LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] Quandl_2.10.0        tsDyn_10-1.2         tseries_0.10-47      quantmod_0.4-15      TTR_0.23-5
 [6] xts_0.11-2           scales_1.0.0         stargazer_5.2.2      forecast_8.11        readxl_1.3.1
[11] dynlm_0.3-6          AER_1.2-9            survival_3.1-8       car_3.0-6            carData_3.0-3
[16] pdfetch_0.2.4        vars_1.5-3           lmtest_0.9-37        urca_1.3-0           strucchange_1.5-2
[21] sandwich_2.5-1       MASS_7.3-51.5        lubridate_1.7.4      zoo_1.8-6            pastecs_1.3.21
[26] rvest_0.3.5          xml2_1.2.2           ngram_3.0.4          quanteda_1.5.2       textstem_0.1.4
[31] koRpus.lang.en_0.1-3 koRpus_0.11-5        sylly_0.1-5          readtext_0.75        pdftools_2.3
[36] forcats_0.4.0        stringr_1.4.0        dplyr_0.8.4          purrr_0.3.2          readr_1.3.1
[41] tidyr_1.0.2          tibble_2.1.3         ggplot2_3.2.1        tidyverse_1.3.0      topicmodels_0.2-8

loaded via a namespace (and not attached):
 [1] backports_1.1.4       fastmatch_1.1-0       plyr_1.8.4            selectr_0.4-2         lazyeval_0.2.2
 [6] splines_3.6.2         digest_0.6.21         foreach_1.4.8         htmltools_0.4.0       fansi_0.4.0
[11] magrittr_1.5          tm_0.7-7              openxlsx_4.1.4        remotes_2.1.0         modelr_0.1.5
[16] RcppParallel_4.4.3    textshape_1.6.0       askpass_1.1           colorspace_1.4-1      haven_2.2.0
[21] xfun_0.12             crayon_1.3.4          jsonlite_1.6          iterators_1.0.12      glue_1.3.1
[26] stopwords_1.0         gtable_0.3.0          spacyr_1.2            abind_1.4-5           qpdf_1.1
[31] DBI_1.1.0             tseriesChaos_0.1-13.1 qdapRegex_0.7.2       Rcpp_1.0.2            foreign_0.8-74
[36] deSolve_1.27.1        Formula_1.2-3         textclean_0.9.3       stats4_3.6.2          httr_1.4.1
[41] modeltools_0.2-22     pkgconfig_2.0.3       XML_3.99-0.3          nnet_7.3-12           dbplyr_1.4.2
[46] utf8_1.1.4            janitor_1.2.1         tidyselect_0.2.5      labeling_0.3          rlang_0.4.4
[51] reshape2_1.4.3        munsell_0.5.0         cellranger_1.1.0      tools_3.6.2           cli_2.0.1
[56] generics_0.0.2        broom_0.5.4           evaluate_0.14         yaml_2.2.0            knitr_1.26
[61] fs_1.3.1              zip_2.0.4             nlme_3.1-143          slam_0.1-45           compiler_3.6.2
[66] rstudioapi_0.11       curl_4.1              reprex_0.3.0          syuzhet_1.0.4         stringi_1.4.3
[71] lattice_0.20-38       Matrix_1.2-18         vctrs_0.2.2           pillar_1.4.3          lifecycle_0.1.0
[76] data.table_1.12.2     sylly.en_0.1-3        R6_2.4.1              rio_0.5.16            lexicon_1.2.1
[81] codetools_0.2-16      boot_1.3-24           assertthat_0.2.1      withr_2.1.2           mnormt_1.5-6
[86] fracdiff_1.5-1        mgcv_1.8-31           parallel_3.6.2        hms_0.5.3             ISOcodes_2019.12.22
[91] quadprog_1.5-8        grid_3.6.2            timeDate_3043.102     rmarkdown_2.1         NLP_0.2-0

Body:
This seems to be a locale problem, most likely down to the failure of lubridate to parse the unusual English year-month format of the downloaded csv document in your locale.

I can replicate your error by doing

Sys.setlocale("LC_ALL", "Italian_Italy.1252")
pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")
#> Error in xts(as.matrix(suppressWarnings(as.numeric(fr[, 2]))), dates,  :
#>   'order.by' cannot contain 'NA', 'NaN', or 'Inf'

and fix it by doing

Sys.setlocale("LC_ALL", "English_United Kingdom.1252")
pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")
#>            ICP.M.U2.Y.XEFUN0.3.INX
#> 1997-01-31                   75.45
#> 1997-02-28                   75.52
#> 1997-03-31                   75.59
#> 1997-04-30                   75.61
#> 1997-05-31                   75.71
#> 1997-06-30                   75.76
#> ...

So this should work for you:

Sys.setlocale("LC_ALL", "English_United Kingdom.1252")
result <- pdfetch_ECB("ICP.M.U2.Y.XEFUN0.3.INX")
Sys.setlocale("LC_ALL", "Italian_Italy.1252")


问:
Maximum height of the staircase
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.

Your submission failed for the following input: A : 92761

Your function returned the following : 65536

The expected returned value : 430

```<code>Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…

Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.
</code>```

CODE

```<code>public int solve(int A) {
        int l=1,h=A,T=2*A;
        while(l<=h)
        {
            int mid=l+(h-l)/2;
            if((mid*(mid+1))==T)
                return mid;
            if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
                return mid-1;
            if((mid*(mid+1))>T)
                h=mid-1;
            else
                l=mid+1;
        }
        return 0;
    }
</code>```

答:
Why are you using all these formulas? A simple while() loop should do the trick, eventually, it's just a simple Gaussian Sum ..

```<code>public static int calculateStairs(int blocks) {
    int lastHeight = 0;
    int sum = 0;
    int currentHeight = 0; //number of bricks / level
    while (sum <= blocks) {
        lastHeight = currentHeight;
        currentHeight++;
        sum += currentHeight;
    }
    return lastHeight;
}
</code>```

Title: Maximum height of the staircase

Body:
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.

Your submission failed for the following input: A : 92761

Your function returned the following : 65536

The expected returned value : 430

Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…

Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.

CODE

public int solve(int A) {
        int l=1,h=A,T=2*A;
        while(l<=h)
        {
            int mid=l+(h-l)/2;
            if((mid*(mid+1))==T)
                return mid;
            if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
                return mid-1;
            if((mid*(mid+1))>T)
                h=mid-1;
            else
                l=mid+1;
        }
        return 0;
    }

Body:
Why are you using all these formulas? A simple while() loop should do the trick, eventually, it's just a simple Gaussian Sum ..

public static int calculateStairs(int blocks) {
    int lastHeight = 0;
    int sum = 0;
    int currentHeight = 0; //number of bricks / level
    while (sum <= blocks) {
        lastHeight = currentHeight;
        currentHeight++;
        sum += currentHeight;
    }
    return lastHeight;
}


问:
Pivot row values matching a pattern into column names
I have data that look like this:

```<code>OH_IDNR  OCV_VNAME                              OCV_VALUE
8420518  response_part_0_script_0_code_0        $[*].id
8420518  response_part_0_script_0_queryType     JSONPath
8420518  response_part_0_script_0_resourceName  profileIds#
8420518  response_part_0_script_0_saveTo        variable
8420518  response_part_0_script_0_useArray      TRUE
8420518  response_part_0_script_1_code_0        $[*].name
8420518  response_part_0_script_1_queryType     JSONPath
8420518  response_part_0_script_1_resourceName  profileNames#
8420518  response_part_0_script_1_saveTo        variable
8420518  response_part_0_script_1_useArray      TRUE
8420518  response_part_0_script_2_code_0        $[*].environment
8420518  response_part_0_script_2_queryType     JSONPath
8420518  response_part_0_script_2_resourceName  profileEnvironments#
8420518  response_part_0_script_2_saveTo        variable
8420518  response_part_0_script_2_useArray      TRUE
8420518  response_part_0_script_3_code_0        $[*].description
8420518  response_part_0_script_3_queryType     JSONPath
8420518  response_part_0_script_3_resourceName  profileDescriptions#
8420518  response_part_0_script_3_saveTo        variable
8420518  response_part_0_script_3_useArray      TRUE

</code>```

I would like to pivot these data so that for each set of rows with the same OH_IDNR and with the same common/non-unique part of OCV_VNAME, these columns are returned:

OH_IDNR

The common part of OCV_VNAME (e.g., 'response_part_0_script_0_')

– n. One column for each unique part of OCV_Name (e.g.,' resourceName'), with OCV_VALUE as the value.

E.g.,

```<code>OH_IDNR  OCV_VNAME_common           code_0            queryType  resourceName          saveTo    useArray
8420518  response_part_0_script_0_  $[*].id           JSONPath   profileIds#           variable  TRUE
8420518  response_part_0_script_1_  $[*].name         JSONPath   profileNames#         variable  TRUE
8420518  response_part_0_script_2_  $[*].environment  JSONPath   profileEnvironments#  variable  TRUE
8420518  response_part_0_script_3_  $[*].description  JSONPath   profileDescriptions#  variable  TRUE

</code>```

This obviously assumes that the unique part of OCV_VNAME is a string suitable for use as a column name. I’ve tried a few things, but the elegant solution eludes me.

答:
You can do conditional aggregation:

```<code>select
    oh_idnr,
    regexp_substr(ocv_vname, 'response_part_0_script_\d_') ocv_vname_common,
    max(case when ocv_vname like '%_code_0' then ocv_value end) code_0,
    max(case when ocv_vname like '%_queryType' then ocv_value end) queryType,
    max(case when ocv_vname like '%_resourceName' then ocv_value end) resourceName,
    max(case when ocv_vname like '%_saveTo' then ocv_value end) saveTo,
    max(case when ocv_vname like '%_useArray' then ocv_value end) useArray
from mytable
group by oh_idnr, regexp_substr(ocv_vname, 'response_part_0_script_\d_')
</code>```

Demo on DB Fiddle:

```
OH_IDNR | OCV_VNAME_COMMON          | CODE_0           | QUERYTYPE | RESOURCENAME         | SAVETO   | USEARRAY
------: | :------------------------ | :--------------- | :-------- | :------------------- | :------- | :-------
8420518 | response_part_0_script_0_ | $[*].id          | JSONPath  | profileIds#          | variable | TRUE
8420518 | response_part_0_script_1_ | $[*].name        | JSONPath  | profileNames#        | variable | TRUE
8420518 | response_part_0_script_2_ | $[*].environment | JSONPath  | profileEnvironments# | variable | TRUE
8420518 | response_part_0_script_3_ | $[*].description | JSONPath  | profileDescriptions# | variable | TRUE
```

You might find it more readable to parse in a subquery first:

```<code>select
    oh_idnr,
    ocv_vname_common,
    max(case when ocv_var_name = 'code_0' then ocv_value end) code_0,
    max(case when ocv_var_name = 'queryType' then ocv_value end) queryType,
    max(case when ocv_var_name = 'resourceName' then ocv_value end) resourceName,
    max(case when ocv_var_name = 'saveTo' then ocv_value end) saveTo,
    max(case when ocv_var_name = 'useArray' then ocv_value end) useArray
from (
    select
        oh_idnr,
        regexp_substr(ocv_vname, 'response_part_0_script_\d_') ocv_vname_common,
        regexp_replace(ocv_vname, 'response_part_0_script_\d_', '') ocv_var_name,
        ocv_value
    from mytable
) t
group by oh_idnr, ocv_vname_common
</code>```

Demo on DB Fiddle

Body:
I have data that look like this:

OH_IDNR  OCV_VNAME                              OCV_VALUE
8420518  response_part_0_script_0_code_0        $[*].id
8420518  response_part_0_script_0_queryType     JSONPath
8420518  response_part_0_script_0_resourceName  profileIds#
8420518  response_part_0_script_0_saveTo        variable
8420518  response_part_0_script_0_useArray      TRUE
8420518  response_part_0_script_1_code_0        $[*].name
8420518  response_part_0_script_1_queryType     JSONPath
8420518  response_part_0_script_1_resourceName  profileNames#
8420518  response_part_0_script_1_saveTo        variable
8420518  response_part_0_script_1_useArray      TRUE
8420518  response_part_0_script_2_code_0        $[*].environment
8420518  response_part_0_script_2_queryType     JSONPath
8420518  response_part_0_script_2_resourceName  profileEnvironments#
8420518  response_part_0_script_2_saveTo        variable
8420518  response_part_0_script_2_useArray      TRUE
8420518  response_part_0_script_3_code_0        $[*].description
8420518  response_part_0_script_3_queryType     JSONPath
8420518  response_part_0_script_3_resourceName  profileDescriptions#
8420518  response_part_0_script_3_saveTo        variable
8420518  response_part_0_script_3_useArray      TRUE

I would like to pivot these data so that for each set of rows with the same OH_IDNR and with the same common/non-unique part of OCV_VNAME, these columns are returned:

OH_IDNR

The common part of OCV_VNAME (e.g., 'response_part_0_script_0_')

– n. One column for each unique part of OCV_Name (e.g.,' resourceName'), with OCV_VALUE as the value.

E.g.,

OH_IDNR  OCV_VNAME_common           code_0            queryType  resourceName          saveTo    useArray
8420518  response_part_0_script_0_  $[*].id           JSONPath   profileIds#           variable  TRUE
8420518  response_part_0_script_1_  $[*].name         JSONPath   profileNames#         variable  TRUE
8420518  response_part_0_script_2_  $[*].environment  JSONPath   profileEnvironments#  variable  TRUE
8420518  response_part_0_script_3_  $[*].description  JSONPath   profileDescriptions#  variable  TRUE

This obviously assumes that the unique part of OCV_VNAME is a string suitable for use as a column name. I’ve tried a few things, but the elegant solution eludes me.

Body:
You can do conditional aggregation:

select
    oh_idnr,
    regexp_substr(ocv_vname, 'response_part_0_script_\d_') ocv_vname_common,
    max(case when ocv_vname like '%_code_0' then ocv_value end) code_0,
    max(case when ocv_vname like '%_queryType' then ocv_value end) queryType,
    max(case when ocv_vname like '%_resourceName' then ocv_value end) resourceName,
    max(case when ocv_vname like '%_saveTo' then ocv_value end) saveTo,
    max(case when ocv_vname like '%_useArray' then ocv_value end) useArray
from mytable
group by oh_idnr, regexp_substr(ocv_vname, 'response_part_0_script_\d_')

Demo on DB Fiddle:

OH_IDNR | OCV_VNAME_COMMON          | CODE_0           | QUERYTYPE | RESOURCENAME         | SAVETO   | USEARRAY
------: | :------------------------ | :--------------- | :-------- | :------------------- | :------- | :-------
8420518 | response_part_0_script_0_ | $[*].id          | JSONPath  | profileIds#          | variable | TRUE
8420518 | response_part_0_script_1_ | $[*].name        | JSONPath  | profileNames#        | variable | TRUE
8420518 | response_part_0_script_2_ | $[*].environment | JSONPath  | profileEnvironments# | variable | TRUE
8420518 | response_part_0_script_3_ | $[*].description | JSONPath  | profileDescriptions# | variable | TRUE

You might find it more readable to parse in a subquery first:

select
    oh_idnr,
    ocv_vname_common,
    max(case when ocv_var_name = 'code_0' then ocv_value end) code_0,
    max(case when ocv_var_name = 'queryType' then ocv_value end) queryType,
    max(case when ocv_var_name = 'resourceName' then ocv_value end) resourceName,
    max(case when ocv_var_name = 'saveTo' then ocv_value end) saveTo,
    max(case when ocv_var_name = 'useArray' then ocv_value end) useArray
from (
    select
        oh_idnr,
        regexp_substr(ocv_vname, 'response_part_0_script_\d_') ocv_vname_common,
        regexp_replace(ocv_vname, 'response_part_0_script_\d_', '') ocv_var_name,
        ocv_value
    from mytable
) t
group by oh_idnr, ocv_vname_common

Demo on DB Fiddle


问:
Why rows disappear when I click on filter in ag-grid?
When I click on the filter icon next to each column, it opens the popup showing the options for selecting the filter, however only the popup shows, the actual grid behind it vanishes. So the popup is just floating on an empty background. When I close the popup, the grid returns.
I use Vue.js only by
My html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="./node_modules/ag-grid-community/dist/ag-grid-community.min.noStyle.js"></script>
  <link rel="stylesheet" href="node_modules/xel/themes/material.css">
  <link rel="stylesheet" href="css/style.css">
  <title>Test</title>
</head>
<body>

  <div id="app">

    <app-header :par="'test'"></app-header>
    <app-grid ref="grid"></app-grid>

  </div>

  <script src="../node_modules/xel/xel.min.js"></script>
  <script src="./js/vue.js"></script>
  <script src="./js/render.js"></script>
</body>
</html>
</code>```

My js:

```<code>class Spreadsheet {
  constructor(
    rowData = [],
    columnDefs = [
      {
        headerName: 'Name',
        field: 'name',
        sortable: true,
        checkboxSelection: true,
        headerCheckboxSelection: true,
        filter: 'agTextColumnFilter',
        filterParams: {
          clearButton: true,
          debounceMs: 200
        }
      },
      {
        headerName: 'Model',
        field: 'model',
        sortable: true,
        filter: 'agTextColumnFilter',
        filterParams: {
          clearButton: true,
          debounceMs: 200
        }
      },
      {
        headerName: 'Price',
        field: 'price',
        sortable: true,
        editable: true,
        filter: 'agNumberColumnFilter',
        filterParams: {
          clearButton: true,
          debounceMs: 200
        }
      }
    ]
  ) {
    this.template = `
    <div class="spreadsheet">
      <x-input class="filter" type="text" @input="filter">
        <x-label>filter...</x-label>
      </x-input>
      <div ref="grid_vue" class="ag-theme-fresh"></div>
    </div>
    `
    this.data = function() {
      return {
        columnDefs: null,
        rowData: null,
        gridOptions: null,
        devices: []
      }
    }

    this.beforeMount = function() {
      this.devices = rowData;
      this.gridOptions = {
        suppressDragLeaveHidesColumns: true,
        defaultColDef: {
          filter: true,
          resizable: true,
          width: 100
        },
        columnDefs: columnDefs,
        rowData: rowData,
        enableCellChangeFlash: true,
        animateRows: true,
        rowSelection: 'multiple',
        onGridReady: function(params) {
          params.api.sizeColumnsToFit();
        }
      }
    }
  }

  methods = {
    addItem(item_obj) {
      this.devices.push(item_obj);
      this.gridOptions.api.setRowData(this.devices);
    },
    filter(event) {
      const filter_text = event.target.value;
      this.gridOptions.api.setQuickFilter(filter_text);
    },
    redrawAllRows() {
      this.gridOptions.api.refreshCells();
      this.gridOptions.api.redrawRows();
    }
  }

  mounted = function() {
    const eGridDiv = this.$refs.grid_vue;
    new agGrid.Grid(eGridDiv, this.gridOptions);
  }

  beforeUpdate = function() {
    console.log('beforeUpdate');
    this.redrawAllRows();
  }

}

const devices = [
  {name: "phone", model: 'Sumsung', price: 35000, class: "smartphone"},
  {name: "laptop", model: 'HP', price: 32000, class: "pc"},
  {name: "test", model: 'Test', price: 72000, class: "test"}
];

const app_table = new Spreadsheet(devices);
const app_header = {
  props: ['par'],
  template: `
  <div class="pageHeader">
    <x-button class="addDongleButton" @click="addItem">
      <x-label>Add Item</x-label>
    </x-button>
  </div>
  `,
  methods: {
    addItem() {
      console.log(this.par);
      const some_obj = {name: "Test2", model: 'X2', price: 555, class: "test"};
      vm.$refs.grid.addItem(some_obj);
    }
  }
};

const vm = new Vue({
  el: "#app",
  components: {
    appHeader: app_header,
    appGrid: app_table
  }
});
</code>```

Css:

```<code>@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-fresh.css";

*, *::after, *::before {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

body {
  background: rgb(241, 241, 241);
  box-sizing: border-box;
}

.pageHeader {
  z-index: 1000;
  background: #a1c4dd;
  height: 75px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
}

.spreadsheet {
  margin: 85px 5% 20px;
}

.filter {
  display: inline-block;
  height: 25px;
  margin-bottom: 5px;
}

.ag-theme-fresh {
  height: 400px;
  width: 100%;
}

.ag-theme-fresh.ag-dnd-ghost {
  width: 30%;
  min-width: 100px;
}
</code>```

答:
Same thing happened to me while using Svelte, used the answer by joolsf.
When checking ".ag-theme-balham" was also applied to the div as explained by joolsf. In there a min-height was set. This means I had to add the following:</p>

```<code>.ag-popup {
    height: 0 !important;
    min-height: 0 !important;
}
</code>```

Body:
When I click on the filter icon next to each column, it opens the popup showing the options for selecting the filter, however only the popup shows, the actual grid behind it vanishes. So the popup is just floating on an empty background. When I close the popup, the grid returns.
I use Vue.js only by
My html:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="node_modules/xel/themes/material.css">
  <link rel="stylesheet" href="css/style.css">
  <title>Test</title>

    <app-header :par="'test'"></app-header>
    <app-grid ref="grid"></app-grid>

My js:

class Spreadsheet {
  constructor(
    rowData = [],
    columnDefs = [
      {
        headerName: 'Name',
        field: 'name',
        sortable: true,
        checkboxSelection: true,
        headerCheckboxSelection: true,
        filter: 'agTextColumnFilter',
        filterParams: {
          clearButton: true,
          debounceMs: 200
        }
      },
      {
        headerName: 'Model',
        field: 'model',
        sortable: true,
        filter: 'agTextColumnFilter',
        filterParams: {
          clearButton: true,
          debounceMs: 200
        }
      },
      {
        headerName: 'Price',
        field: 'price',
        sortable: true,
        editable: true,
        filter: 'agNumberColumnFilter',
        filterParams: {
          clearButton: true,
          debounceMs: 200
        }
      }
    ]
  ) {
    this.template = `

      <x-input class="filter" type="text" @input="filter">
        <x-label>filter...</x-label>
      </x-input>

    `
    this.data = function() {
      return {
        columnDefs: null,
        rowData: null,
        gridOptions: null,
        devices: []
      }
    }

    this.beforeMount = function() {
      this.devices = rowData;
      this.gridOptions = {
        suppressDragLeaveHidesColumns: true,
        defaultColDef: {
          filter: true,
          resizable: true,
          width: 100
        },
        columnDefs: columnDefs,
        rowData: rowData,
        enableCellChangeFlash: true,
        animateRows: true,
        rowSelection: 'multiple',
        onGridReady: function(params) {
          params.api.sizeColumnsToFit();
        }
      }
    }
  }

  methods = {
    addItem(item_obj) {
      this.devices.push(item_obj);
      this.gridOptions.api.setRowData(this.devices);
    },
    filter(event) {
      const filter_text = event.target.value;
      this.gridOptions.api.setQuickFilter(filter_text);
    },
    redrawAllRows() {
      this.gridOptions.api.refreshCells();
      this.gridOptions.api.redrawRows();
    }
  }

  mounted = function() {
    const eGridDiv = this.$refs.grid_vue;
    new agGrid.Grid(eGridDiv, this.gridOptions);
  }

  beforeUpdate = function() {
    console.log('beforeUpdate');
    this.redrawAllRows();
  }

}

const devices = [
  {name: "phone", model: 'Sumsung', price: 35000, class: "smartphone"},
  {name: "laptop", model: 'HP', price: 32000, class: "pc"},
  {name: "test", model: 'Test', price: 72000, class: "test"}
];

const app_table = new Spreadsheet(devices);
const app_header = {
  props: ['par'],
  template: `

    <x-button class="addDongleButton" @click="addItem">
      <x-label>Add Item</x-label>
    </x-button>

  `,
  methods: {
    addItem() {
      console.log(this.par);
      const some_obj = {name: "Test2", model: 'X2', price: 555, class: "test"};
      vm.$refs.grid.addItem(some_obj);
    }
  }
};

const vm = new Vue({
  el: "#app",
  components: {
    appHeader: app_header,
    appGrid: app_table
  }
});

Css:

@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-fresh.css";

*, *::after, *::before {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

body {
  background: rgb(241, 241, 241);
  box-sizing: border-box;
}

.pageHeader {
  z-index: 1000;
  background: #a1c4dd;
  height: 75px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
}

.spreadsheet {
  margin: 85px 5% 20px;
}

.filter {
  display: inline-block;
  height: 25px;
  margin-bottom: 5px;
}

.ag-theme-fresh {
  height: 400px;
  width: 100%;
}

.ag-theme-fresh.ag-dnd-ghost {
  width: 30%;
  min-width: 100px;
}

Body:
Same thing happened to me while using Svelte, used the answer by joolsf.
When checking ".ag-theme-balham" was also applied to the div as explained by joolsf. In there a min-height was set. This means I had to add the following:

.ag-popup {
    height: 0 !important;
    min-height: 0 !important;
}


问:
Unit testing lazy loaded modules routing
I'm facing some problems with unit testing for routing. I've tried this solution, but this lazy loading notation is now deprecated, so my tests are failed for some reason.
Could someone give me advice what might be wrong with my code?

app-routing.module.ts:

```<code>export const routes: Routes = [
{path: 'about', component: AboutComponent},
{path: 'files', loadChildren: () => import('./files/files.module').then(m => m.FilesModule)},
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

app-routing.module.spec.ts:

```<code>describe('AppRoutingModule', () => {
   let location: Location;
   let router: Router;
   let fixture;

   beforeEach(() => {
   TestBed.configureTestingModule({
       imports:[
           RouterTestingModule.withRoutes(routes),
           HttpClientModule,
           AboutComponent,
       ],
       declarations: [
           AppComponent,
           FilesComponent,
       ],
       providers: [{provide: APP_BASE_HREF, useValue: '/'}]
   })

   router = TestBed.get(Router);
   location = TestBed.get(Location);

   fixture = TestBed.createComponent(AppComponent);
   router.initialNavigation();
   });

   it('should navigate to files', fakeAsync(() => {
       const loader = TestBed.get(NgModuleFactoryLoader);
       loader.stubbedModules = {lazyModule : FilesModule }

       router.resetConfig([
           {path: 'files', loadChildren: 'lazyModule'},
       ]);

       router.navigate(['files']);
       tick(50);
       fixture.detectChanges();

       expect(location.path()).toBe('/files');
   }));
});

</code>```

Thank you!

答:
Did you try:

```<code>router.resetConfig([
  { path: 'files', loadChildren: () => Promise.resolve(FilesModule) },
 ]);
</code>```

?

Or at this point it could be just an spy

```<code>const spy = jasmine.createSpy('loadChildren');
...
router.resetConfig([
  { path: 'files', loadChildren: spy  },
 ]);
...
expect(spy).toHaveBeenCalled();
</code>```

Not tested to so no idea if it will work.

Body:
I'm facing some problems with unit testing for routing. I've tried this solution, but this lazy loading notation is now deprecated, so my tests are failed for some reason.
Could someone give me advice what might be wrong with my code?

app-routing.module.ts:

export const routes: Routes = [
{path: 'about', component: AboutComponent},
{path: 'files', loadChildren: () => import('./files/files.module').then(m => m.FilesModule)},
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

app-routing.module.spec.ts:

describe('AppRoutingModule', () => {
   let location: Location;
   let router: Router;
   let fixture;

   beforeEach(() => {
   TestBed.configureTestingModule({
       imports:[
           RouterTestingModule.withRoutes(routes),
           HttpClientModule,
           AboutComponent,
       ],
       declarations: [
           AppComponent,
           FilesComponent,
       ],
       providers: [{provide: APP_BASE_HREF, useValue: '/'}]
   })

   router = TestBed.get(Router);
   location = TestBed.get(Location);

   fixture = TestBed.createComponent(AppComponent);
   router.initialNavigation();
   });

   it('should navigate to files', fakeAsync(() => {
       const loader = TestBed.get(NgModuleFactoryLoader);
       loader.stubbedModules = {lazyModule : FilesModule }

       router.resetConfig([
           {path: 'files', loadChildren: 'lazyModule'},
       ]);

       router.navigate(['files']);
       tick(50);
       fixture.detectChanges();

       expect(location.path()).toBe('/files');
   }));
});

Thank you!

Body:
Did you try:

router.resetConfig([
  { path: 'files', loadChildren: () => Promise.resolve(FilesModule) },
 ]);

?

Or at this point it could be just an spy

const spy = jasmine.createSpy('loadChildren');
...
router.resetConfig([
  { path: 'files', loadChildren: spy  },
 ]);
...
expect(spy).toHaveBeenCalled();

Not tested to so no idea if it will work.


问:
How to set up Android emulator proxy settings
I want to to use the browser inside the Android emulator, and I want to use the proxy settings on my machine. How can I set this up?

Reading the very good Android manuals, they tell me that I should start Android using the following command:

```<code>emulator -avd myavd -http-proxy http://168.192.1.2:3300
</code>```

But I am still not able to use the emulator browser. Please note that I am using the IP address for my proxy server.

What am I doing wrong?

答:
The simplest and the best way is to do the following:
This has been done for Android Emulator 2.2

Click on Menu

Click on Settings

Click on Wireless & Networks

Go to Mobile Networks

Go to Access Point Names

Here you will Telkila Internet, click on it.

In the Edit access point section, input the "proxy" and "port"

Also provide the Username and Password, rest of the fields leave them blank.

Body:
I want to to use the browser inside the Android emulator, and I want to use the proxy settings on my machine. How can I set this up?

Reading the very good Android manuals, they tell me that I should start Android using the following command:

emulator -avd myavd -http-proxy http://168.192.1.2:3300

But I am still not able to use the emulator browser. Please note that I am using the IP address for my proxy server.

What am I doing wrong?