问:
How to get all enum values as an array
I have the following enum.

```<code>enum EstimateItemStatus: Printable {
    case Pending
    case OnHold
    case Done

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}
</code>```

I need to get all the raw values as an array of strings (like so ["Pending", "On Hold", "Done"]).

I added this method to the enum.

```<code>func toArray() -> [String] {
    var n = 1
    return Array(
        GeneratorOf<EstimateItemStatus> {
            return EstimateItemStatus(id: n++)!.description
        }
    )
}
</code>```

But I'm getting the following error.

Cannot find an initializer for type 'GeneratorOf' that accepts an argument list of type '(() -> _)'

Is there is an easier, better or more elegant way to do this?

答:
Extension on an enum to create allValues.     </p>

```<code>extension RawRepresentable where Self: CaseIterable {
      static var allValues: [Self.RawValue] {
        return self.allCases.map { $0.rawValue}
      }
    }
</code>```

Title: How to get all enum values as an array

Body:
I have the following enum.

enum EstimateItemStatus: Printable {
    case Pending
    case OnHold
    case Done

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}

I need to get all the raw values as an array of strings (like so ["Pending", "On Hold", "Done"]).

I added this method to the enum.

func toArray() -> [String] {
    var n = 1
    return Array(
        GeneratorOf<EstimateItemStatus> {
            return EstimateItemStatus(id: n++)!.description
        }
    )
}

But I'm getting the following error.

Cannot find an initializer for type 'GeneratorOf' that accepts an argument list of type '(() -> _)'

Is there is an easier, better or more elegant way to do this?

Body:
Extension on an enum to create allValues.

extension RawRepresentable where Self: CaseIterable {
      static var allValues: [Self.RawValue] {
        return self.allCases.map { $0.rawValue}
      }
    }


来源: stackexchange

问:
Persistence.createEntityManagerFactory("something") returns null
I am learning JPA with sample project. Whenever I execute the program, it returns null. I checked follow

JPA - createEntityManagerFactory returns Null ,But,this is not helping. please help me. i have been stuck two days. I dont know where i do mistakes .

Following Exception is always happening,

```<code>1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:84)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:67)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:53)
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
        at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:47)
        at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:175)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at com.test.jpa.App.main(App.java:19)
</code>```

Main class

```<code>public class App
{

    public static void main( String[] args )
    {
        System.out.println( "I am going to connect" );
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("boom");
            if(entityManagerFactory !=null ) {
                 System.out.println( "lalala" );
            }else {
                 System.out.println( "nullllllllllllll" );
            }

    }
}
</code>```

This is Mapping class,

```<code>package com.test.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "client")
public class User {

    @Column(name = "name")
    private String name = null;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Column(name = "age")
    private int age = 0;

    @Id
    @Column(name = "No")
    private int No = 0;

    public int getNo() {
        return No;
    }

    public void setNo(int no) {
     No = no;
   }
}
</code>```

pom file

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

  <groupId>com.test</groupId>
  <artifactId>jpa</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jpa</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
             <version>1.7.30</version>
        </dependency>
        <dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>
         <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

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

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <optimize>true</optimize>
                <debug>true</debug>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-assembly-plugin</artifactId>
              <configuration>
                  <descriptorRefs>
                      <descriptorRef>jar-with-dependencies</descriptorRef>
                  </descriptorRefs>
                  <dependencySets>
                      <dependencySet>
                          <includes>
                              <include>*:jar:*</include>
                          </includes>
                          <excludes>
                              <exclude>*:sources</exclude>
                              <exclude>*:javadoc</exclude>
                          </excludes>
                      </dependencySet>
                  </dependencySets>
                 <archive>
                   <manifest>
                     <addClasspath>true</addClasspath>
                     <mainClass>com.test.jpa.App</mainClass>
                   </manifest>
                 </archive>
               </configuration>
                 <executions>
                     <execution>
                         <id>make-assembly</id>
                         <phase>package</phase>
                         <goals>
                             <goal>single</goal>
                         </goals>
                     </execution>
                 </executions>
            </plugin>
        </plugins>
   </build>
</project>
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="boom"  >
     <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>com.test.jpa.User</class>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:6767/User"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.password" value="atis"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      <property name="hibernate.show_sql" value="false"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.autocommit" value="false"/>
      <property name="hibernate.connection.provider_disables_autocommit" value="true"/>
    </properties>
  </persistence-unit>
</persistence>
</code>```

I created database with name User, table is "client" , cloumn are "No","age"-integer datatype, "name"-string datatype

update:

I tested with junit tool with follow class.

```<code>import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PersonTest {
    private EntityManagerFactory emf;

    private EntityManager em;

    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

        emf = Persistence.createEntityManagerFactory("boom");
        if(emf !=null)
        System.out.println("wooooooooooooooooooooo ");
        em = emf.createEntityManager();
    }

    @After
    public void cleanup() {
        em.close();
    }

    @Test
    public void emptyTest() {
    }
}
</code>```

When it gets executed, it is not throws null pointer exception. it prints like follow, then it passes to sucessive execution.

```<code>844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@45312be2] into BootstrapContext; was [null]
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@7fb95505] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@58be6e8]
903 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting JPA temp ClassLoader [null] into BootstrapContext; was [null]
903 [main] DEBUG org.hibernate.boot.internal.ClassLoaderAccessImpl  - ClassLoaderAccessImpl#injectTempClassLoader(null) [was null]
</code>```

But when execute using well packaged jar in command line,exeception is thrown

```<code>1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException
</code>```

thanks

答:
I fixed problem .It was dependency problem. In pom file, After i added following

```<code>   <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.12.Final</version>
        </dependency>
</code>```

and removed following dependency

```<code><dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>
</code>```

hibernate-entitymanager will add all necessary dependency.

ContentLicense: CC BY-SA 4.0

Body:
I am learning JPA with sample project. Whenever I execute the program, it returns null. I checked follow

JPA - createEntityManagerFactory returns Null ,But,this is not helping. please help me. i have been stuck two days. I dont know where i do mistakes .

Following Exception is always happening,

1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:84)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:67)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:53)
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
        at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:47)
        at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:175)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at com.test.jpa.App.main(App.java:19)

Main class

public class App
{

    public static void main( String[] args )
    {
        System.out.println( "I am going to connect" );
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("boom");
            if(entityManagerFactory !=null ) {
                 System.out.println( "lalala" );
            }else {
                 System.out.println( "nullllllllllllll" );
            }

    }
}

This is Mapping class,

package com.test.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "client")
public class User {

    @Column(name = "name")
    private String name = null;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Column(name = "age")
    private int age = 0;

    @Id
    @Column(name = "No")
    private int No = 0;

    public int getNo() {
        return No;
    }

    public void setNo(int no) {
     No = no;
   }
}

pom file

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

  <groupId>com.test</groupId>
  <artifactId>jpa</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jpa</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
             <version>1.7.30</version>
        </dependency>
        <dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>
         <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

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

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <optimize>true</optimize>
                <debug>true</debug>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-assembly-plugin</artifactId>
              <configuration>
                  <descriptorRefs>
                      <descriptorRef>jar-with-dependencies</descriptorRef>
                  </descriptorRefs>
                  <dependencySets>
                      <dependencySet>
                          <includes>
                              <include>*:jar:*</include>
                          </includes>
                          <excludes>
                              <exclude>*:sources</exclude>
                              <exclude>*:javadoc</exclude>
                          </excludes>
                      </dependencySet>
                  </dependencySets>
                 <archive>
                   <manifest>
                     <addClasspath>true</addClasspath>
                     <mainClass>com.test.jpa.App</mainClass>
                   </manifest>
                 </archive>
               </configuration>
                 <executions>
                     <execution>
                         <id>make-assembly</id>
                         <phase>package</phase>
                         <goals>
                             <goal>single</goal>
                         </goals>
                     </execution>
                 </executions>
            </plugin>
        </plugins>
   </build>
</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="boom"  >
     <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>com.test.jpa.User</class>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:6767/User"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.password" value="atis"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      <property name="hibernate.show_sql" value="false"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.autocommit" value="false"/>
      <property name="hibernate.connection.provider_disables_autocommit" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

I created database with name User, table is "client" , cloumn are "No","age"-integer datatype, "name"-string datatype

update:

I tested with junit tool with follow class.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PersonTest {
    private EntityManagerFactory emf;

    private EntityManager em;

    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

        emf = Persistence.createEntityManagerFactory("boom");
        if(emf !=null)
        System.out.println("wooooooooooooooooooooo ");
        em = emf.createEntityManager();
    }

    @After
    public void cleanup() {
        em.close();
    }

    @Test
    public void emptyTest() {
    }
}

When it gets executed, it is not throws null pointer exception. it prints like follow, then it passes to sucessive execution.

844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@45312be2] into BootstrapContext; was [null]
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@7fb95505] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@58be6e8]
903 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting JPA temp ClassLoader [null] into BootstrapContext; was [null]
903 [main] DEBUG org.hibernate.boot.internal.ClassLoaderAccessImpl  - ClassLoaderAccessImpl#injectTempClassLoader(null) [was null]

But when execute using well packaged jar in command line,exeception is thrown

1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException

thanks

Body:
I fixed problem .It was dependency problem. In pom file, After i added following

   <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.12.Final</version>
        </dependency>

and removed following dependency

<dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>

hibernate-entitymanager will add all necessary dependency.


问:
Making a Maven Plugin Optional?
How do I make a maven plugin optional so if someone does not have it, their build will not fail?  In this example, I am trying to make JSHint optional so it runs if you have access to the plugin.</p>

答:
You need to create different profiles with unique ids

```<code>   <profiles>
    <profile>
        <id>no-optional-plugins</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <!-- active this profile to enable the docker-maven-plugin -->
    <id>docker</id>
    <activation>
        <activeByDefault>false</activeByDefault>
    </activation>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.26.0</version>
                <extensions>true</extensions>
                <configuration>
                    <verbose>true</verbose>
                    <images>
                        <image>
                            <name>${docker.image.prefix}/${project.parent.artifactId}/${project.artifactId}</name>
                            <build>
                                <from>java:8-jdk-alpine</from>
                                <entryPoint>
                                    <exec>
                                        <args>java</args>
                                        <args>-jar</args>
                                        <args>/maven/${project.artifactId}-${project.version}.jar</args>
                                    </exec>
                                </entryPoint>
                                <assembly>
                                    <descriptorRef>artifact</descriptorRef>
                                </assembly>
                            </build>
                        </image>
                    </images>
                </configuration>
                <executions>
                    <execution>
                        <id>build</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    </profile>
</profiles>
</code>```

Build with docker image creation mvn clean install -P docker

Build without docker mvn clean install

ContentLicense: CC BY-SA 3.0

Title: Making a Maven Plugin Optional?

Body:
You need to create different profiles with unique ids

   <profiles>
    <profile>
        <id>no-optional-plugins</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <!-- active this profile to enable the docker-maven-plugin -->
    <id>docker</id>
    <activation>
        <activeByDefault>false</activeByDefault>
    </activation>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.26.0</version>
                <extensions>true</extensions>
                <configuration>
                    <verbose>true</verbose>
                    <images>
                        <image>
                            <name>${docker.image.prefix}/${project.parent.artifactId}/${project.artifactId}</name>
                            <build>
                                <from>java:8-jdk-alpine</from>
                                <entryPoint>
                                    <exec>
                                        <args>java</args>
                                        <args>-jar</args>
                                        <args>/maven/${project.artifactId}-${project.version}.jar</args>
                                    </exec>
                                </entryPoint>
                                <assembly>
                                    <descriptorRef>artifact</descriptorRef>
                                </assembly>
                            </build>
                        </image>
                    </images>
                </configuration>
                <executions>
                    <execution>
                        <id>build</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    </profile>
</profiles>

Build with docker image creation mvn clean install -P docker

Build without docker mvn clean install


问:
Getting Recent folders and Recent files in Windows XP
i wrote some code to get Recent folders and files in C# by using

```<code>DirectoryInfo d = new DirectoryInfo(
                          System.Environment.GetFolderPath(
                              Environment.SpecialFolder.Recent)).
</code>```

It is working fine in windows 7.But it is not working in windows xp.

Because there is no folder with "C:\Users\AppData\Roaming\Microsoft\Windows\Recent" in XP.
Then how to get recent files in windows xp?

答: On Windows XP, System.Environment.GetFolderPath(Environment.SpecialFolder.Recent) will not return "C:\Users\AppData\Roaming\Microsoft\Windows\Recent", it returns the correct path. In my case this is "C:\Documents and Settings\daniel.hilgarth\Recent".

Body:
i wrote some code to get Recent folders and files in C# by using

DirectoryInfo d = new DirectoryInfo(
                          System.Environment.GetFolderPath(
                              Environment.SpecialFolder.Recent)).

It is working fine in windows 7.But it is not working in windows xp.

Because there is no folder with "C:\Users\AppData\Roaming\Microsoft\Windows\Recent" in XP.
Then how to get recent files in windows xp?


问:
Angular 7 web app page refresh gives "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
I'm working on a angular 7 web application which is hosted in IIS in Windows Server 2012 R2. This is on ASP.NET CORE 2.2.

When I navigate the application with the domain name it works fine, but if refresh the page I visited, then it gives me "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."

If I check the developer tools in chrome, it shows me the following error. Please refer the image below:

This user-type-selection:1 is the route path and the param value.

I tried to add the web.config in the src folder on the ClientApp and it as an asset in angular.json. It add the web.config in the release folder but it give me 500 internal server error for that.

Anyone has any thoughts about this?

答:
This issue fixed with the following in the web.config:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <!--<action type=”Rewrite” url=”/my-app/” /> -->
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
</code>```

Please make user URL Rewrite extension is installed in IIS.

I tried the above web.config before but without the above extension and it gave me the 500 error because of that.

Happy coding.

Body:
This issue fixed with the following in the web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <!--<action type=”Rewrite” url=”/my-app/” /> -->
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Please make user URL Rewrite extension is installed in IIS.

I tried the above web.config before but without the above extension and it gave me the 500 error because of that.

Happy coding.


问:
Add new button to tooltip area
I need to add new button or checkbox in order to disable the tour in general for my app. Is it possible add new button into tooltip and catch click on it in order to disable the door forever?

Thanks
Luca

答:
```<code>introJs().setOptions({
   steps: [
       {
         element: '#step1',
         intro: "<button>click me</button>"
       },
   ]
})
</code>```

check this out html in tooltip

Title: Add new button to tooltip area

Body:
introJs().setOptions({
   steps: [
       {
         element: '#step1',
         intro: "<button>click me</button>"
       },
   ]
})

check this out html in tooltip


问:
Why won't the sequencer in AudioKit play my drum sounds and why is the volume so low?
First of all, a great framework. This is singlehandedly allowing me to graduate from my master's program. Also, I'm a sponsor! Any help would be taken with much gratitude. I can also push my repository and share it on GitHub for a closer look.

Anyway, here is my code

```<code>import Foundation
import AudioKit

class DrumSounds {

    let drums = AKMIDISampler()
    var currentBPM = 60
    var rideCymbalFile: AKAudioFile?
    var snareDrumFile: AKAudioFile?
    var bassDrumFile: AKAudioFile?
    var hiHatFile: AKAudioFile?
    let sequencer = AKAppleSequencer(filename: "4tracks")
    var booster = AKBooster()
    init() {

        do{

        try rideCymbalFile = AKAudioFile(readFileName: "rideCymbalSound.wav")
        try snareDrumFile = AKAudioFile(readFileName: "snareDrumSound.wav")
        try bassDrumFile = AKAudioFile(readFileName: "bassDrumSound.wav")
        try hiHatFile = AKAudioFile(readFileName: "hiHatSound.mp3")
        try drums.loadAudioFiles([rideCymbalFile!,
                                   snareDrumFile!,
                                   bassDrumFile!,
                                   hiHatFile!])

        } catch {
            print("error loading samples to drum object")
        }

        drums.volume = 1
        booster = AKBooster(drums)
        AudioKit.output = drums
        sequencer.clearRange(start: AKDuration(beats: 0), duration: AKDuration(beats: 100))
        sequencer.debug()
        sequencer.setGlobalMIDIOutput(drums.midiIn)
        sequencer.enableLooping(AKDuration(beats: 4))
        sequencer.setTempo(Double(currentBPM))

    }

    func playDrumSounds () {

        do {
            try AKSettings.setSession(category: .playAndRecord, with:  AVAudioSession.CategoryOptions.defaultToSpeaker)

            let session = AVAudioSession.sharedInstance()
            try session.setCategory(AVAudioSession.Category.playAndRecord)

            if !AKSettings.headPhonesPlugged {
                try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
         }
        }catch {
            print("error in settings.setSession")
        }

        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 0), duration: AKDuration(beats: 1.0))
        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 1), duration: AKDuration(beats: 1.0))
        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 2), duration: AKDuration(beats: 1.0))
        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 3), duration: AKDuration(beats: 1.0))
        sequencer.play()

    }
}
</code>```

答:
I figured it out by randomly stumbling upon a comment in another post. The volume is low because you need to enable "Audio, AirPlay, and Picture in Picture" in "Background Modes" under "Signing & Capabilities". Click the "+" button in the top left to add a capability:

As for playing the right drum sound: The right drum sound was, in fact, being played. However I set the MIDI note number too low, so it sounded like harsh static. If you're having this problem and have never worked with MIDI (like me), here is a link to a description of MIDI note numbers: https://www.inspiredacoustics.com/en/MIDI_note_numbers_and_center_frequencies. The higher the number, the higher the frequency. Changing the MIDI note number will change the frequency of your audio file!

Body:
First of all, a great framework. This is singlehandedly allowing me to graduate from my master's program. Also, I'm a sponsor! Any help would be taken with much gratitude. I can also push my repository and share it on GitHub for a closer look.

Anyway, here is my code

import Foundation
import AudioKit

class DrumSounds {

    let drums = AKMIDISampler()
    var currentBPM = 60
    var rideCymbalFile: AKAudioFile?
    var snareDrumFile: AKAudioFile?
    var bassDrumFile: AKAudioFile?
    var hiHatFile: AKAudioFile?
    let sequencer = AKAppleSequencer(filename: "4tracks")
    var booster = AKBooster()
    init() {

        do{

        try rideCymbalFile = AKAudioFile(readFileName: "rideCymbalSound.wav")
        try snareDrumFile = AKAudioFile(readFileName: "snareDrumSound.wav")
        try bassDrumFile = AKAudioFile(readFileName: "bassDrumSound.wav")
        try hiHatFile = AKAudioFile(readFileName: "hiHatSound.mp3")
        try drums.loadAudioFiles([rideCymbalFile!,
                                   snareDrumFile!,
                                   bassDrumFile!,
                                   hiHatFile!])

        } catch {
            print("error loading samples to drum object")
        }

        drums.volume = 1
        booster = AKBooster(drums)
        AudioKit.output = drums
        sequencer.clearRange(start: AKDuration(beats: 0), duration: AKDuration(beats: 100))
        sequencer.debug()
        sequencer.setGlobalMIDIOutput(drums.midiIn)
        sequencer.enableLooping(AKDuration(beats: 4))
        sequencer.setTempo(Double(currentBPM))

    }

    func playDrumSounds () {

        do {
            try AKSettings.setSession(category: .playAndRecord, with:  AVAudioSession.CategoryOptions.defaultToSpeaker)

            let session = AVAudioSession.sharedInstance()
            try session.setCategory(AVAudioSession.Category.playAndRecord)

            if !AKSettings.headPhonesPlugged {
                try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
         }
        }catch {
            print("error in settings.setSession")
        }

        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 0), duration: AKDuration(beats: 1.0))
        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 1), duration: AKDuration(beats: 1.0))
        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 2), duration: AKDuration(beats: 1.0))
        sequencer.tracks[0].add(noteNumber: 0, velocity: 127, position: AKDuration(beats: 3), duration: AKDuration(beats: 1.0))
        sequencer.play()

    }
}


问:
How to use pagination in table view
Basically i have a table view and get 5 item in every time when i call the api. So how to use/ reload more data white scrolling table view.
array.count-1 not for me at cell for row indexpath because when device size bigger all data shown at a time and api not call</p>

答:
Declare

current page = 1

Then add this method in viewController

```<code>private func isLastCell(indexPath: IndexPath) -> Bool {
    print(indexPath)
    if array.count > 0 {
        return ((indexPath.section == sectionCount-1) && (indexPath.row == (array.count-1)))
    } else {
        return false
    }
</code>```

}

After that in tableViewWillDisplayCell method add this function

```<code>if array.count > 0, self.isLastCell(indexPath: indexPath) {
            self.currentPage += 1
            // call api here
  }
</code>```

It works for me

Title: How to use pagination in table view

Body:
Declare

current page = 1

Then add this method in viewController

private func isLastCell(indexPath: IndexPath) -> Bool {
    print(indexPath)
    if array.count > 0 {
        return ((indexPath.section == sectionCount-1) && (indexPath.row == (array.count-1)))
    } else {
        return false
    }

}

After that in tableViewWillDisplayCell method add this function

if array.count > 0, self.isLastCell(indexPath: indexPath) {
            self.currentPage += 1
            // call api here
  }

It works for me


问:
How to monitor method execution at third party library?
I have task to somehow monitor method calling at logback library. I started doing it with spring aop. So, for instance, i should catch all methods execution at ch.qos.logback.classic.Logger class. And there is my Aspect for it:

```<code>@Aspect
@Configuration
public class LogbackAspect {

    @Before(value = "execution(* ch.qos.logback.classic.Logger.*(..))")
    public void getInfo(JoinPoint joinPoint) {
         System.out.println("+++++AOP " + joinPoint.getSignature().getName());
}
}
</code>```

But it's not working for now, so, is there any possibility to intercept method execution with spring aop? Or there are some better ways to do it?

答:
Check this other answer out Intercepting third party functions in android using AspectJ

Unfortunately, you can only weave your own code.

However, depending on what you actually need to do with Logback, you could create a custom Appender and do what you need to in there?

UPDATE

Seeing as you want to record some form of metric of these exceptions, you could configure a StatusListener according to the logstash-logback docs

https://github.com/logstash/logstash-logback-encoder#status-listeners

With this, you could receive the event, and record whatever metrics you need

Body:
I have task to somehow monitor method calling at logback library. I started doing it with spring aop. So, for instance, i should catch all methods execution at ch.qos.logback.classic.Logger class. And there is my Aspect for it:

@Aspect
@Configuration
public class LogbackAspect {

    @Before(value = "execution(* ch.qos.logback.classic.Logger.*(..))")
    public void getInfo(JoinPoint joinPoint) {
         System.out.println("+++++AOP " + joinPoint.getSignature().getName());
}
}

But it's not working for now, so, is there any possibility to intercept method execution with spring aop? Or there are some better ways to do it?


问:
How to write parameter one recommend Endpoint To Database in Angular
I'm newbie in Angular. I have a database includes movies and actors, and one recommend endpoint url.
I want to recommend something for each elements( movies and actors) when I send request to recommend endpoint by ID. I think I need to use HttpParams but how.  Anyone help ?

Edit:
 I want to clearify this.

I have one database(http://travis.com:3002/db/commit)
 and one recommend url ( http://10.10.10.10:2999/getMostSimilar?model_id = 1232321455&numSimilar=10%uri=neo4j://individuals/1)...
I send request to recommend url to recommend  uri for each element in the database object by id which have an id.

Thanks.

答:
Try like this  </p>

```<code>const params = new HttpParams();
params.set('one', '1')
params.set('two', '2');
this.httpClient.get("/api/countries", {params})
</code>```

Body:
Try like this

const params = new HttpParams();
params.set('one', '1')
params.set('two', '2');
this.httpClient.get("/api/countries", {params})


问:
HTML Table nested selectors
I want to select a certain cell from within a colgroup and can't figure out how. Below is an example:

table {
  position:relative;
  top:50px;
  margin:0 auto;
  border-collapse:collapse;
}

td, th {
  border:1px solid black;
  width:75px;
  height:25px;
}

.first {
  background-color:red;
}

.second {
  background-color:yellow;
}

.third {
  background-color:green;
}

.cell {
  background-color:white;
}

.first .cell {
  text-align:left;
  border:5px solid black;
  color:red;
}

.second > .cell {
  text-align:center;
  border:5px solid black;
  color:red;
}

.third .cell {
  text-align:right;
  border:5px solid black;
  color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <colgroup>
    <col span=2 class='first'>
    <col span=2 class='second'>
    <col span=2 class='third'>
  </colgroup>
  <thead>
    <th colspan=6>asdad</th>
  </thead>
  <tbody>
    <tr>
      <th>asdad</th>
      <td class='cell'>One</td>
      <th>asdad</th>
      <td>fghfghf</td>
      <th>sdadsad</th>
      <td>yututu</td>
    </tr>
        <tr>
      <th>asdad</th>
      <td>jhkjhk</td>
      <th>asdad</th>
      <td class='cell'>Two</td>
      <th>sdadsad</th>
      <td>yututu</td>
    </tr>
    <tr>
      <th>asdad</th>
      <td>jhkjhk</td>
      <th>asdad</th>
      <td>fghfghf</td>
      <th>sdadsad</th>
      <td class='cell'>Three</td>
    </tr>
  </tbody>
</table></code>```

I have tried most selectors form here, but they don't seem to work. How can I achieve what I want? I would also want to select the #cell elements using Javascript or Jquery. $('.first #cell') is also not working. $('.first').find('#cell') also failed.

答:
First of all, ids must be used only once on a page. That's the concept of ids: Being unique. So the idea of "finding the first occurence of #cell" is weird.

If you have the chance of giving ids to the table cells you want to select, things are very easy: Select them by their unique id:

```<code>#cell1
#cell2
#cell3
…
</code>```

Same thing in jQuery:

```<code>$('#cell1')
$('#cell2')
$('#cell3')
…
</code>```

But if you want to select a certain cell without id (or class), things might get a bit more complicated. Maybe you can try the nth-child-selector. https://www.w3schools.com/cssref/sel_nth-child.asp

Title: HTML Table nested selectors

Body:
I want to select a certain cell from within a colgroup and can't figure out how. Below is an example:

table {
  position:relative;
  top:50px;
  margin:0 auto;
  border-collapse:collapse;
}

td, th {
  border:1px solid black;
  width:75px;
  height:25px;
}

.first {
  background-color:red;
}

.second {
  background-color:yellow;
}

.third {
  background-color:green;
}

.cell {
  background-color:white;
}

.first .cell {
  text-align:left;
  border:5px solid black;
  color:red;
}

.second > .cell {
  text-align:center;
  border:5px solid black;
  color:red;
}

.third .cell {
  text-align:right;
  border:5px solid black;
  color:red;
}

  <colgroup>
    <col span=2 class='first'>
    <col span=2 class='second'>
    <col span=2 class='third'>
  </colgroup>

    asdad

      asdad
      One
      asdad
      fghfghf
      sdadsad
      yututu

      asdad
      jhkjhk
      asdad
      Two
      sdadsad
      yututu

      asdad
      jhkjhk
      asdad
      fghfghf
      sdadsad
      Three

I have tried most selectors form here, but they don't seem to work. How can I achieve what I want? I would also want to select the #cell elements using Javascript or Jquery. $('.first #cell') is also not working. $('.first').find('#cell') also failed.

Body:
First of all, ids must be used only once on a page. That's the concept of ids: Being unique. So the idea of "finding the first occurence of #cell" is weird.

If you have the chance of giving ids to the table cells you want to select, things are very easy: Select them by their unique id:

#cell1
#cell2
#cell3
…

Same thing in jQuery:

$('#cell1')
$('#cell2')
$('#cell3')
…

But if you want to select a certain cell without id (or class), things might get a bit more complicated. Maybe you can try the nth-child-selector. https://www.w3schools.com/cssref/sel_nth-child.asp


问:
Plotly: How to plot a bar & line chart combined with a bar chart as subplots?
I am trying to plot two different charts in python through plotly. I have two plots, one plot consists of merged graph ( line and bar chart) like the following,

,

and another one is bar chart as follows,

I wanted to display one single chart with these two combined charts and display the same. I have tried this in plotly through make_subplots but I am not able to achieve the results properly. Below are the codes for creating these two charts,

Line_Bar_chart Code:

```<code>import plotly.graph_objects as go
from plotly.offline import iplot

trace1  = go.Scatter(
        mode='lines+markers',
        x = df['Days'],
        y = df['Perc_Cases'],
        name="Percentage Cases",
        marker_color='crimson'
    )

trace2 = go.Bar(
        x = df['Days'],
        y = df['Count_Cases'],
        name="Absolute_cases",
        yaxis='y2',
        marker_color ='green',
        marker_line_width=1.5,
        marker_line_color='rgb(8,48,107)',
        opacity=0.5
    )

data = [trace1, trace2]

layout = go.Layout(
    title_text='States_Name',
    yaxis=dict(
        range = [0, 100],
        side = 'right'
    ),
    yaxis2=dict(
        overlaying='y',
        anchor='y3',
    )
)
fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='multiple-axes-double')
**Line_Bar_chart Code**:
</code>```

Bar_chart Code:

```<code>trace2 = go.Bar(
        x = df['Days'],
        y = df['Perc_Cases'],
        yaxis='y2',
        marker_color ='green',
        marker_line_width=1.5,
        marker_line_color='rgb(8,48,107)',
        opacity=0.5,
    )
layout = go.Layout(
    title_text='States_Name',
    yaxis2=dict(
        overlaying='y',

    )
)
fig = go.Figure(data=trace2, layout=layout)
iplot(fig, filename='multiple-axes-double')
</code>```

Any help on how to make subplots of these two graphs like below would be helpful,

答:
The key here is to assign your traces to the subplot through row and col in fig.add_trace(). And you don't have to use from plotly.offline import iplot for the latest plotly updates.

Plot:

Code:

```<code># imports
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# data
df = pd.DataFrame({'Index': {0: 1.0,
                              1: 2.0,
                              2: 3.0,
                              3: 4.0,
                              4: 5.0,
                              5: 6.0,
                              6: 7.0,
                              7: 8.0,
                              8: 9.0,
                              9: 10.0},
                             'A': {0: 15.0,
                              1: 6.0,
                              2: 5.0,
                              3: 4.0,
                              4: 3.0,
                              5: 2.0,
                              6: 1.0,
                              7: 0.5,
                              8: 0.3,
                              9: 0.1},
                             'B': {0: 1.0,
                              1: 4.0,
                              2: 2.0,
                              3: 5.0,
                              4: 4.0,
                              5: 6.0,
                              6: 7.0,
                              7: 2.0,
                              8: 8.0,
                              9: 1.0},
                             'C': {0: 12.0,
                              1: 6.0,
                              2: 5.0,
                              3: 4.0,
                              4: 3.0,
                              5: 2.0,
                              6: 1.0,
                              7: 0.5,
                              8: 0.2,
                              9: 0.1}})
# set up plotly figure
fig = make_subplots(1,2)

# add first bar trace at row = 1, col = 1
fig.add_trace(go.Bar(x=df['Index'], y=df['A'],
                     name='A',
                     marker_color = 'green',
                     opacity=0.4,
                     marker_line_color='rgb(8,48,107)',
                     marker_line_width=2),
              row = 1, col = 1)

# add first scatter trace at row = 1, col = 1
fig.add_trace(go.Scatter(x=df['Index'], y=df['B'], line=dict(color='red'), name='B'),
              row = 1, col = 1)

# add first bar trace at row = 1, col = 2
fig.add_trace(go.Bar(x=df['Index'], y=df['C'],
                     name='C',
                     marker_color = 'green',
                     opacity=0.4,
                     marker_line_color='rgb(8,48,107)',
                    marker_line_width=2),
              row = 1, col = 2)

fig.show()
</code>```

Body:
I am trying to plot two different charts in python through plotly. I have two plots, one plot consists of merged graph ( line and bar chart) like the following,

,

and another one is bar chart as follows,

I wanted to display one single chart with these two combined charts and display the same. I have tried this in plotly through make_subplots but I am not able to achieve the results properly. Below are the codes for creating these two charts,

Line_Bar_chart Code:

import plotly.graph_objects as go
from plotly.offline import iplot

trace1  = go.Scatter(
        mode='lines+markers',
        x = df['Days'],
        y = df['Perc_Cases'],
        name="Percentage Cases",
        marker_color='crimson'
    )

trace2 = go.Bar(
        x = df['Days'],
        y = df['Count_Cases'],
        name="Absolute_cases",
        yaxis='y2',
        marker_color ='green',
        marker_line_width=1.5,
        marker_line_color='rgb(8,48,107)',
        opacity=0.5
    )

data = [trace1, trace2]

layout = go.Layout(
    title_text='States_Name',
    yaxis=dict(
        range = [0, 100],
        side = 'right'
    ),
    yaxis2=dict(
        overlaying='y',
        anchor='y3',
    )
)
fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='multiple-axes-double')
**Line_Bar_chart Code**:

Bar_chart Code:

trace2 = go.Bar(
        x = df['Days'],
        y = df['Perc_Cases'],
        yaxis='y2',
        marker_color ='green',
        marker_line_width=1.5,
        marker_line_color='rgb(8,48,107)',
        opacity=0.5,
    )
layout = go.Layout(
    title_text='States_Name',
    yaxis2=dict(
        overlaying='y',

    )
)
fig = go.Figure(data=trace2, layout=layout)
iplot(fig, filename='multiple-axes-double')

Any help on how to make subplots of these two graphs like below would be helpful,

Body:
The key here is to assign your traces to the subplot through row and col in fig.add_trace(). And you don't have to use from plotly.offline import iplot for the latest plotly updates.

Plot:

Code:

# imports
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# data
df = pd.DataFrame({'Index': {0: 1.0,
                              1: 2.0,
                              2: 3.0,
                              3: 4.0,
                              4: 5.0,
                              5: 6.0,
                              6: 7.0,
                              7: 8.0,
                              8: 9.0,
                              9: 10.0},
                             'A': {0: 15.0,
                              1: 6.0,
                              2: 5.0,
                              3: 4.0,
                              4: 3.0,
                              5: 2.0,
                              6: 1.0,
                              7: 0.5,
                              8: 0.3,
                              9: 0.1},
                             'B': {0: 1.0,
                              1: 4.0,
                              2: 2.0,
                              3: 5.0,
                              4: 4.0,
                              5: 6.0,
                              6: 7.0,
                              7: 2.0,
                              8: 8.0,
                              9: 1.0},
                             'C': {0: 12.0,
                              1: 6.0,
                              2: 5.0,
                              3: 4.0,
                              4: 3.0,
                              5: 2.0,
                              6: 1.0,
                              7: 0.5,
                              8: 0.2,
                              9: 0.1}})
# set up plotly figure
fig = make_subplots(1,2)

# add first bar trace at row = 1, col = 1
fig.add_trace(go.Bar(x=df['Index'], y=df['A'],
                     name='A',
                     marker_color = 'green',
                     opacity=0.4,
                     marker_line_color='rgb(8,48,107)',
                     marker_line_width=2),
              row = 1, col = 1)

# add first scatter trace at row = 1, col = 1
fig.add_trace(go.Scatter(x=df['Index'], y=df['B'], line=dict(color='red'), name='B'),
              row = 1, col = 1)

# add first bar trace at row = 1, col = 2
fig.add_trace(go.Bar(x=df['Index'], y=df['C'],
                     name='C',
                     marker_color = 'green',
                     opacity=0.4,
                     marker_line_color='rgb(8,48,107)',
                    marker_line_width=2),
              row = 1, col = 2)

fig.show()


问:
How to unset GEM_HOME
Hi my understanding of the terminal is small. I'm trying to install rvm can someone tell me how to unset GEM_HOME? I have a feeling I need to edit some file, but I don't know if its a command line or a file I need to open and comment out.   I'm running Mac OSX 10.14.6 Mojave?

Thank you

```<code>Joshuas-iMac:~ compy$ \curl -sSL https://get.rvm.io | bash -s stable
Downloading https://github.com/rvm/rvm/archive/1.29.9.tar.gz
Downloading https://github.com/rvm/rvm/releases/download/1.29.9/1.29.9.tar.gz.asc
Found PGP signature at: 'https://github.com/rvm/rvm/releases/download/1.29.9/1.29.9.tar.gz.asc',
but no GPG software exists to validate it, skipping.
Upgrading the RVM installation in /Users/compy/.rvm/
    RVM PATH line found in /Users/compy/.mkshrc /Users/compy/.profile /Users/compy/.bashrc /Users/compy/.zshrc.
    RVM sourcing line found in /Users/compy/.profile /Users/compy/.bash_profile /Users/compy/.zlogin.
Upgrade of RVM in /Users/compy/.rvm/ is complete.
  * WARNING: you have set GEM_HOME="/Users/compy/.gem/ruby/2.5.1"
     This is conflicting with RVM. Make sure to call:

           unset GEM_HOME

Thanks for installing RVM
</code>```

答:
The answer is on the error logs:
unset GEM_HOME

On comman line do:

unset GEM_HOME ; \curl -sSL https://get.rvm.io | bash -s stable

Title: How to unset GEM_HOME

Body:
Hi my understanding of the terminal is small. I'm trying to install rvm can someone tell me how to unset GEM_HOME? I have a feeling I need to edit some file, but I don't know if its a command line or a file I need to open and comment out.   I'm running Mac OSX 10.14.6 Mojave?

Thank you

Joshuas-iMac:~ compy$ \curl -sSL https://get.rvm.io | bash -s stable
Downloading https://github.com/rvm/rvm/archive/1.29.9.tar.gz
Downloading https://github.com/rvm/rvm/releases/download/1.29.9/1.29.9.tar.gz.asc
Found PGP signature at: 'https://github.com/rvm/rvm/releases/download/1.29.9/1.29.9.tar.gz.asc',
but no GPG software exists to validate it, skipping.
Upgrading the RVM installation in /Users/compy/.rvm/
    RVM PATH line found in /Users/compy/.mkshrc /Users/compy/.profile /Users/compy/.bashrc /Users/compy/.zshrc.
    RVM sourcing line found in /Users/compy/.profile /Users/compy/.bash_profile /Users/compy/.zlogin.
Upgrade of RVM in /Users/compy/.rvm/ is complete.
  * WARNING: you have set GEM_HOME="/Users/compy/.gem/ruby/2.5.1"
     This is conflicting with RVM. Make sure to call:

           unset GEM_HOME

Thanks for installing RVM


问:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")

In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?

Tried:

Rollback tables: heroku run php artisan migrate:rollback

migrate fresh: heroku run php artisan migrate:fresh

migrate reset: heroku run php artisan migrate:reset

The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.

stories table:

        <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateStoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('story');
                $table->date('published_on');
                $table->integer('count_views')->default(0);
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedBigInteger("category_id");
                $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stories');
        }
    }

```

<p>categories table: </p>

<pre class="lang-php prettyprint-override"><code>    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateCategoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category');
                $table->string('title')->nullable();
                $table->string('img')->nullable();
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('categories');
        }
    }
</code>```

Story model:

        <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Reviews;
    use App\User;
    use App\Category;
    use App\ReadingList;

    class Story extends Model
    {

        protected $guarded = [];

        public function readingList()
        {
            return $this->belongsTo(ReadingList::class);
        }

        public function category()
        {
            return $this->belongsTo(Category::class);
        }

        public function reviews() {
            return $this->hasMany(Reviews::class);
        }

        public function user() {
            return $this->belongsTo(User::class);
        }

    }
```

<p>Category model: </p>

<pre class="lang-php prettyprint-override"><code>    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    use App\Story;

    class Category extends Model
    {
        protected $guarded = [];

        public function story()
        {
            return $this->hasMany(Story::class);
        }

    }

</code>```

Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.

答:
You should change date in migration file names

Example

```<code>2019_07_29_113341_create_categories_table
2019_07_30_113341_create_stories_table
</code>```

the older date time would be the first to run,

you should migrate categories table then stories

Hope help you

Body:
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")

In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?

Tried:

Rollback tables: heroku run php artisan migrate:rollback

migrate fresh: heroku run php artisan migrate:fresh

migrate reset: heroku run php artisan migrate:reset

The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.

stories table:

        <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateStoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('story');
                $table->date('published_on');
                $table->integer('count_views')->default(0);
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedBigInteger("category_id");
                $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stories');
        }
    }

categories table:

    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateCategoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category');
                $table->string('title')->nullable();
                $table->string('img')->nullable();
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('categories');
        }
    }

Story model:

        <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Reviews;
    use App\User;
    use App\Category;
    use App\ReadingList;

    class Story extends Model
    {

        protected $guarded = [];

        public function readingList()
        {
            return $this->belongsTo(ReadingList::class);
        }

        public function category()
        {
            return $this->belongsTo(Category::class);
        }

        public function reviews() {
            return $this->hasMany(Reviews::class);
        }

        public function user() {
            return $this->belongsTo(User::class);
        }

    }

Category model:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    use App\Story;

    class Category extends Model
    {
        protected $guarded = [];

        public function story()
        {
            return $this->hasMany(Story::class);
        }

    }

Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.

Body:
You should change date in migration file names

Example

2019_07_29_113341_create_categories_table
2019_07_30_113341_create_stories_table

the older date time would be the first to run,

you should migrate categories table then stories

Hope help you


问:
Uber cool Linear Gradients in CSS3
Is it possible to create (without images), really cool looking linear gradients like the ones you see in the Ribbon menu controls?

Does anyone know of any tutorials, articles resources or samples that demonstrate/show off this kinda gradient?

答:
Background Gradient:

```<code>background: -moz-linear-gradient(center top , #ededed, #ededed) repeat scroll 0 0 transparent;
border: 1px solid #e1e1e1;
/* For WebKit (Safari, Google Chrome etc) */
background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ededed));
/* For Mozilla/Gecko (Firefox etc) */
background: -moz-linear-gradient(top, #ededed, #ededed);
/* For Internet Explorer 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ededed, endColorstr=#ededed);
/* For Internet Explorer 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ededed, endColorstr=#ededed)";
</code>```

Text Shadow Effect:

```<code>box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
</code>```

Title: Uber cool Linear Gradients in CSS3

Body:
Background Gradient:

background: -moz-linear-gradient(center top , #ededed, #ededed) repeat scroll 0 0 transparent;
border: 1px solid #e1e1e1;
/* For WebKit (Safari, Google Chrome etc) */
background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ededed));
/* For Mozilla/Gecko (Firefox etc) */
background: -moz-linear-gradient(top, #ededed, #ededed);
/* For Internet Explorer 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ededed, endColorstr=#ededed);
/* For Internet Explorer 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ededed, endColorstr=#ededed)";

Text Shadow Effect:

box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);


Title: How to round floats in a nested list to 2 decimal places?

Body:
I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list

Body:
You can use recursion if your list is arbitrarily nested. If your list is 3 level nested then use @Guy's answer or @mrEvgenX's answer.

In [51]: def recur(lst):
    ...:     if isinstance(lst,float):
    ...:         return '%.2f'%lst #use round(lst,2) if you want float instead of string.
    ...:     else:
    ...:         return [recur(i) for i in lst]

In [52]: recur(l_b)

Output

[[['57.50', '2.88'],
  ['83.75', '4.19'],
  ['83.75', '18.71'],
  ['57.50', '18.71'],
  ['57.50', '2.88']],
 [['83.75', '18.71'],
  ['57.50', '18.71'],
  ['57.50', '34.09'],
  ['83.75', '34.54'],
  ['83.75', '18.71']],
 [['0.00', '0.00'],
  ['18.12', '0.91'],
  ['18.12', '16.70'],
  ['-2.53', '16.70'],
  ['0.00', '0.00']],
 [['18.12', '16.70'],
  ['-2.53', '16.70'],
  ['-5.00', '33.00'],
  ['18.12', '33.40'],
  ['18.12', '16.70']]]


问:
Delete images and pdf when the session is over
I want to develop a healthcare app in android. the doctor will be authenticate for a specific time to access patient's medical reports and download them to the application (reports will be in a block-chain or a db). when the session is over all of those downloaded data (reports) should be permanently deleted from the doctors mobile. what is the best approach to delete these data?

答:
Storing files in DB is never advised. Rather, they should be stored as File themselves and you can save their path in the DB searching and accessing the files.

Your point about session timeout is too broad. It could be carried out in several ways, like Logout, Time Limit expired, Case closed from the Patient/Doctor's End etc.

You can try these steps if you find them suitable:

Once the doctor selects documents to be saved, download and save them in the Internal Storage of your app. Concurrently, save their respective path and download timestamp in a DB Table for future reference.

If your files are confidential and shouldn't be read outside your app, you can either encrypt them using an encryption algorithm and then save them on the device. You can also save them in different extensions and with random names to further make it complex for general users to extract them from the device. You will have to decrypt them at the time of viewing though.

If you think that the data in the file can be parsed and raw (text) data can be extracted, you can also try implementing a DB table and save such information in the DB itself. In such a case, there would be no files being saved on the device.

Now, you have your content (be it in a file system or DB) and your next task is to delete them once the session is over.

For LogOut Case, simply delete all the available data (both from the file system and DB), cleaning everything.

For Doctor Deleting the case, You can remove all the files for the selected case from the device. This information could be easily maintained in a DB Table.

For the case where a patient deletes/closes, you will have to implement a Push Notification service, wherein your server will send a delete command to the device. On receiving the notification on the app, you can follow the same steps.

For time limit expired, The simplest logic is to check, either every day at a certain time or every time your app is opened, for all the files which have a timestamp having 7 days older than today's date. Note the timestamp and file information is stored in the DB.

To check every day at a certain time, You will have to implement AlarmManager which will invoke a background service to carry out the task.

Note: There could be more possible ways to do such a specific task, however, these are the simplest and most widely used approaches.


答:
You don't necessarily need HttpParams to make a request via HttpClient.

The simplest way is just to form the url:

```<code>constructor(private http: HttpClient) {}

getMovie(id): Observable<Movie> {
  const url = `https://mydatabase.com/movies?id=${id}`; // multiline strings (``)
  return this.http.get<Movie>(url);
}
</code>```

Where Movie is some interface you have created with properties that match your endpoint's response.

Edit:

If you want to use HttpParams, you can do the following:

```<code>constructor(private http: HttpClient) {}

getMovie(id): Observable<Movie> {
  const url = 'https://mydatabase.com/movies';
  const params = new HttpParams()
    .set('id', id);
  return this.http.get<Movie>(url, { params });
}
</code>```

Title: How to write parameter one recommend Endpoint To Database in Angular

Body:
I'm newbie in Angular. I have a database includes movies and actors, and one recommend endpoint url.
I want to recommend something for each elements( movies and actors) when I send request to recommend endpoint by ID. I think I need to use HttpParams but how.  Anyone help ?

Edit:
 I want to clearify this.

I have one database(http://travis.com:3002/db/commit)
 and one recommend url ( http://10.10.10.10:2999/getMostSimilar?model_id = 1232321455&numSimilar=10%uri=neo4j://individuals/1)...
I send request to recommend url to recommend  uri for each element in the database object by id which have an id.

Thanks.

Body:
You don't necessarily need HttpParams to make a request via HttpClient.

The simplest way is just to form the url:

constructor(private http: HttpClient) {}

getMovie(id): Observable<Movie> {
  const url = `https://mydatabase.com/movies?id=${id}`; // multiline strings (``)
  return this.http.get<Movie>(url);
}

Where Movie is some interface you have created with properties that match your endpoint's response.

Edit:

If you want to use HttpParams, you can do the following:

constructor(private http: HttpClient) {}

getMovie(id): Observable<Movie> {
  const url = 'https://mydatabase.com/movies';
  const params = new HttpParams()
    .set('id', id);
  return this.http.get<Movie>(url, { params });
}


问:
Why can't I send Mutex<*mut c_void> between threads?
I need to share an object created from C++ between Rust threads. I have wrapped it in a Mutex construct, so now it is safe to be sent between threads. However the compiler won't let me do what.

error[E0277]: `*mut std::ffi::c_void` cannot be sent between threads safely
   --> sendsync.rs:14:2
    |
14  |     thread::spawn(move || {
    |     ^^^^^^^^^^^^^ `*mut std::ffi::c_void` cannot be sent between threads safely
    |
    = help: within `Api`, the trait `std::marker::Send` is not implemented for `*mut std::ffi::c_void`
    = note: required because it appears within the type `OpaqWrapper`
    = note: required because it appears within the type `Api`
    = note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Mutex<Api>`
    = note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<std::sync::Mutex<Api>>`
    = note: required because it appears within the type `[closure@sendsync.rs:14:16: 19:3 safe_obj:std::sync::Arc<std::sync::Mutex<Api>>]`
```

<p>How should I implement this according to Rust rules? Here is the code:</p>

```use std::{
    sync::{
        Arc,Mutex,
    },
    ptr,
    thread::{self},
};
pub struct OpaqWrapper {
    pub obj_ptr: *mut ::std::os::raw::c_void,
}
pub struct Api(OpaqWrapper);

fn spawn_api_thread(safe_obj: Arc<Mutex<Api>>) {
    thread::spawn(move || {
        {
            let my_api = safe_obj.lock().unwrap();
            // my_api.whatever();
        }
    });
}

fn main() {
    let api = Api(
        OpaqWrapper {
            obj_ptr: ptr::null_mut(),
        }
    );
    let shared_api= Arc::new(Mutex::new(api));
    for _ in 0..10 {
        spawn_api_thread(shared_api.clone());
    }
}
```

答:
Short version

Passing something to a thread requires that it be Send.

```<code>T:Send => Mutex<T>:Send+Sync =>  Arc<Mutex<T>>:Send
</code>```

so it is enough to mark Api as Send

Long version

Passing something to a thread requires that it be Send.

Arc<T> only automatically gets Send (and Sync) if T is Send and Sync. The source contains something like this:

```<code>unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
</code>```

However, Mutex only requires Send for it to be both Sync and Send, its code contains:

```<code>unsafe impl<T: ?Sized + Send> Send for Mutex<T> { }
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { }
</code>```

This means for Arc<Mutex<Api>> to be Sync, you need Mutex<Api> to be
 Sync+Send which will happen if Api is Send. To get this you need to mark either Api or OpaqWrapper as Send.

```<code>unsafe impl Send for Api {}
</code>```

Note you dont need to mark them as Sync as the Mutex gets that automatically.

Body:
I need to share an object created from C++ between Rust threads. I have wrapped it in a Mutex construct, so now it is safe to be sent between threads. However the compiler won't let me do what.

error[E0277]: `*mut std::ffi::c_void` cannot be sent between threads safely
   --> sendsync.rs:14:2
    |
14  |     thread::spawn(move || {
    |     ^^^^^^^^^^^^^ `*mut std::ffi::c_void` cannot be sent between threads safely
    |
    = help: within `Api`, the trait `std::marker::Send` is not implemented for `*mut std::ffi::c_void`
    = note: required because it appears within the type `OpaqWrapper`
    = note: required because it appears within the type `Api`
    = note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Mutex<Api>`
    = note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<std::sync::Mutex<Api>>`
    = note: required because it appears within the type `[closure@sendsync.rs:14:16: 19:3 safe_obj:std::sync::Arc<std::sync::Mutex<Api>>]`

How should I implement this according to Rust rules? Here is the code:

use std::{
    sync::{
        Arc,Mutex,
    },
    ptr,
    thread::{self},
};
pub struct OpaqWrapper {
    pub obj_ptr: *mut ::std::os::raw::c_void,
}
pub struct Api(OpaqWrapper);

fn spawn_api_thread(safe_obj: Arc<Mutex<Api>>) {
    thread::spawn(move || {
        {
            let my_api = safe_obj.lock().unwrap();
            // my_api.whatever();
        }
    });
}

fn main() {
    let api = Api(
        OpaqWrapper {
            obj_ptr: ptr::null_mut(),
        }
    );
    let shared_api= Arc::new(Mutex::new(api));
    for _ in 0..10 {
        spawn_api_thread(shared_api.clone());
    }
}

Body:
Short version

Passing something to a thread requires that it be Send.

T:Send => Mutex<T>:Send+Sync =>  Arc<Mutex<T>>:Send

so it is enough to mark Api as Send

Long version

Passing something to a thread requires that it be Send.

Arc<T> only automatically gets Send (and Sync) if T is Send and Sync. The source contains something like this:

unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}

However, Mutex only requires Send for it to be both Sync and Send, its code contains:

unsafe impl<T: ?Sized + Send> Send for Mutex<T> { }
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { }

This means for Arc<Mutex<Api>> to be Sync, you need Mutex<Api> to be
 Sync+Send which will happen if Api is Send. To get this you need to mark either Api or OpaqWrapper as Send.

unsafe impl Send for Api {}

Note you dont need to mark them as Sync as the Mutex gets that automatically.


问:
Flutter Flare animation not working properly
I am trying to get Flare animation working in Flutter.
For this, I tried this :
https://github.com/tarek360/Boring-Star-Animation

Actually, that code is working perfectly fine.
But, I wanted to change the animation to this :
https://www.2dimensions.com/a/innocent/files/flare/status_success

Now, the code runs and the animation is showed, but is still. (i.e., not animating, only the photo is displayed)
And I get below error:

```<code>E/flutter ( 7462): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '*' was called on null.
E/flutter ( 7462): Receiver: null
E/flutter ( 7462): Tried calling: *(0.0)
E/flutter ( 7462): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 7462): #1      KeyFrameStrokeEnd.setValue (package:flare_dart/animation/keyframe.dart:1161:33)
E/flutter ( 7462): #2      KeyFrameNumeric.apply (package:flare_dart/animation/keyframe.dart:138:5)
E/flutter ( 7462): #3      PropertyAnimation.apply (package:flare_dart/animation/actor_animation.dart:199:21)
E/flutter ( 7462): #4      ComponentAnimation.apply (package:flare_dart/animation/actor_animation.dart:248:27)
E/flutter ( 7462): #5      ActorAnimation.apply (package:flare_dart/animation/actor_animation.dart:403:26)
E/flutter ( 7462): #6      FlareActorRenderObject._updateAnimation (package:flare_flutter/flare_actor.dart:468:19)
E/flutter ( 7462): #7      FlareActorRenderObject.filename=.<anonymous closure> (package:flare_flutter/flare_actor.dart:245:11)
E/flutter ( 7462): #8      _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 7462): #9      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 7462): #10     _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
E/flutter ( 7462): #11     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
E/flutter ( 7462): #12     Future._propagateToListeners (dart:async/future_impl.dart:668:32)
E/flutter ( 7462): #13     Future._complete (dart:async/future_impl.dart:473:7)
E/flutter ( 7462): #14     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 7462): #15     _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async/runtime/libasync_patch.dart:33:20)
E/flutter ( 7462): #16     _rootRun (dart:async/zone.dart:1120:38)
E/flutter ( 7462): #17     _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 7462): #18     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 7462): #19     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter ( 7462): #20     _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 7462): #21     _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 7462): #22     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 7462): #23     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter ( 7462): #24     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 7462): #25     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
E/flutter ( 7462):
</code>```

I am very much sure that I did not mistype the filename and animation name.

Below is my main.dart file:

```<code>import 'package:flutter/material.dart';
import "package:flare_flutter/flare_actor.dart";

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'The Boring Star',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new FlareActor("animations/status_success.flr",
        alignment: Alignment.center,
        fit: BoxFit.contain,
        animation: "success_arrow");
  }
}
</code>```

-----EDIT-------
I don't know why, but below animation is working very nicely
https://www.2dimensions.com/a/pollux/files/flare/smiley-switch

So, it concludes that there is some problem with my animation :
https://www.2dimensions.com/a/innocent/files/flare/status_success

Can anyone help me with this?

答:
The name of the animation is not success_arrow but just success</p>

```<code>FlareActor("animations/status_success.flr",
        alignment: Alignment.center,
        fit: BoxFit.contain,
        animation: "success");
</code>```

Body:
I am trying to get Flare animation working in Flutter.
For this, I tried this :
https://github.com/tarek360/Boring-Star-Animation

Actually, that code is working perfectly fine.
But, I wanted to change the animation to this :
https://www.2dimensions.com/a/innocent/files/flare/status_success

Now, the code runs and the animation is showed, but is still. (i.e., not animating, only the photo is displayed)
And I get below error:

E/flutter ( 7462): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '*' was called on null.
E/flutter ( 7462): Receiver: null
E/flutter ( 7462): Tried calling: *(0.0)
E/flutter ( 7462): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 7462): #1      KeyFrameStrokeEnd.setValue (package:flare_dart/animation/keyframe.dart:1161:33)
E/flutter ( 7462): #2      KeyFrameNumeric.apply (package:flare_dart/animation/keyframe.dart:138:5)
E/flutter ( 7462): #3      PropertyAnimation.apply (package:flare_dart/animation/actor_animation.dart:199:21)
E/flutter ( 7462): #4      ComponentAnimation.apply (package:flare_dart/animation/actor_animation.dart:248:27)
E/flutter ( 7462): #5      ActorAnimation.apply (package:flare_dart/animation/actor_animation.dart:403:26)
E/flutter ( 7462): #6      FlareActorRenderObject._updateAnimation (package:flare_flutter/flare_actor.dart:468:19)
E/flutter ( 7462): #7      FlareActorRenderObject.filename=.<anonymous closure> (package:flare_flutter/flare_actor.dart:245:11)
E/flutter ( 7462): #8      _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 7462): #9      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 7462): #10     _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
E/flutter ( 7462): #11     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
E/flutter ( 7462): #12     Future._propagateToListeners (dart:async/future_impl.dart:668:32)
E/flutter ( 7462): #13     Future._complete (dart:async/future_impl.dart:473:7)
E/flutter ( 7462): #14     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 7462): #15     _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async/runtime/libasync_patch.dart:33:20)
E/flutter ( 7462): #16     _rootRun (dart:async/zone.dart:1120:38)
E/flutter ( 7462): #17     _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 7462): #18     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 7462): #19     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter ( 7462): #20     _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 7462): #21     _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 7462): #22     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 7462): #23     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter ( 7462): #24     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 7462): #25     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
E/flutter ( 7462):

I am very much sure that I did not mistype the filename and animation name.

Below is my main.dart file:

import 'package:flutter/material.dart';
import "package:flare_flutter/flare_actor.dart";

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'The Boring Star',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new FlareActor("animations/status_success.flr",
        alignment: Alignment.center,
        fit: BoxFit.contain,
        animation: "success_arrow");
  }
}

-----EDIT-------
I don't know why, but below animation is working very nicely
https://www.2dimensions.com/a/pollux/files/flare/smiley-switch

So, it concludes that there is some problem with my animation :
https://www.2dimensions.com/a/innocent/files/flare/status_success

Can anyone help me with this?

Body:
The name of the animation is not success_arrow but just success

FlareActor("animations/status_success.flr",
        alignment: Alignment.center,
        fit: BoxFit.contain,
        animation: "success");