问:
javax.xml.stream.XMLStreamException: ParseError in hibernate configuration file
I am working on writing a most minimal program to do CRUD operations on mysql using hibernate in Java.

I am following below tutorial at:

https://medium.com/@amrut.patil88/crud-with-java-hibernate-and-mysql-part-1-f6b1d6f7dbbf

I have created user in mysql and started it.

CreateStudentDemo.java is :

```<code>import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

//import com.luv2code.hibernate.demo.entity.Student;

public class CreateStudentDemo {

    public static void main(String[] args) {

        //create a Session Factory

        SessionFactory sessionFactory = new Configuration().
                configure("hibernate.cfg.xml").
                addAnnotatedClass(Student.class).
                buildSessionFactory();

        //create a Session
        Session session = sessionFactory.getCurrentSession();

        try{

            System.out.println("Creating a new Student object...");

            //create the Student object
            Student student = new Student("Paul", "Walker","paul.walker@gmail.com");

            //start a transaction
            session.beginTransaction();

            //Save the Student object to the database
            session.save(student);

            System.out.println("Java object saved to the database");
            //commit the transaction
            session.getTransaction().commit();

        }finally{

            sessionFactory.close();
        }
    }

}
</code>```

Student.java is:

```<code>//package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name=”student”)
public class Student {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name=”id”)
 private int id;

 @Column(name=”first_name”)
 private String firstName;

 @Column(name=”last_name”)
 private String lastName;

 @Column(name=”email”)
 private String email;
 public Student(){

 }

 public Student(String firstName, String lastName, String email) {
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }
public int getId() {
 return id;
 }
public void setId(int id) {
 this.id = id;
 }
public String getFirstName() {
 return firstName;
 }
public void setFirstName(String firstName) {
 this.firstName = firstName;
 }
public String getLastName() {
 return lastName;
 }
public void setLastName(String lastName) {
 this.lastName = lastName;
 }
public String getEmail() {
 return email;
 }
public void setEmail(String email) {
 this.email = email;
 }
@Override
 public String toString() {
 return “Student [id=” + id + “, firstName=” + firstName + “, lastName=” + lastName + “, email=” + email + “]”;
 }
}
</code>```

In Student.java,

my eclipse is showing error on :  @Table(name=”student”)

```<code>"syntax error on tokens. delete these tokens".
</code>```

Is it because some library/jar is not installed?

hibernate.cfg.xml is:

```<code><!DOCTYPE hibernate-configuration SYSTEM
    "classpath:hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory> <! — allows us to get session objects for connecting to the database -->
<! — JDBC Database connection settings -->
 <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
 <property name=”connection.url”>jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false</property>
 <property name=”connection.username”>hb_student2</property>
 <property name=”connection.password”>Student123&$,</property>
<! — JDBC connection pool settings … using built-in test pool -->
 <property name=”connection.pool_size”>1</property>
<! — Select our SQL dialect -->
 <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<! — Echo the SQL to stdout -->
 <property name=”show_sql”>true</property>
<! — Set the current session context -->
 <property name=”current_session_context_class”>thread</property>

 </session-factory>
</hibernate-configuration>
</code>```

I have created a project in eclipse and have copied "required" jars from hibernate downnload.

Now, when I run CreateStudentDemo.java, I get below error:

```<code>Jun 02, 2020 2:57:29 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.17.Final
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:234)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
    at CreateStudentDemo.main(CreateStudentDemo.java:14)
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,21]
Message: The content of elements must consist of well-formed character data or markup.]
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:485)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:463)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:435)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
    ... 5 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,21]
Message: The content of elements must consist of well-formed character data or markup.
    at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
    at com.sun.xml.internal.stream.XMLEventReaderImpl.peek(Unknown Source)
    at javax.xml.stream.util.EventReaderDelegate.peek(Unknown Source)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor$NamespaceAddingEventReader.peek(JaxbCfgProcessor.java:254)
    at com.sun.xml.bind.v2.runtime.unmarshaller.StAXEventConnector.handleCharacters(StAXEventConnector.java:179)
    at com.sun.xml.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:141)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:460)
    ... 7 more
</code>```

Please help.

答:
I think it's because you are using a special character ” instead of ". there is big difference between them. so try to replace ” with " in all your code. this happens always especially if you copy code from a tutorial which is using wrong characters.

also in the XML file, for the comment it must be done this way  and not <! — comment -->

copy paste, I replaced all of them for you :)

Student.java :

```<code>//package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id")
 private int id;

 @Column(name="first_name")
 private String firstName;

 @Column(name="last_name")
 private String lastName;

 @Column(name="email")
 private String email;
 public Student(){

 }

 public Student(String firstName, String lastName, String email) {
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }
public int getId() {
 return id;
 }
public void setId(int id) {
 this.id = id;
 }
public String getFirstName() {
 return firstName;
 }
public void setFirstName(String firstName) {
 this.firstName = firstName;
 }
public String getLastName() {
 return lastName;
 }
public void setLastName(String lastName) {
 this.lastName = lastName;
 }
public String getEmail() {
 return email;
 }
public void setEmail(String email) {
 this.email = email;
 }
@Override
 public String toString() {
 return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
 }
}
</code>```

hibernate.cfg.xml :

```<code><!DOCTYPE hibernate-configuration SYSTEM "classpath:hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- allows us to get session objects for connecting to the database -->
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false</property>
        <property name="connection.username">hb_student2</property>
        <property name="connection.password">Student123&$,</property>
        <!-- JDBC connection pool settings … using built-in test pool -->
        <property name="connection.pool_size">1</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>

    </session-factory>
</hibernate-configuration>
</code>```

Body:
I am working on writing a most minimal program to do CRUD operations on mysql using hibernate in Java.

I am following below tutorial at:

https://medium.com/@amrut.patil88/crud-with-java-hibernate-and-mysql-part-1-f6b1d6f7dbbf

I have created user in mysql and started it.

CreateStudentDemo.java is :

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

//import com.luv2code.hibernate.demo.entity.Student;

public class CreateStudentDemo {

    public static void main(String[] args) {

        //create a Session Factory

        SessionFactory sessionFactory = new Configuration().
                configure("hibernate.cfg.xml").
                addAnnotatedClass(Student.class).
                buildSessionFactory();

        //create a Session
        Session session = sessionFactory.getCurrentSession();

        try{

            System.out.println("Creating a new Student object...");

            //create the Student object
            Student student = new Student("Paul", "Walker","paul.walker@gmail.com");

            //start a transaction
            session.beginTransaction();

            //Save the Student object to the database
            session.save(student);

            System.out.println("Java object saved to the database");
            //commit the transaction
            session.getTransaction().commit();

        }finally{

            sessionFactory.close();
        }
    }

}

Student.java is:

//package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name=”student”)
public class Student {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name=”id”)
 private int id;

 @Column(name=”first_name”)
 private String firstName;

 @Column(name=”last_name”)
 private String lastName;

 @Column(name=”email”)
 private String email;
 public Student(){

 }

 public Student(String firstName, String lastName, String email) {
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }
public int getId() {
 return id;
 }
public void setId(int id) {
 this.id = id;
 }
public String getFirstName() {
 return firstName;
 }
public void setFirstName(String firstName) {
 this.firstName = firstName;
 }
public String getLastName() {
 return lastName;
 }
public void setLastName(String lastName) {
 this.lastName = lastName;
 }
public String getEmail() {
 return email;
 }
public void setEmail(String email) {
 this.email = email;
 }
@Override
 public String toString() {
 return “Student [id=” + id + “, firstName=” + firstName + “, lastName=” + lastName + “, email=” + email + “]”;
 }
}

In Student.java,

my eclipse is showing error on :  @Table(name=”student”)

"syntax error on tokens. delete these tokens".

Is it because some library/jar is not installed?

hibernate.cfg.xml is:

<!DOCTYPE hibernate-configuration SYSTEM
    "classpath:hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory> <! — allows us to get session objects for connecting to the database -->
<! — JDBC Database connection settings -->
 <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
 <property name=”connection.url”>jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false</property>
 <property name=”connection.username”>hb_student2</property>
 <property name=”connection.password”>Student123&$,</property>
<! — JDBC connection pool settings … using built-in test pool -->
 <property name=”connection.pool_size”>1</property>
<! — Select our SQL dialect -->
 <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<! — Echo the SQL to stdout -->
 <property name=”show_sql”>true</property>
<! — Set the current session context -->
 <property name=”current_session_context_class”>thread</property>

 </session-factory>
</hibernate-configuration>

I have created a project in eclipse and have copied "required" jars from hibernate downnload.

Now, when I run CreateStudentDemo.java, I get below error:

Jun 02, 2020 2:57:29 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.17.Final
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:234)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
    at CreateStudentDemo.main(CreateStudentDemo.java:14)
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,21]
Message: The content of elements must consist of well-formed character data or markup.]
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:485)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:463)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:435)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
    ... 5 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,21]
Message: The content of elements must consist of well-formed character data or markup.
    at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
    at com.sun.xml.internal.stream.XMLEventReaderImpl.peek(Unknown Source)
    at javax.xml.stream.util.EventReaderDelegate.peek(Unknown Source)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor$NamespaceAddingEventReader.peek(JaxbCfgProcessor.java:254)
    at com.sun.xml.bind.v2.runtime.unmarshaller.StAXEventConnector.handleCharacters(StAXEventConnector.java:179)
    at com.sun.xml.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:141)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:460)
    ... 7 more

Please help.

Body:
I think it's because you are using a special character ” instead of ". there is big difference between them. so try to replace ” with " in all your code. this happens always especially if you copy code from a tutorial which is using wrong characters.

also in the XML file, for the comment it must be done this way <!-- comment --> and not <! — comment -->

copy paste, I replaced all of them for you :)

Student.java :

//package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id")
 private int id;

 @Column(name="first_name")
 private String firstName;

 @Column(name="last_name")
 private String lastName;

 @Column(name="email")
 private String email;
 public Student(){

 }

 public Student(String firstName, String lastName, String email) {
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }
public int getId() {
 return id;
 }
public void setId(int id) {
 this.id = id;
 }
public String getFirstName() {
 return firstName;
 }
public void setFirstName(String firstName) {
 this.firstName = firstName;
 }
public String getLastName() {
 return lastName;
 }
public void setLastName(String lastName) {
 this.lastName = lastName;
 }
public String getEmail() {
 return email;
 }
public void setEmail(String email) {
 this.email = email;
 }
@Override
 public String toString() {
 return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
 }
}

hibernate.cfg.xml :

<!DOCTYPE hibernate-configuration SYSTEM "classpath:hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- allows us to get session objects for connecting to the database -->
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false</property>
        <property name="connection.username">hb_student2</property>
        <property name="connection.password">Student123&$,</property>
        <!-- JDBC connection pool settings … using built-in test pool -->
        <property name="connection.pool_size">1</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>

    </session-factory>
</hibernate-configuration>


来源: stackexchange

问:
How do I escape a special Regex character?
I've encountered a problem in Java, specific to the String.split function.
I'm porting my C# code to Java, and something bothers Java. My C# code is as follows :

```<code>foreach (char sep in separators)
    if (text.Contains(sep.ToString()))
        array = text.Reverse().Split(sep);
</code>```

Reverse() is an extension I've made myself which just reverses a string.
separators is a char array that contains a few separators :

```<code>char[] separators = { '&', '!', '#', '?', '%' };
</code>```

Now, in Java, my code is as follows :

```<code>for (char sep : separators) {
    String sepp = String.valueOf(sep);
    if (text.contains(sepp))
        array = new StringBuilder(text).reverse().toString().split(sepp);
}
</code>```

The problem with this code is that, when I have the specific separator ? (it's randomly choosed), then it throws me this error (Java only) :

```<code>Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
at java.base/java.util.regex.Pattern.error(Pattern.java:2027)
at java.base/java.util.regex.Pattern.sequence(Pattern.java:2202)
at java.base/java.util.regex.Pattern.expr(Pattern.java:2068)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1782)
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.split(String.java:2317)
at java.base/java.lang.String.split(String.java:2364)
at com.anerruption.encryption.Main.decrypt(Main.java:58)
at com.anerruption.encryption.Main.main(Main.java:43)
</code>```

My guess is that the function string.Split in C# doesn't use Regex, but the one in Java does. From what I've heard, I need to escape the character. Doing \\? did not work. How could I do this?

Any help is greatly appreciated!

答:
Meta Character Description .........................................Escape character

```<code>*   zero or more occurrence of the characters        \\*
+   one or more occurrence of the characters         \\+
?   zero or only one occurrence of the characters    \\?
^   Start of the character sequence                  \\^
$   End of the character sequence                    \\$
</code>```

Example of ?

```<code> public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] separators = { "&", "!", "#", "\\?", "%" };
    String str = "Parth?Prem";
    String str2 = "\\?";
    String[] strArray;

    strArray = str.split(str2);

    System.out.println("Given String : " + str);
    for(int i=0;i<strArray.length;i++) {
        System.out.println("strArray["+i+"] = " + strArray[i]);
    }

}
</code>```

Output:

Given String : Parth?Prem

strArray[0] = Parth

strArray[1] = Prem

ContentLicense: CC BY-SA 4.0

Body:
I've encountered a problem in Java, specific to the String.split function.
I'm porting my C# code to Java, and something bothers Java. My C# code is as follows :

foreach (char sep in separators)
    if (text.Contains(sep.ToString()))
        array = text.Reverse().Split(sep);

Reverse() is an extension I've made myself which just reverses a string.
separators is a char array that contains a few separators :

char[] separators = { '&', '!', '#', '?', '%' };

Now, in Java, my code is as follows :

for (char sep : separators) {
    String sepp = String.valueOf(sep);
    if (text.contains(sepp))
        array = new StringBuilder(text).reverse().toString().split(sepp);
}

The problem with this code is that, when I have the specific separator ? (it's randomly choosed), then it throws me this error (Java only) :

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
at java.base/java.util.regex.Pattern.error(Pattern.java:2027)
at java.base/java.util.regex.Pattern.sequence(Pattern.java:2202)
at java.base/java.util.regex.Pattern.expr(Pattern.java:2068)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1782)
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.split(String.java:2317)
at java.base/java.lang.String.split(String.java:2364)
at com.anerruption.encryption.Main.decrypt(Main.java:58)
at com.anerruption.encryption.Main.main(Main.java:43)

My guess is that the function string.Split in C# doesn't use Regex, but the one in Java does. From what I've heard, I need to escape the character. Doing \\? did not work. How could I do this?

Any help is greatly appreciated!

Body:
Meta Character Description .........................................Escape character

*   zero or more occurrence of the characters        \\*
+   one or more occurrence of the characters         \\+
?   zero or only one occurrence of the characters    \\?
^   Start of the character sequence                  \\^
$   End of the character sequence                    \\$

Example of ?

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] separators = { "&", "!", "#", "\\?", "%" };
    String str = "Parth?Prem";
    String str2 = "\\?";
    String[] strArray;

    strArray = str.split(str2);

    System.out.println("Given String : " + str);
    for(int i=0;i<strArray.length;i++) {
        System.out.println("strArray["+i+"] = " + strArray[i]);
    }

}

Output:

Given String : Parth?Prem

strArray[0] = Parth

strArray[1] = Prem


问:
capitalize first letter in Report Builder filed
I am writing a report using report builder and the one of the filed value of the data set is in upper-case I want to capitalize first letter of this data field value in the text box. Please let me know if you could help.

Thanks
Yogi

答:
In the report, you can do the casing with the Common Text Fuction StrConv() to make proper casing (first character of every word in capitals):

StrConv([Field].value, vbProperCase)

https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/strconv-function

If you only want the first character capitalized (and leave the rest as is):

UCase(Left([Field].value, 1)) & Right([Field].value, Len([Field].value) - 1)

(the question title refers to Report Builder, so the given answer in SQL might not suit erveryones needs)

ContentLicense: CC BY-SA 3.0


问:
Hiding the internal views and auto adjust the height of the cell swift
According to the following screenshot I have a table view cell with couple of stack views inside the cell. I want to hide the red circled stack view when it's inside label values are empty. To achieve this specific thing what I have done is just hiding the related stack view as the following screenshot. The related stack view is hiding. That's fine. But I want it to be hidden that empty area and adjust the height of the cell accordingly. I am not using the following function as well.

```<code>    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return 150
    }
</code>```

I have used the following function as well. But it's still the same.

```<code>    override func viewWillAppear(_ animated: Bool) {
        SalaryDetailTableView.rowHeight = UITableViewAutomaticDimension
        SalaryDetailTableView.estimatedRowHeight = 65.0
    }
</code>```

Could anyone please help me to sort out the issue ?

https://imgur.com/a/hMYA3qT

https://imgur.com/a/Dye8pBT

答:
From your first screenshot I can see that you are using AutoLayout. Wrap all your stack views in a base stack view, pin it to the cell and check and fix your other constraints if needed. After that, you need to specify

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableView.automaticDimension
}
</code>```

If your constraints are right, AutoLayout will take care of collapsing or expanding the cell when you hide your inner stack view.

Body:
According to the following screenshot I have a table view cell with couple of stack views inside the cell. I want to hide the red circled stack view when it's inside label values are empty. To achieve this specific thing what I have done is just hiding the related stack view as the following screenshot. The related stack view is hiding. That's fine. But I want it to be hidden that empty area and adjust the height of the cell accordingly. I am not using the following function as well.

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return 150
    }

I have used the following function as well. But it's still the same.

    override func viewWillAppear(_ animated: Bool) {
        SalaryDetailTableView.rowHeight = UITableViewAutomaticDimension
        SalaryDetailTableView.estimatedRowHeight = 65.0
    }

Could anyone please help me to sort out the issue ?

https://imgur.com/a/hMYA3qT

https://imgur.com/a/Dye8pBT

Body:
From your first screenshot I can see that you are using AutoLayout. Wrap all your stack views in a base stack view, pin it to the cell and check and fix your other constraints if needed. After that, you need to specify

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableView.automaticDimension
}

If your constraints are right, AutoLayout will take care of collapsing or expanding the cell when you hide your inner stack view.


问:
how to find user input value in the dictionary and display them, if it exists
```<code>MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })

def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title")
        if find in movies:
            print("movie found.", movies)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)

</code>```

if the user inputs the f for finding the movie name in the movies dictionary then what do I write in the last elif function, can anyone explain it??

I want - (userinput movie name) - avengers
output - match found! movie name - avengers, director - (what the userinputs) & year - (what the userinputs)

答:
You have a list with dictionaries that contain title, director and year keys. You can loop through the list and search a match for the title, assuming the user inputs the title:</p>

```<code>movies.append({
    'title': "title",
    'director': "director",
    'year': "year"
})

for m in movies:
    if m.get('title').lower().find("title") > -1:
        print("true")
    else:
        print("false")
</code>```

Body:
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })

def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title")
        if find in movies:
            print("movie found.", movies)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)

if the user inputs the f for finding the movie name in the movies dictionary then what do I write in the last elif function, can anyone explain it??

I want - (userinput movie name) - avengers
output - match found! movie name - avengers, director - (what the userinputs) & year - (what the userinputs)

Body:
You have a list with dictionaries that contain title, director and year keys. You can loop through the list and search a match for the title, assuming the user inputs the title:

movies.append({
    'title': "title",
    'director': "director",
    'year': "year"
})

for m in movies:
    if m.get('title').lower().find("title") > -1:
        print("true")
    else:
        print("false")


问:
gerate random token to user in laravel
on a site I'm trying to develop with a token, give me back this error, I've tried surfing the internet for solutions but so far nothing:\

If someone can help me thank you.

```<code>(1/1) Error
Call to undefined function App\Http\Controllers\str_random()
in UserController.php line 65
at UserController->doRegisto(object(Request))

else {
            Session::flash('message', "Este email está disponivel.");
        $user = new User;

        $user->nome = $request->nome;
        $user->morada = $request->morada;
        $user->distrito = $request->distrito;
        $user->cod_postal = $request->cod_postal;
        $user->localidade = $request->localidade;
        $user->nif = $request->nif;
        $user->telefone = $request->telefone;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);

        $user->save();

        $verificar = new verificar_user;
        $token = str_random(32);
        $verificar->id_user = $user->id;
        $verificar->token = $token;

        $data = ['token' => $token];
</code>```

答:
Try This:

```<code>use Illuminate\Support\Str;
$token = Str::random(32);
</code>```

Let me know if it help you!

Title: gerate random token to user in laravel

Body:
on a site I'm trying to develop with a token, give me back this error, I've tried surfing the internet for solutions but so far nothing:\

If someone can help me thank you.

(1/1) Error
Call to undefined function App\Http\Controllers\str_random()
in UserController.php line 65
at UserController->doRegisto(object(Request))

else {
            Session::flash('message', "Este email está disponivel.");
        $user = new User;

        $user->nome = $request->nome;
        $user->morada = $request->morada;
        $user->distrito = $request->distrito;
        $user->cod_postal = $request->cod_postal;
        $user->localidade = $request->localidade;
        $user->nif = $request->nif;
        $user->telefone = $request->telefone;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);

        $user->save();

        $verificar = new verificar_user;
        $token = str_random(32);
        $verificar->id_user = $user->id;
        $verificar->token = $token;

        $data = ['token' => $token];

Body:
Try This:

use Illuminate\Support\Str;
$token = Str::random(32);

Let me know if it help you!


问:
how to use django model object in django templates?
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the  ActivityPeriod(model) of that user. Please check my code for the clarity:

Here is my code:

views.py

```<code>from .models import User,ActivityPeriod

def call_response(request):
    user = User.objects.all()
    return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})
</code>```

Test/list.html

```<code>{% for user in users %}
    'real_name': {{ user.real_name}}},
    'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
    {{ activity.start_time }}
    {% endwith %}
{% endfor %}
</code>```

But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'

What is the correct way? Can anyone please share it with me.

答:
views.py

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

user = User.objects.filter(user=request.user)
activityperiod = activityperiod.objects.get(user=user)
context={'user':user,'activityperiod':activityperiod}
return render(request, "Test/list.html",context})
</code>```

Test/list.html

```<code>'real_name': {{ user.real_name}}
'activity_periods':{{ activityperiod.start_time }}
</code>```

Body:
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the  ActivityPeriod(model) of that user. Please check my code for the clarity:

Here is my code:

views.py

from .models import User,ActivityPeriod

def call_response(request):
    user = User.objects.all()
    return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})

Test/list.html

{% for user in users %}
    'real_name': {{ user.real_name}}},
    'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
    {{ activity.start_time }}
    {% endwith %}
{% endfor %}

But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'

What is the correct way? Can anyone please share it with me.

Body:
views.py

def call_response(request):

user = User.objects.filter(user=request.user)
activityperiod = activityperiod.objects.get(user=user)
context={'user':user,'activityperiod':activityperiod}
return render(request, "Test/list.html",context})

Test/list.html

'real_name': {{ user.real_name}}
'activity_periods':{{ activityperiod.start_time }}


问:
React FontAwesome Icon disappears when I add  tag
I am trying to add links to my font-awesome react component.

```<code><div>
    <FontAwesomeIcon icon={faHome} size="2x" />
<div>
</code>```

The component above renders the faHome icon.

But when I add anchor tag around it, it does not render. I can still see that the component in inspector tools with <svg> tag also loaded the same way when I didn't have anchor tag in the first example.

```<code><div>
    <a href="https://www.youtube.com/c/jamesqquick">
        <FontAwesomeIcon icon={faHome} size="2x" />
    </a>
</div>
</code>```

答:
it is working perfectly. Please check the below code:

```<code>import React from "react";
import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faHome } from "@fortawesome/free-solid-svg-icons";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <a href="https://www.youtube.com/">
          <FontAwesomeIcon icon={faHome} size="2x" />
        </a>
      </div>
    </div>
  );
}
</code>```

Here is the Code Sandbox

Here is output

Title: React FontAwesome Icon disappears when I add <a> tag

Body:
I am trying to add links to my font-awesome react component.

    <FontAwesomeIcon icon={faHome} size="2x" />

The component above renders the faHome icon.

But when I add anchor tag around it, it does not render. I can still see that the component in inspector tools with <svg> tag also loaded the same way when I didn't have anchor tag in the first example.

        <FontAwesomeIcon icon={faHome} size="2x" />

Body:
it is working perfectly. Please check the below code:

import React from "react";
import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faHome } from "@fortawesome/free-solid-svg-icons";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <a href="https://www.youtube.com/">
          <FontAwesomeIcon icon={faHome} size="2x" />
        </a>
      </div>
    </div>
  );
}

Here is the Code Sandbox

Here is output


问:
Coinitialize ex is failing inside a WMI call in a JNI program stub
Environment:

I have a JNI program which is made of the following pieces

C++ : Here I make use of WMI to return the running process details. The program is similar to the example in http://msdn.microsoft.com/en-us/library/aa390423(v=vs.85).aspx
I have encompassed the entire code in the example with a JNI wrapper (One of the parameters I send to the program is of type Integer). Below is the signature of that function

JNIEXPORT jdouble JNICALL Java_handlemonitor_NativeSytem_getSystemDetails(JNIEnv *env, jclass cls, jint pId)

The generated DLL is kept in the bin folder inside JDK directory

Java : Here I just call the function inside the dll and consume the returned value.
I also generate the .h file using the javah program and I have included it in the C++ program.

Issue: When I run the program, I get an error msg in the C++ program that CoInitializeEx failed with the error code 0x80010106.

following is the line where the program fails.

hres = CoInitializeEx(0,COINIT_MULTITHREADED).

I tried increasing the heapSize still it continues to fail.

Any particular reason why CoInitializeEx is failing?

Thanks in advance

答:
The error 0x80010106 means "HRESULT - 0x80010106 - Cannot change thread mode after it is set."

The problem is basically that a thread can Initialize its COM mode (and apartment type, STA/MTA) only once.  Once it is set, you will get this error if you attempt to initialize again with a different value.

Often what happens with this error is that some other 3rd-party code will cause COM to become initialized before your code is executed.  If this is the case, then you have a couple of choices:

1)  Try to find a way to have your code execute first, so you can set the COM apartment type yourself.  This can be tricky, and might cause side effects if the 3rd-party code expects an STA

2)  Put your code on its own thread, where you can explicitly set the apartment type

If you actually don't care about the apartment type, then you can just change the call to CoInitializeEx to use COINIT_APARTMENTTHREADED (STA) instead of COINIT_MULTITHREADED (MTA).

Hope that helps,

John


问:
ksqlDB not taking rowkey properly
I have produced following data on topic named SENSOR_STATUS_DETAILS in json:

```<code>1001
{
  "sensorid": 1001,
  "status": "CONNECTED",
  "lastconnectedtime": "2020-05-31 22:31:54"
}
1002
{
  "sensorid": 1002,
  "status": "CONNECTED",
  "lastconnectedtime": "2020-05-31 22:33:37"
}
</code>```

I am trying to make a table from it as:

```<code>CREATE TABLE STATUS_IB_TABLE (ROWKEY INT KEY,
  sensorid INTEGER,
  status VARCHAR,
  lastconnectedtime STRING)
WITH (TIMESTAMP='lastconnectedtime', TIMESTAMP_FORMAT='yyyy-MM-dd HH:mm:ss', KAFKA_TOPIC='SENSOR_STATUS_DETAILS', VALUE_FORMAT='JSON', KEY='sensorid');
</code>```

The rowkey ksqlDB is making is as follows:

I want the rowkey to be sensorid....
I don't know whats happening

please help me on this.

thanks in advance!!

PS:

Confluent Platform version: 5.5

答:
The issue here is that the data being produced to the Kafka topic SENSOR_STATUS_DETAILS has a STRING key, not an INT key.

If you take the STRING "1001" it just happens to serialize to the same number of bytes as an INT.  If you deserialize those same bytes as an INT you get the number 825241649.

You have two options:

Change how you are producing the data so that you are producing a serialized 32-bit integer as the Kafka message's key and continue to import as ROWKEY INT KEY, or

Change your CREATE TABLE statement to have a STRING key:

CREATE TABLE STATUS_IB_TABLE (
     ROWKEY STRING KEY,  // <-- string key
     sensorid STRING,    // <-- matching type here.
     status VARCHAR,
     lastconnectedtime STRING
)
WITH (<as above>);

The first option would likely result in slightly better performance

Title: ksqlDB not taking rowkey properly

Body:
I have produced following data on topic named SENSOR_STATUS_DETAILS in json:

1001
{
  "sensorid": 1001,
  "status": "CONNECTED",
  "lastconnectedtime": "2020-05-31 22:31:54"
}
1002
{
  "sensorid": 1002,
  "status": "CONNECTED",
  "lastconnectedtime": "2020-05-31 22:33:37"
}

I am trying to make a table from it as:

CREATE TABLE STATUS_IB_TABLE (ROWKEY INT KEY,
  sensorid INTEGER,
  status VARCHAR,
  lastconnectedtime STRING)
WITH (TIMESTAMP='lastconnectedtime', TIMESTAMP_FORMAT='yyyy-MM-dd HH:mm:ss', KAFKA_TOPIC='SENSOR_STATUS_DETAILS', VALUE_FORMAT='JSON', KEY='sensorid');

The rowkey ksqlDB is making is as follows:

I want the rowkey to be sensorid....
I don't know whats happening

please help me on this.

thanks in advance!!

PS:

Confluent Platform version: 5.5


问:
Is it possible to set top_level for bdist_wheel?
I have a project with a structure similar to this:

```<code>project_name
  |_ module_1
    |_ submodule1
    |_ file1.py
  |_ module_2
  |_ filea.py
  |_ fileb.py
  |_ setup.py
</code>```

If I create a bdist_wheel from it, when installing I will get the files and module folder directly under site-packages.

I can add another level to the tree, like so:

```<code>project_name
  some_name
    |_ module_1
      |_ submodule1
      |_ file1.py
    |_ module_2
    |_ filea.py
    |_ fileb.py
    |_ setup.py
</code>```

and then I get everything installed under some_name in site-packages.

Question is, can I achieve the same by somehow setting top_level or by other means that doesn't require adding another folder to the hierarchy (code is like in former in GIT)?

答:
Maybe something like the following could work, but I am not sure (haven't tested it), it might also be required to exclude setup.py somehow, I would not recommend it anyway:

```<code>import setuptools

setuptools.setup(
    packages=['some_name', 'some_name.module_1'],
    package_dir={'some_name': '../project_name'},
    # ...
)
</code>```

References:

https://docs.python.org/3/distutils/setupscript.html?highlight=package_dir#listing-whole-packages

Body:
I have a project with a structure similar to this:

project_name
  |_ module_1
    |_ submodule1
    |_ file1.py
  |_ module_2
  |_ filea.py
  |_ fileb.py
  |_ setup.py

If I create a bdist_wheel from it, when installing I will get the files and module folder directly under site-packages.

I can add another level to the tree, like so:

project_name
  some_name
    |_ module_1
      |_ submodule1
      |_ file1.py
    |_ module_2
    |_ filea.py
    |_ fileb.py
    |_ setup.py

and then I get everything installed under some_name in site-packages.

Question is, can I achieve the same by somehow setting top_level or by other means that doesn't require adding another folder to the hierarchy (code is like in former in GIT)?

Body:
Maybe something like the following could work, but I am not sure (haven't tested it), it might also be required to exclude setup.py somehow, I would not recommend it anyway:

import setuptools

setuptools.setup(
    packages=['some_name', 'some_name.module_1'],
    package_dir={'some_name': '../project_name'},
    # ...
)

References:

https://docs.python.org/3/distutils/setupscript.html?highlight=package_dir#listing-whole-packages


问:
K8S Nginx Ingress issue - invalid condition
I have trouble about nginx ingress using condition

Install Nginx Ingress via helm instal (tested in both nginx-ingress-1.16 and nginx-ingress-1.36

I am try to follow
ingress nginx redirect from www to https
Setup some condition

like

```<code>    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ( $host = "mydomain.co" ) {
        rewrite ^ https://www.mydomain.co$uri permanent;
      }
</code>```

When apply the ingress rule, nginx ingress start reload in fail status

```<code>-------------------------------------------------------------------------------
W0602 07:35:36.244415       6 queue.go:130] requeuing vincent/demoheader-ingress, err
-------------------------------------------------------------------------------
Error: exit status 1
2020/06/02 07:35:36 [notice] 982#982: ModSecurity-nginx v1.0.0
2020/06/02 07:35:36 [emerg] 982#982: invalid condition "~" in /tmp/nginx-cfg971999838:530
nginx: [emerg] invalid condition "~" in /tmp/nginx-cfg971999838:530
nginx: configuration file /tmp/nginx-cfg971999838 test failed

</code>```

My Full ingress rule

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: demoheader-ingress
  namespace: namespace
  annotations:
    kubernetes.io/ingress.class: nginx-temp
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
    nginx.ingress.kubernetes.io/configuration-snippet: |
        if ( $uri ~* ^/xx/(.*) ) {
          rewrite ^ https://www.xxx.co permanent;
        }
spec:
  rules:
  - host: mydomain
    http:
      paths:
      - backend:
          serviceName: header-headerv1
          servicePort: 80
        path: /
EOF
</code>```

Any idea ?

答:
OK i know what happen in here

I encount a wired issue for k8s apply stuff ….
While official document  told you , you can apply object by this method

```<code>cat <<EOF | kubectl apply -f -
xxx
yyy
eee
EOF
</code>```

https://kubernetes.io/docs/reference/kubectl/cheatsheet/

However for ingress rule , if you under a specific condition such like this

```<code>    nginx.ingress.kubernetes.io/configuration-snippet: |
        if ( $host = ^mydomain ) {
          rewrite ^ https://www.mydomain$uri permanent;
        }
</code>```

you are unable to make the nginx working again (never config reload success, it will affect the following config change)

Until you delete the ingress rule and re-apply by
kubectl apply -f the-ingress-file

Body:
I have trouble about nginx ingress using condition

Install Nginx Ingress via helm instal (tested in both nginx-ingress-1.16 and nginx-ingress-1.36

I am try to follow
ingress nginx redirect from www to https
Setup some condition

like

    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ( $host = "mydomain.co" ) {
        rewrite ^ https://www.mydomain.co$uri permanent;
      }

When apply the ingress rule, nginx ingress start reload in fail status

-------------------------------------------------------------------------------
W0602 07:35:36.244415       6 queue.go:130] requeuing vincent/demoheader-ingress, err
-------------------------------------------------------------------------------
Error: exit status 1
2020/06/02 07:35:36 [notice] 982#982: ModSecurity-nginx v1.0.0
2020/06/02 07:35:36 [emerg] 982#982: invalid condition "~" in /tmp/nginx-cfg971999838:530
nginx: [emerg] invalid condition "~" in /tmp/nginx-cfg971999838:530
nginx: configuration file /tmp/nginx-cfg971999838 test failed

My Full ingress rule

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: demoheader-ingress
  namespace: namespace
  annotations:
    kubernetes.io/ingress.class: nginx-temp
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
    nginx.ingress.kubernetes.io/configuration-snippet: |
        if ( $uri ~* ^/xx/(.*) ) {
          rewrite ^ https://www.xxx.co permanent;
        }
spec:
  rules:
  - host: mydomain
    http:
      paths:
      - backend:
          serviceName: header-headerv1
          servicePort: 80
        path: /
EOF

Any idea ?

Body:
OK i know what happen in here

I encount a wired issue for k8s apply stuff ….
While official document  told you , you can apply object by this method

cat <<EOF | kubectl apply -f -
xxx
yyy
eee
EOF

https://kubernetes.io/docs/reference/kubectl/cheatsheet/

However for ingress rule , if you under a specific condition such like this

    nginx.ingress.kubernetes.io/configuration-snippet: |
        if ( $host = ^mydomain ) {
          rewrite ^ https://www.mydomain$uri permanent;
        }

you are unable to make the nginx working again (never config reload success, it will affect the following config change)

Until you delete the ingress rule and re-apply by
kubectl apply -f the-ingress-file


问:
R: Import values from one dataframe to another by matching dates
Assume I have df1:

```<code>Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5
</code>```

& df2:

```<code>DateTime      Gain   People
2003-01-01    3      3
2003-05-09    5      4
2004-12-31    1      2
2005-01-31    -2     2
2005-08-13    9      7
2006-09-10    6      8
2007-10-03    7      5
</code>```

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. If dates do not fall into any of periods in df1, return Value 0. A view of desired outcome:

```<code>DateTime      Gain   People   Value
2003-01-01    3      3        3
2003-05-09    5      4        3
2004-12-31    1      2        4
2005-01-31    -2     2        5
2005-08-13    9      7        5
2006-09-10    6      8        0
2007-10-03    7      5        0
</code>```

Please advise

答:
For some reason my previous answer was deleted by a moderator which means I can't undelete it - anyway answer reproduced below with a solution taken from one of the links.

You might want to do this with a left range join

Merge 2 dataframes if value within range

Join tables by date range

matching time a time in the interval between a start and end time

These three SO posts should give you a good starting place

EDIT: I think using sqldf is the easiest (clearest syntax anyway) from the 3 links above.

```<code>library(sqldf)
library(lubridate)
df1 <- data.frame(Start_Date=c(ymd("2001-01-01"),
                               ymd("2002-01-01"),
                               ymd("2003-01-01"),
                               ymd("2004-01-01"),
                                ymd("2005-01-01")),
                    End_Date=c(ymd("2001-12-31"),
                               ymd("2002-12-31"),
                               ymd("2003-12-31"),
                               ymd("2004-12-31"),
                               ymd("2005-12-31")),
                    Value=c(1,2,3,4,5))

df2 <- data.frame(DateTime=c(ymd("2003-01-01"),
                             ymd("2003-05-09"),
                             ymd("2004-12-31"),
                             ymd("2005-01-31"),
                             ymd("2005-08-13"),
                             ymd("2006-09-10"),
                             ymd("2007-10-03")),
                  Gain=c(3,5,1,-2,9,6,7),
                  People=c(3,4,2,2,7,8,5))

sqldf("SELECT DateTime,Gain,People,COALESCE(Value,0) AS Value FROM df2
            LEFT JOIN df1
            ON df2.DateTime BETWEEN df1.Start_Date AND df1.End_Date")
</code>```

Coalesce changes NA (non matching) values to 0. The rest is pretty self explanatory.

Body:
Assume I have df1:

Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5

& df2:

DateTime      Gain   People
2003-01-01    3      3
2003-05-09    5      4
2004-12-31    1      2
2005-01-31    -2     2
2005-08-13    9      7
2006-09-10    6      8
2007-10-03    7      5

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. If dates do not fall into any of periods in df1, return Value 0. A view of desired outcome:

DateTime      Gain   People   Value
2003-01-01    3      3        3
2003-05-09    5      4        3
2004-12-31    1      2        4
2005-01-31    -2     2        5
2005-08-13    9      7        5
2006-09-10    6      8        0
2007-10-03    7      5        0

Please advise

Body:
For some reason my previous answer was deleted by a moderator which means I can't undelete it - anyway answer reproduced below with a solution taken from one of the links.

You might want to do this with a left range join

Merge 2 dataframes if value within range

Join tables by date range

matching time a time in the interval between a start and end time

These three SO posts should give you a good starting place

EDIT: I think using sqldf is the easiest (clearest syntax anyway) from the 3 links above.

library(sqldf)
library(lubridate)
df1 <- data.frame(Start_Date=c(ymd("2001-01-01"),
                               ymd("2002-01-01"),
                               ymd("2003-01-01"),
                               ymd("2004-01-01"),
                                ymd("2005-01-01")),
                    End_Date=c(ymd("2001-12-31"),
                               ymd("2002-12-31"),
                               ymd("2003-12-31"),
                               ymd("2004-12-31"),
                               ymd("2005-12-31")),
                    Value=c(1,2,3,4,5))

df2 <- data.frame(DateTime=c(ymd("2003-01-01"),
                             ymd("2003-05-09"),
                             ymd("2004-12-31"),
                             ymd("2005-01-31"),
                             ymd("2005-08-13"),
                             ymd("2006-09-10"),
                             ymd("2007-10-03")),
                  Gain=c(3,5,1,-2,9,6,7),
                  People=c(3,4,2,2,7,8,5))

sqldf("SELECT DateTime,Gain,People,COALESCE(Value,0) AS Value FROM df2
            LEFT JOIN df1
            ON df2.DateTime BETWEEN df1.Start_Date AND df1.End_Date")

Coalesce changes NA (non matching) values to 0. The rest is pretty self explanatory.


问:
Using body in GET requests
Why are url query strings is superior to the values in the body?

There are some obvious differences between the two ways to request data - like being able to see the parameters in the url, or the fact that the requests can be saved in the brower's history.

But is there anything more to it?
Is it bad to request data with body?

答:
There's nothing wrong with using a body. GET method does not have a body not because of some prejudice against the usage of body.

If you have a look at the HTTP protocol specification, you might have some insight:

"The GET method means retrieve whatever information (in the form of an
entity) is identified by the Request-URI."

In simpler words, GET method is created to retrieve some resource using only URI. In even simpler words - if you can get some resource using only URI - GET is a method you should use.

As a matter of fact, you can send body with GET request, but it will be just ignored (more information here: HTTP GET with request body)

If you need to pass a body for whatever reason you will need to use a different method. POST is a prominent example:

"The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line."

If you are working on REST API's I would highly encourage to read HTTP specification https://www.rfc-editor.org/rfc/rfc2616

Title: Using body in GET requests


问:
can't register, it keep saying bad Request
I am using passport, node and express in my project. I keep getting this error when i try to register: Bad Request

I am not sure what the problem is. If I delete the authentication, it works perfectly but when I add it, it gives me the same error so I think there's a problem that I can't find. Thank you. I really appreciate it!!!

```<code>  const express = require('express');
    const bodyParser =require("body-parser");
    const passport=require("passport");
    const mongoose= require("mongoose");
    const passportLocalMongoose = require('passport-local-mongoose');
    const session = require("session");
    const expressSession =require("express-session");
    const app = express();
    const LocalStrategy = require('passport-local').Strategy
    const Schema= mongoose.Schema;

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static("public"));
    app.set('view engine', 'ejs');

    mongoose.connect('mongodb://localhost:27017/userDB2', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true});

    const userSchema= new mongoose.Schema({
        email:String,
        password:String
    })
    userSchema.plugin(passportLocalMongoose)

    const User= mongoose.model("User",userSchema);

    passport.use(User.createStrategy());

    passport.serializeUser(User.serializeUser());
    passport.deserializeUser(User.deserializeUser())

    app.get('/', (req, res) => {
        res.render('index');
    });
    app.get('/login', (req, res) => {
        res.render('login');
    });

    app.get("/register",(req,res)=>
    {
        res.render("register");
    })
    app.get('/message', (req, res) => {

        if(req.isAuthenticated())
        {
            res.redirect("/message")
        }
        else
        {
            res.redirect("/register")
        }

    });

    app.post("/register",(req,res)=>
    {
        const email= req.body.email;
        const password= req.body.password;
        User.register({username:email}, password, function(err, user) {
      if (err) {
          console.log("err")
          res.redirect("/register")
      }
      else
      {
          passport.authenticate("local")(req,res, function()
          {

          res.redirect("/message")

          })

      }
        })
    })

    app.listen('4000', (req, res) => {
        console.log('working and refreshin...')
    });
</code>```

答:
I think you are messing this important lines for passport to work
sessions </p>

```<code>app.use(session({secret: 'secret'}))
app.use(passport.initialize());
app.use(passport.session());
</code>```

Body:
I am using passport, node and express in my project. I keep getting this error when i try to register: Bad Request

I am not sure what the problem is. If I delete the authentication, it works perfectly but when I add it, it gives me the same error so I think there's a problem that I can't find. Thank you. I really appreciate it!!!

  const express = require('express');
    const bodyParser =require("body-parser");
    const passport=require("passport");
    const mongoose= require("mongoose");
    const passportLocalMongoose = require('passport-local-mongoose');
    const session = require("session");
    const expressSession =require("express-session");
    const app = express();
    const LocalStrategy = require('passport-local').Strategy
    const Schema= mongoose.Schema;

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static("public"));
    app.set('view engine', 'ejs');

    mongoose.connect('mongodb://localhost:27017/userDB2', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true});

    const userSchema= new mongoose.Schema({
        email:String,
        password:String
    })
    userSchema.plugin(passportLocalMongoose)

    const User= mongoose.model("User",userSchema);

    passport.use(User.createStrategy());

    passport.serializeUser(User.serializeUser());
    passport.deserializeUser(User.deserializeUser())

    app.get('/', (req, res) => {
        res.render('index');
    });
    app.get('/login', (req, res) => {
        res.render('login');
    });

    app.get("/register",(req,res)=>
    {
        res.render("register");
    })
    app.get('/message', (req, res) => {

        if(req.isAuthenticated())
        {
            res.redirect("/message")
        }
        else
        {
            res.redirect("/register")
        }

    });

    app.post("/register",(req,res)=>
    {
        const email= req.body.email;
        const password= req.body.password;
        User.register({username:email}, password, function(err, user) {
      if (err) {
          console.log("err")
          res.redirect("/register")
      }
      else
      {
          passport.authenticate("local")(req,res, function()
          {

          res.redirect("/message")

          })

      }
        })
    })

    app.listen('4000', (req, res) => {
        console.log('working and refreshin...')
    });

Body:
I think you are messing this important lines for passport to work
sessions

app.use(session({secret: 'secret'}))
app.use(passport.initialize());
app.use(passport.session());


问:
Numpy compute dot product of the inner array of a 3D matrix
I have two arrays that look as follows:

In code that is:

```<code>t = np.random.rand(6, 6, 2)
</code>```

I now want to compute the dot product of the axis 2 arrays (the ones of shape 2), for each of the entries of the axis 0 and 1 arrays.

I can do it with a for loop:

```<code>Q = np.zeros_like(t)
for i in range(6):
    for j in range(6):
        Q[i,j] = t[i,j].dot(t[i,j])
</code>```

How can I do this with numpy functions?

I could not get it to work with .dot, .tensordot or similar methods...

t.dot(t) produces this error ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1) which is to be expected, however I would like to circumvent it.

答:
I got it working with np.einsum:

```<code>np.einsum("...i, ...i", t, t)
</code>```

which produces the same output as my for loop.

Body:
I have two arrays that look as follows:

In code that is:

t = np.random.rand(6, 6, 2)

I now want to compute the dot product of the axis 2 arrays (the ones of shape 2), for each of the entries of the axis 0 and 1 arrays.

I can do it with a for loop:

Q = np.zeros_like(t)
for i in range(6):
    for j in range(6):
        Q[i,j] = t[i,j].dot(t[i,j])

How can I do this with numpy functions?

I could not get it to work with .dot, .tensordot or similar methods...

t.dot(t) produces this error ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1) which is to be expected, however I would like to circumvent it.

Body:
I got it working with np.einsum:

np.einsum("...i, ...i", t, t)

which produces the same output as my for loop.


问:
Mounting host directory to container
I am launching a container for my application. But my app needs few config files to login. Files are stored in host directory. How can I mount the host filepath to container?

host directory : /opt/myApp/config

Docker command used currently :

sudo docker run container -d --name myApp-container -p 8090:8080 myApp-image
```

Please suggest the changes in docker command to achieve this.

答:
You need to use -v/--volume key in such way:

```<code>-v <host dir>:<container dir>:ro
</code>```

In your case it will be:

```<code>-v /opt/myApp/config:/opt/myApp/config:ro
</code>```

You can use this key multiple times. You can also drop :ro part if you want directory to be writable.

See Docker documentation on volumes.

Title: Mounting host directory to container

Body:
I am launching a container for my application. But my app needs few config files to login. Files are stored in host directory. How can I mount the host filepath to container?

host directory : /opt/myApp/config

Docker command used currently :

sudo docker run container -d --name myApp-container -p 8090:8080 myApp-image

Please suggest the changes in docker command to achieve this.

Body:
You need to use -v/--volume key in such way:

-v <host dir>:<container dir>:ro

In your case it will be:

-v /opt/myApp/config:/opt/myApp/config:ro

You can use this key multiple times. You can also drop :ro part if you want directory to be writable.

See Docker documentation on volumes.


问:
How do I predict using my type <torchvision.models> upon my set of images? Python / Torchvision / PyTorch
I've trained my images upon my training and validation set, but now I wish to apply my model to my testing set (which I also have the classifications stored). The only way I've seen of even processing the testing set is via the exact same mechanisms of the validation set, but this makes it an extension of the validation set rather than the testing set? There is no prediction.</p>

```<code>model_ft, hist = train_model(model_ft, dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs)
</code>```

答:
Try something like below</p>

```<code>def predict(model, dataloader):
  # Set model to evaluate mode
  model.eval()
  predictions = []

  with torch.no_grad()
    # Iterate over data.
    for inputs, _ in dataloader:
      outputs = model(inputs)
      _, preds = torch.max(outputs, 1)
      predictions.extend(preds.numpy())

  return predictions

print (predict(model_ft, your_test_dataloader))
</code>```

Body:
I've trained my images upon my training and validation set, but now I wish to apply my model to my testing set (which I also have the classifications stored). The only way I've seen of even processing the testing set is via the exact same mechanisms of the validation set, but this makes it an extension of the validation set rather than the testing set? There is no prediction.

model_ft, hist = train_model(model_ft, dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs)

Body:
Try something like below

def predict(model, dataloader):
  # Set model to evaluate mode
  model.eval()
  predictions = []

  with torch.no_grad()
    # Iterate over data.
    for inputs, _ in dataloader:
      outputs = model(inputs)
      _, preds = torch.max(outputs, 1)
      predictions.extend(preds.numpy())

  return predictions

print (predict(model_ft, your_test_dataloader))


问:
Lots of first chance Microsoft.CSharp.RuntimeBinderExceptions thrown when dealing with dynamics
I've got a standard 'dynamic dictionary' type class in C# -

```<code>class Bucket : DynamicObject
{
    readonly Dictionary<string, object> m_dict = new Dictionary<string, object>();

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        m_dict[binder.Name] = value;
        return true;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return m_dict.TryGetValue(binder.Name, out result);
    }
}
</code>```

Now I call it, as follows:

```<code>static void Main(string[] args)
{
    dynamic d = new Bucket();
    d.Name = "Orion"; // 2 RuntimeBinderExceptions
    Console.WriteLine(d.Name); // 2 RuntimeBinderExceptions
}
</code>```

The app does what you'd expect it to, but the debug output looks like this:

```
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
'ScratchConsoleApplication.vshost.exe' (Managed (v4.0.30319)): Loaded 'Anonymously Hosted DynamicMethods Assembly'
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
```

Any attempt to access a dynamic member seems to output a RuntimeBinderException to the debug logs. While I'm aware that first-chance exceptions are not a problem in and of themselves, this does cause some problems for me:

I often have the debugger set to "break on exceptions", as I'm writing WPF apps, and otherwise all exceptions end up getting converted to a DispatcherUnhandledException, and all the actual information you want is lost. WPF sucks like that.

As soon as I hit any code that's using dynamic, the debug output log becomes fairly useless. All the useful trace lines that I care about get hidden amongst all the useless RuntimeBinderExceptions

Is there any way I can turn this off, or is the RuntimeBinder unfortunately just built like that?

Thanks, Orion

答:
This was bothering me, too.  I added the exception to the exceptions list so that I could deselect it.  Just follow these steps:

From the Debug menu, select Exceptions.

Click the "Add..." button on the bottom right.

Choose "Common Language Runtime Exceptions" from the Type dropdown.

Type "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" as the name.

Click OK.

The exception type will now appear on the list.  Just deselect it.

I wish this setting could be saved across solutions, but I don't think it can, so you'll have to reapply this setting on every solution.

ContentLicense: CC BY-SA 2.5

Body:
I've got a standard 'dynamic dictionary' type class in C# -

class Bucket : DynamicObject
{
    readonly Dictionary<string, object> m_dict = new Dictionary<string, object>();

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        m_dict[binder.Name] = value;
        return true;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return m_dict.TryGetValue(binder.Name, out result);
    }
}

Now I call it, as follows:

static void Main(string[] args)
{
    dynamic d = new Bucket();
    d.Name = "Orion"; // 2 RuntimeBinderExceptions
    Console.WriteLine(d.Name); // 2 RuntimeBinderExceptions
}

The app does what you'd expect it to, but the debug output looks like this:

A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
'ScratchConsoleApplication.vshost.exe' (Managed (v4.0.30319)): Loaded 'Anonymously Hosted DynamicMethods Assembly'
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll

Any attempt to access a dynamic member seems to output a RuntimeBinderException to the debug logs. While I'm aware that first-chance exceptions are not a problem in and of themselves, this does cause some problems for me:

I often have the debugger set to "break on exceptions", as I'm writing WPF apps, and otherwise all exceptions end up getting converted to a DispatcherUnhandledException, and all the actual information you want is lost. WPF sucks like that.

As soon as I hit any code that's using dynamic, the debug output log becomes fairly useless. All the useful trace lines that I care about get hidden amongst all the useless RuntimeBinderExceptions

Is there any way I can turn this off, or is the RuntimeBinder unfortunately just built like that?

Thanks, Orion


问:
Chrome form reset don't change display select element
When I reset the form the select element value reset but still display the old value

I'm using this to reset the form

```<code>$('#testForm')[0].reset();
</code>```

In this example the 'Two' option is selected by default.
If I change the selection and press 'reset form' the select value change back but still shows the old value

in Edge its working

https://jsfiddle.net/z6vk91sL/

Google Chrome   83.0.4103.61 (Official Build) (64-bit) (cohort: Stable)

$('#testFormReset').on("click", () => {
  $('#testForm')[0].reset();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}</code>```

<form id='testForm'>
  <select>
    <option value='1'>One</option>
    <option selected value='2'>Two</option>
    <option value='3'>Three</option>
  </select>

  <button id='testFormReset' type='reset'>
    reset form
  </button>
</form>```

答:
Looks like you are having this issue in the Google Chrome and MS Edge browser as both browsers use the same browser engine.

As the issue is already reported and fixed on the Chromium site.

Here I am sharing you the workaround that you can use temporarily.

<!doctype html>

<form id="testForm">
  <select id="my_select">
    <option value='1'>One</option>
    <option value='2' selected>Two</option>
    <option value='3'>Three</option>
  </select>

  <button id='testFormReset'>
    reset form
  </button>
</form>

```

Output in the MS Edge(on the left side) and Google Chrome browser:

Body:
When I reset the form the select element value reset but still display the old value

I'm using this to reset the form

$('#testForm')[0].reset();

In this example the 'Two' option is selected by default.
If I change the selection and press 'reset form' the select value change back but still shows the old value

in Edge its working

https://jsfiddle.net/z6vk91sL/

Google Chrome   83.0.4103.61 (Official Build) (64-bit) (cohort: Stable)

$('#testFormReset').on("click", () => {
  $('#testForm')[0].reset();
})

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

<form id='testForm'>
  <select>
    <option value='1'>One</option>
    <option selected value='2'>Two</option>
    <option value='3'>Three</option>
  </select>

  <button id='testFormReset' type='reset'>
    reset form
  </button>
</form>

Body:
Looks like you are having this issue in the Google Chrome and MS Edge browser as both browsers use the same browser engine.

As the issue is already reported and fixed on the Chromium site.

Here I am sharing you the workaround that you can use temporarily.

<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>
<form id="testForm">
  <select id="my_select">
    <option value='1'>One</option>
    <option value='2' selected>Two</option>
    <option value='3'>Three</option>
  </select>

  <button id='testFormReset'>
    reset form
  </button>
</form>
<script>
$('#testFormReset').on("click", () => {
    $('#my_select option').prop('selected', function() {
        return this.defaultSelected;
    });

    $('#testForm')[0].reset();

})
</script>
</body>
</html>

Output in the MS Edge(on the left side) and Google Chrome browser:


问:
Presto - get sum of array elements
I'm using Athena and trying to get a sum of array elements which are double but the reduce function seems to only work on integers:

SELECT reduce(ARRAY [5.0, 20.0, 50.4], 0, (s, x) -> s + x, s -> s);

Will throw an error:

Unexpected parameters (array(double), integer, com.facebook.presto.sql.analyzer.TypeSignatureProvider@762f0fa7, com.facebook.presto.sql.analyzer.TypeSignatureProvider@29dfe267) for function reduce. Expected: reduce(array(T), S, function(S,T,S), function(S,R)) T, S, R

Is there a way to do it?

答:
Doesn't look clean but I have found a way to make it work:</p>

```<code>SELECT reduce(ARRAY [5.0, 20.0, 50.4],
              CAST(ROW(0.0, 0) AS ROW(sum DOUBLE, count INTEGER)),
              (s, x) -> CAST(ROW(x + s.sum, s.count + 1) AS ROW(sum DOUBLE, count INTEGER)),
              s -> IF(s.count = 0, NULL, s.sum));
</code>```

Title: Presto - get sum of array elements

Body:
Doesn't look clean but I have found a way to make it work:

SELECT reduce(ARRAY [5.0, 20.0, 50.4],
              CAST(ROW(0.0, 0) AS ROW(sum DOUBLE, count INTEGER)),
              (s, x) -> CAST(ROW(x + s.sum, s.count + 1) AS ROW(sum DOUBLE, count INTEGER)),
              s -> IF(s.count = 0, NULL, s.sum));


问:
Crazy PHP fopen / fwrite / file_put_contents / move_uploaded_file bug with binary mode writing on CentOS Linux Adding 0x0D to every 0x0A
Seems the file keeps adding 0x0D to my saved binary files no matter what setting I put in the fopen mode flag.

It's not only affecting fopen/fwrite.. but also file_put_contents.

file_get_contents I thought was the problem to begin with.. but it turns out this one is actually working okay.. because when I dumped the file using bin2hex() it came out good.

I was blaming at first the std::string in C++ for this bug.. but it turns out it doesn't even have anything to do with C++ but it's in fact a bug with PHP or maybe with only CentOS linux and I have yet to find a solution to store my file in binary.. best I could do is hexstring dump file which works..

Look at my code and screenshots.

```<code>$target_file = "/privatefiles/" . basename($_FILES["a"]["name"]);
$fileTypeExtension = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

//Check file extension.
if($fileTypeExtension != "dll" && $fileTypeExtension != "exe" ) die("ER");

// Check file size
if ($_FILES["a"]["size"] > 10*(1024*1024)) //10 MB cap
  die("ER");

//To decode a base64 encoded file (this was a quickfix to fix binary file encoding in C++ part).
$fileContent = file_get_contents($_FILES['a']['tmp_name']);
$fileContent = base64_decode($fileContent);

//fail
$fh = fopen("wtf1.bin", "wb");
fwrite($fh, $fileContent, strlen($fileContent));
fclose($fh);

//fail (exact result as top)
$fh = fopen("wtf2.bin", "wb");
$fileContent = bin2hex($fileContent);
for($i=0;$i<strlen($fileContent);$i+=2)
    fwrite($fh, chr(hexdec(substr($fileContent,$i,2))));
fclose($fh);

//good result.. but not binary
$fh = fopen("wtf3.bin", "w");
$fileContent = bin2hex(base64_decode(file_get_contents($_FILES['a']['tmp_name'])));
fwrite($fh, $fileContent);
fclose($fh);

//good result but not binary
file_put_contents($target_file, $fileContent); //good bin2hex.

//fail same as the top 2 fail's.
file_put_contents($target_file."_", file_get_contents($_FILES['a']['tmp_name'])); //bad same as wtf1.bin or wtf2.bin
</code>```

Here are my screenshots (proof of what is happening from running the code above), and initiating a file upload using C++ application (which cannot be bugged because at first I sent using raw binary mode.. then after this 0x0D 0x0A bug I changed it to base64 encoding to fix the transfer problem.. and it turns out that wasn't even the problem, but in fact a PHP problem I believe..

Here is the original binary file (not altered) this is what I upload (as you can see I stop at 0x0A 0x40 to show you the bug).

Here is wtf1.bin (Just a simple 1 liner of base64_decode to file) at same offset.

Here is wtf2.bin (Some hackery I tried to do to fix this problem using bin2hex which dumps it good) at same offset.

Here is wtf3.bin (bin2hex) which works good at same offset. (0x846 / 2 = 0x423) (same offset confirmed!)

Even this simple upload script, uploads corrupted files with 0xA,0xD

```<code><!DOCTYPE html>
<html>
<head>
  <title>Upload your files</title>
</head>
<body>
  <form enctype="multipart/form-data" action="test.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="submit" value="Upload"></input>
  </form>
</body>
</html>
<?php
  if(!empty($_FILES['uploaded_file']))
  {
    $path = basename( $_FILES['uploaded_file']['name']);
    print_r($_FILES);
    $size = filesize($_FILES['uploaded_file']['tmp_name']);
    echo "<br>size uploaded = " . $size . "<br>";
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
      echo "The file ".  basename( $_FILES['uploaded_file']['name']).
      " has been uploaded<br>";
      echo "path = " . $path . "<br>";
      echo "size stored = " . filesize($path);
    } else{
        echo "There was an error uploading the file, please try again!";
    }
  }
?>
</code>```

Bug happens when I just upload these bytes in binary format

BC 09 00 00 83 C4 04 BA E8 57 40 00 8D 64 24 00 8A 08 88 0A 40 42 84 C9

I get back on server

BC 09 00 00 83 C4 04 BA E8 57 40 00 8D 64 24 00 8A 08 88 0D 0A 40 42 84 C9

答: Thanks CBroe and IVO GELOV, The issue was in my FTP/SFTP Client WinSCP. I attached a screenshot which setting you need to turn off so this problem doesn't happen.

Body:
Seems the file keeps adding 0x0D to my saved binary files no matter what setting I put in the fopen mode flag.

It's not only affecting fopen/fwrite.. but also file_put_contents.

file_get_contents I thought was the problem to begin with.. but it turns out this one is actually working okay.. because when I dumped the file using bin2hex() it came out good.

I was blaming at first the std::string in C++ for this bug.. but it turns out it doesn't even have anything to do with C++ but it's in fact a bug with PHP or maybe with only CentOS linux and I have yet to find a solution to store my file in binary.. best I could do is hexstring dump file which works..

Look at my code and screenshots.

$target_file = "/privatefiles/" . basename($_FILES["a"]["name"]);
$fileTypeExtension = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

//Check file extension.
if($fileTypeExtension != "dll" && $fileTypeExtension != "exe" ) die("ER");

// Check file size
if ($_FILES["a"]["size"] > 10*(1024*1024)) //10 MB cap
  die("ER");

//To decode a base64 encoded file (this was a quickfix to fix binary file encoding in C++ part).
$fileContent = file_get_contents($_FILES['a']['tmp_name']);
$fileContent = base64_decode($fileContent);

//fail
$fh = fopen("wtf1.bin", "wb");
fwrite($fh, $fileContent, strlen($fileContent));
fclose($fh);

//fail (exact result as top)
$fh = fopen("wtf2.bin", "wb");
$fileContent = bin2hex($fileContent);
for($i=0;$i<strlen($fileContent);$i+=2)
    fwrite($fh, chr(hexdec(substr($fileContent,$i,2))));
fclose($fh);

//good result.. but not binary
$fh = fopen("wtf3.bin", "w");
$fileContent = bin2hex(base64_decode(file_get_contents($_FILES['a']['tmp_name'])));
fwrite($fh, $fileContent);
fclose($fh);

//good result but not binary
file_put_contents($target_file, $fileContent); //good bin2hex.

//fail same as the top 2 fail's.
file_put_contents($target_file."_", file_get_contents($_FILES['a']['tmp_name'])); //bad same as wtf1.bin or wtf2.bin

Here are my screenshots (proof of what is happening from running the code above), and initiating a file upload using C++ application (which cannot be bugged because at first I sent using raw binary mode.. then after this 0x0D 0x0A bug I changed it to base64 encoding to fix the transfer problem.. and it turns out that wasn't even the problem, but in fact a PHP problem I believe..

Here is the original binary file (not altered) this is what I upload (as you can see I stop at 0x0A 0x40 to show you the bug).

Here is wtf1.bin (Just a simple 1 liner of base64_decode to file) at same offset.

Here is wtf2.bin (Some hackery I tried to do to fix this problem using bin2hex which dumps it good) at same offset.

Here is wtf3.bin (bin2hex) which works good at same offset. (0x846 / 2 = 0x423) (same offset confirmed!)

Even this simple upload script, uploads corrupted files with 0xA,0xD

<!DOCTYPE html>

  <title>Upload your files</title>

  <form enctype="multipart/form-data" action="test.php" method="POST">

Upload your file

    <input type="file" name="uploaded_file"></input>

    <input type="submit" value="Upload"></input>
  </form>

<?php
  if(!empty($_FILES['uploaded_file']))
  {
    $path = basename( $_FILES['uploaded_file']['name']);
    print_r($_FILES);
    $size = filesize($_FILES['uploaded_file']['tmp_name']);
    echo "
size uploaded = " . $size . "
";
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
      echo "The file ".  basename( $_FILES['uploaded_file']['name']).
      " has been uploaded
";
      echo "path = " . $path . "
";
      echo "size stored = " . filesize($path);
    } else{
        echo "There was an error uploading the file, please try again!";
    }
  }
?>

Bug happens when I just upload these bytes in binary format

BC 09 00 00 83 C4 04 BA E8 57 40 00 8D 64 24 00 8A 08 88 0A 40 42 84 C9

I get back on server

BC 09 00 00 83 C4 04 BA E8 57 40 00 8D 64 24 00 8A 08 88 0D 0A 40 42 84 C9


问:
From string, extract a word starting with a keyword (SQL or any other methods?)
Let's say I have a string of random characters, and I want to extract only the string that starts after a specific keyword (including the keyword). How could I do so using MySQL or MariaDB? ..............

String example:

axdsSSFddlwie ====> SSFddlwie

aldfklafnlanaSSFiiie ====> SSFiiie

iiiSSFnnnn ====> SSFnnnn

Thanks for the help!

答:
Using the base string functions we can try:

```<code>SELECT SUBSTRING(col, INSTR('SSF', col))
FROM yourTable;
</code>```

If you are using MySQL 8+, then REGEXP_SUBSTR is another option:

```<code>SELECT REGEXP_SUBSTR(col, 'SSF.*')
FROM yourTable;
</code>```

Body:
Using the base string functions we can try:

SELECT SUBSTRING(col, INSTR('SSF', col))
FROM yourTable;

If you are using MySQL 8+, then REGEXP_SUBSTR is another option:

SELECT REGEXP_SUBSTR(col, 'SSF.*')
FROM yourTable;


问:
Cannot make a simple SQL request with java driver but work fine in a mysql console
so I wanted to do a simple SQL query to my MariaDB server to remove the database (I know it's probably not the best way to do it). This is the piece of code to do that:

```<code>public static void cleanDatabase() {
    try {
      Connection con = DriverManager.getConnection("myurl", "username", "password"); // replaced by real values
      Statement stmt = con.createStatement();
      stmt.executeUpdate("DROP DATABASE statuer_test; CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8;");
      con.close();
    } catch (Exception e)  {
      e.printStackTrace();
      System.err.println("cleanDatabse(): error");
    }
  }
</code>```

This is what I get when I call the cleanDatabase() method :

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8' at line 1
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
(more lines...)
</code>```

However this is totally working when I use a mysql cli client:

```<code>MariaDB [(none)]> CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8;
Query OK, 0 rows affected, 1 warning (0.000 sec)
</code>```

So what I'm missing here ?

答:
Seem to work with that code, so resolved:</p>

```<code>stmt.executeUpdate("DROP DATABASE statuer_test");
stmt.executeUpdate("CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8");
</code>```

Body:
so I wanted to do a simple SQL query to my MariaDB server to remove the database (I know it's probably not the best way to do it). This is the piece of code to do that:

public static void cleanDatabase() {
    try {
      Connection con = DriverManager.getConnection("myurl", "username", "password"); // replaced by real values
      Statement stmt = con.createStatement();
      stmt.executeUpdate("DROP DATABASE statuer_test; CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8;");
      con.close();
    } catch (Exception e)  {
      e.printStackTrace();
      System.err.println("cleanDatabse(): error");
    }
  }

This is what I get when I call the cleanDatabase() method :

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8' at line 1
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
(more lines...)

However this is totally working when I use a mysql cli client:

MariaDB [(none)]> CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8;
Query OK, 0 rows affected, 1 warning (0.000 sec)

So what I'm missing here ?

Body:
Seem to work with that code, so resolved:

stmt.executeUpdate("DROP DATABASE statuer_test");
stmt.executeUpdate("CREATE SCHEMA IF NOT EXISTS statuer_test DEFAULT CHARACTER SET utf8");